narraleaf-react 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,80 +1,82 @@
1
- var ke={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},qt={say:"character:say",action:"character:action",setName:"character:setName"},X={action:"scene:action",init:"scene:init",exit:"scene:exit",jumpTo:"scene:jumpTo",setBackgroundMusic:"scene:setBackgroundMusic",preUnmount:"scene:preUnmount",transitionToScene:"scene:transitionToScene",nvlBlock:"scene:nvlBlock",nvlShow:"scene:nvlShow",nvlHide:"scene:nvlHide",nvlEnd:"scene:nvlEnd"};var at={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},os={action:"condition:action"},rs={action:"script:action"},ss={action:"menu:action"},xt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute",seek:"sound:seek"},ee={action:"control:action",do:"control:do",doAsync:"control:doAsync",any:"control:any",all:"control:all",allAsync:"control:allAsync",repeat:"control:repeat",while:"control:while",break:"control:break",sleep:"control:sleep",waitForClick:"control:waitForClick",label:"control:label",jump:"control:jump"},yi={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},Nn={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},sn={action:"layer:action",setZIndex:"layer:setZIndex"},Ct={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"},Qt={action:"vfx:action",show:"vfx:show",hide:"vfx:hide",pause:"vfx:pause",resume:"vfx:resume",setRate:"vfx:setRate"},Xe={action:"puppet:action",setMotion:"puppet:setMotion",setExpression:"puppet:setExpression",setSkin:"puppet:setSkin",setParam:"puppet:setParam",setSlot:"puppet:setSlot",command:"puppet:command"};var as=(p=>(p[p.string=0]="string",p[p.number=1]="number",p[p.boolean=2]="boolean",p[p.object=3]="object",p[p.array=4]="array",p[p.function=5]="function",p[p.symbol=6]="symbol",p[p.undefined=7]="undefined",p[p.null=8]="null",p[p.date=9]="date",p[p.regexp=10]="regexp",p[p.other=11]="other",p))(as||{}),Io=(function(o){return typeof o=="string"?0:typeof o=="number"?1:typeof o=="boolean"?2:typeof o=="object"?Array.isArray(o)?4:o===null?8:o instanceof Date?9:o instanceof RegExp?10:3:typeof o=="function"?5:typeof o=="symbol"?6:typeof o>"u"?7:11});Io.DataTypes=as;function z(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,c)=>Io(a)===3&&Io(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:z(a,c):Array.isArray(a)&&Array.isArray(c)?c&&c.length>0?[...c]:[...a]:a===void 0&&Array.isArray(c)?[...c]:c===void 0?Array.isArray(a)?[...a]:a:Array.isArray(c)?[...c]:c;for(let s in o)n(o,s)&&(i[s]=r(s,o[s],e[s]));for(let s in e)n(e,s)&&!n(i,s)&&(typeof e[s]=="object"&&e[s]!==null?e[s].constructor===Object?i[s]=z({},e[s]):Array.isArray(e[s])?i[s]=[...e[s]]:i[s]=e[s]:i[s]=e[s]);if(t.length){let[s,...a]=t;return z(i,s,...a)}return i}var $e=class $e{constructor(e=(n=>n),t){this.solved=!1;this.aborted=!1;this.failed=!1;this.error=null;this.listeners=[];this.failListeners=[];this.settledListeners=[];this.onRegisterSkipController=[];this.skipControllerAbortToken=null;this.settledNotified=!1;this.receiver=e,this.skipController=t,this.__stack=Ro()}static isAwaitable(e){return e instanceof $e}static fromPromise(e){let t=new $e;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new $e;return t.resolve(e),t}static delay(e){let t=new $e;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new $e;return e(t),t}static wait(e){let t=new $e;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new $e;return e.length===0?(t.resolve(void 0),t):(e.forEach(n=>{n.then(i=>{e.forEach(r=>{r!==n&&r.skipController?.abort()}),t.resolve(i)}),n.onFailed(i=>t.fail(i))}),t.registerSkipController(new H(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new $e().registerSkipController(n||new H(()=>t));e.then(()=>i.resolve(t)),e.onFailed(a=>i.fail(a));let r=e.skipController?.onAbort(()=>{i.skipController?.abort(),r?.cancel(),s?.cancel()}),s=i.skipController?.onAbort(()=>{e.skipController?.abort(),r?.cancel(),s?.cancel()});return i}static toPromise(e){return new Promise((t,n)=>{e.then(t),e.onFailed(n)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new $e;return e.length===0?(t.resolve(),t):(e.forEach(n=>{n.onSettled(()=>t.resolve()),n.onFailed(i=>{e.forEach(r=>{r!==n&&r.abort()}),t.fail(i)})}),t.registerSkipController(new H(()=>{e.forEach(n=>n.abort())})),t)}static all(...e){let t=new $e;if(e.length===0)return t.resolve(),t;let n=0;return e.forEach(i=>{i.onSettled(()=>{n++,n===e.length&&t.resolve()}),i.onFailed(r=>{e.forEach(s=>{s!==i&&s.abort()}),t.fail(r)})}),t.registerSkipController(new H(()=>{e.forEach(i=>i.abort())})),t}registerSkipController(e){this.skipControllerAbortToken?.cancel(),this.skipController=e,this.skipControllerAbortToken=e.onAbort(()=>{this.aborted=!0,this.notifySettled()});for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.isSettled()){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result);this.notifySettled()}}fail(e){if(!this.isSettled()){this.error=e,this.failed=!0,this.skipController&&this.skipController.cancel();for(let t of this.failListeners)t(e);this.notifySettled()}}then(e,t){return this.solved?e(this.result):this.failed?t?.(this.error):(this.pushListener(e),t&&this.pushFailListener(t)),this}onSettled(e){if(this.isSettled())e();else return this.settledListeners.push(e),{cancel:()=>{this.offSettledListener(e)}};return{cancel:()=>{}}}onFailed(e){if(this.failed)e(this.error);else if(!this.isSettled())return this.pushFailListener(e),{cancel:()=>{this.offFailListener(e)}};return{cancel:()=>{}}}onSkipControllerRegister(e){return this.skipController?e(this.skipController):this.onRegisterSkipController.push(e),{cancel:()=>{this.offSkipControllerRegister(e)}}}offSkipControllerRegister(e){let t=this.onRegisterSkipController.indexOf(e);return t!==-1&&this.onRegisterSkipController.splice(t,1),this}abort(){return this.isSettled()?this.result:(this.aborted=!0,this.skipController?this.skipController.abort():this.notifySettled(),this.result)}isSolved(){return this.solved&&!this.aborted&&!this.failed}isAborted(){return this.aborted}isFailed(){return this.failed}isSettled(){return this.solved||this.aborted||this.failed}pushListener(e){return this.listeners.length>=$e.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many listeners, this may cause performance issues."),this.listeners.push(e),this}pushFailListener(e){return this.failListeners.length>=$e.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many failure listeners, this may cause performance issues."),this.failListeners.push(e),this}offListener(e){let t=this.listeners.indexOf(e);return t!==-1&&this.listeners.splice(t,1),this}offFailListener(e){let t=this.failListeners.indexOf(e);return t!==-1&&this.failListeners.splice(t,1),this}offSettledListener(e){let t=this.settledListeners.indexOf(e);return t!==-1&&this.settledListeners.splice(t,1),this}notifySettled(){if(!this.settledNotified){this.settledNotified=!0;for(let e of this.settledListeners)e()}}};$e.nothing=e=>e,$e.maxListeners=8;var T=$e;function cs(o){let e=new WeakSet;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return;if(e.add(n),Array.isArray(n)){let r=[];for(let s of n)r.push(t(s));return r}let i={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=t(n[r]));return i}return t(o)}function vn(o){return typeof o=="string"?o:`#${(o.r||0).toString(16).padStart(2,"0")}${(o.g||0).toString(16).padStart(2,"0")}${(o.b||0).toString(16).padStart(2,"0")}${o.a===void 0?"":o.a.toString(16).padStart(2,"0")}`}var q=class{constructor(){this.events={};this.maxListeners=10}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this.events[e].length>this.maxListeners&&console.warn(`NarraLeaf-React: Event ${e} has more than ${this.maxListeners} listeners (total: ${this.events[e].length}), this may cause performance issues.`),this.emit("event:EventDispatcher.register",e,t),{type:e,listener:t,cancel:()=>{this.off(e,t)}}}depends(e){return{cancel:()=>{e.forEach(t=>t.cancel())}}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(n=>n!==t))}emit(e,...t){if(!this.events[e])return 0;let n=this.events[e].length;return this.events[e].forEach(i=>{i(...t)}),n}once(e,t){let n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n)}async any(e,...t){if(this.events[e]||(this.events[e]=[]),this.events[e].length>0){await Promise.all(this.events[e].map(n=>n(...t)));return}return new Promise(n=>{let i="event:EventDispatcher.register",r=this.on(i,(s,a)=>{if(s===e){this.off(i,r);let c=a?.(...t);c!==null&&typeof c=="object"&&c.then?c.then(n):n(c)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function Ro(o=1){let e=new Error().stack;return e?e.split(`
1
+ var Ee={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},zt={say:"character:say",action:"character:action",setName:"character:setName"},J={action:"scene:action",init:"scene:init",exit:"scene:exit",jumpTo:"scene:jumpTo",setBackgroundMusic:"scene:setBackgroundMusic",preUnmount:"scene:preUnmount",transitionToScene:"scene:transitionToScene",nvlBlock:"scene:nvlBlock",nvlShow:"scene:nvlShow",nvlHide:"scene:nvlHide",nvlEnd:"scene:nvlEnd"};var ut={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},fs={action:"condition:action"},hs={action:"script:action"},gs={action:"menu:action"},Pt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute",seek:"sound:seek"},ne={action:"control:action",do:"control:do",doAsync:"control:doAsync",any:"control:any",all:"control:all",allAsync:"control:allAsync",repeat:"control:repeat",while:"control:while",break:"control:break",sleep:"control:sleep",waitForClick:"control:waitForClick",label:"control:label",jump:"control:jump"},Ai={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},Fn={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},un={action:"layer:action",setZIndex:"layer:setZIndex"},Et={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"},Jt={action:"vfx:action",show:"vfx:show",hide:"vfx:hide",pause:"vfx:pause",resume:"vfx:resume",setRate:"vfx:setRate"},_e={action:"puppet:action",setMotion:"puppet:setMotion",setExpression:"puppet:setExpression",setSkin:"puppet:setSkin",setParam:"puppet:setParam",setSlot:"puppet:setSlot",command:"puppet:command"};var ys=(p=>(p[p.string=0]="string",p[p.number=1]="number",p[p.boolean=2]="boolean",p[p.object=3]="object",p[p.array=4]="array",p[p.function=5]="function",p[p.symbol=6]="symbol",p[p.undefined=7]="undefined",p[p.null=8]="null",p[p.date=9]="date",p[p.regexp=10]="regexp",p[p.other=11]="other",p))(ys||{}),Ho=(function(o){return typeof o=="string"?0:typeof o=="number"?1:typeof o=="boolean"?2:typeof o=="object"?Array.isArray(o)?4:o===null?8:o instanceof Date?9:o instanceof RegExp?10:3:typeof o=="function"?5:typeof o=="symbol"?6:typeof o>"u"?7:11});Ho.DataTypes=ys;function z(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,c)=>Ho(a)===3&&Ho(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:z(a,c):Array.isArray(a)&&Array.isArray(c)?c&&c.length>0?[...c]:[...a]:a===void 0&&Array.isArray(c)?[...c]:c===void 0?Array.isArray(a)?[...a]:a:Array.isArray(c)?[...c]:c;for(let s in o)n(o,s)&&(i[s]=r(s,o[s],e[s]));for(let s in e)n(e,s)&&!n(i,s)&&(typeof e[s]=="object"&&e[s]!==null?e[s].constructor===Object?i[s]=z({},e[s]):Array.isArray(e[s])?i[s]=[...e[s]]:i[s]=e[s]:i[s]=e[s]);if(t.length){let[s,...a]=t;return z(i,s,...a)}return i}var Qe=class Qe{constructor(e=(n=>n),t){this.solved=!1;this.aborted=!1;this.failed=!1;this.error=null;this.listeners=[];this.failListeners=[];this.settledListeners=[];this.onRegisterSkipController=[];this.skipControllerAbortToken=null;this.settledNotified=!1;this.receiver=e,this.skipController=t,this.__stack=Fo()}static isAwaitable(e){return e instanceof Qe}static fromPromise(e){let t=new Qe;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new Qe;return t.resolve(e),t}static delay(e){let t=new Qe;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new Qe;return e(t),t}static wait(e){let t=new Qe;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new Qe;return e.length===0?(t.resolve(void 0),t):(e.forEach(n=>{n.then(i=>{e.forEach(r=>{r!==n&&r.skipController?.abort()}),t.resolve(i)}),n.onFailed(i=>t.fail(i))}),t.registerSkipController(new V(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new Qe().registerSkipController(n||new V(()=>t));e.then(()=>i.resolve(t)),e.onFailed(a=>i.fail(a));let r=e.skipController?.onAbort(()=>{i.skipController?.abort(),r?.cancel(),s?.cancel()}),s=i.skipController?.onAbort(()=>{e.skipController?.abort(),r?.cancel(),s?.cancel()});return i}static toPromise(e){return new Promise((t,n)=>{e.then(t),e.onFailed(n)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new Qe;return e.length===0?(t.resolve(),t):(e.forEach(n=>{n.onSettled(()=>t.resolve()),n.onFailed(i=>{e.forEach(r=>{r!==n&&r.abort()}),t.fail(i)})}),t.registerSkipController(new V(()=>{e.forEach(n=>n.abort())})),t)}static all(...e){let t=new Qe;if(e.length===0)return t.resolve(),t;let n=0;return e.forEach(i=>{i.onSettled(()=>{n++,n===e.length&&t.resolve()}),i.onFailed(r=>{e.forEach(s=>{s!==i&&s.abort()}),t.fail(r)})}),t.registerSkipController(new V(()=>{e.forEach(i=>i.abort())})),t}registerSkipController(e){this.skipControllerAbortToken?.cancel(),this.skipController=e,this.skipControllerAbortToken=e.onAbort(()=>{this.aborted=!0,this.notifySettled()});for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.isSettled()){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result);this.notifySettled()}}fail(e){if(!this.isSettled()){this.error=e,this.failed=!0,this.skipController&&this.skipController.cancel();for(let t of this.failListeners)t(e);this.notifySettled()}}then(e,t){return this.solved?e(this.result):this.failed?t?.(this.error):(this.pushListener(e),t&&this.pushFailListener(t)),this}onSettled(e){if(this.isSettled())e();else return this.settledListeners.push(e),{cancel:()=>{this.offSettledListener(e)}};return{cancel:()=>{}}}onFailed(e){if(this.failed)e(this.error);else if(!this.isSettled())return this.pushFailListener(e),{cancel:()=>{this.offFailListener(e)}};return{cancel:()=>{}}}onSkipControllerRegister(e){return this.skipController?e(this.skipController):this.onRegisterSkipController.push(e),{cancel:()=>{this.offSkipControllerRegister(e)}}}offSkipControllerRegister(e){let t=this.onRegisterSkipController.indexOf(e);return t!==-1&&this.onRegisterSkipController.splice(t,1),this}abort(){return this.isSettled()?this.result:(this.aborted=!0,this.skipController?this.skipController.abort():this.notifySettled(),this.result)}isSolved(){return this.solved&&!this.aborted&&!this.failed}isAborted(){return this.aborted}isFailed(){return this.failed}isSettled(){return this.solved||this.aborted||this.failed}pushListener(e){return this.listeners.length>=Qe.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many listeners, this may cause performance issues."),this.listeners.push(e),this}pushFailListener(e){return this.failListeners.length>=Qe.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many failure listeners, this may cause performance issues."),this.failListeners.push(e),this}offListener(e){let t=this.listeners.indexOf(e);return t!==-1&&this.listeners.splice(t,1),this}offFailListener(e){let t=this.failListeners.indexOf(e);return t!==-1&&this.failListeners.splice(t,1),this}offSettledListener(e){let t=this.settledListeners.indexOf(e);return t!==-1&&this.settledListeners.splice(t,1),this}notifySettled(){if(!this.settledNotified){this.settledNotified=!0;for(let e of this.settledListeners)e()}}};Qe.nothing=e=>e,Qe.maxListeners=8;var T=Qe;function vs(o){let e=new WeakSet;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return;if(e.add(n),Array.isArray(n)){let r=[];for(let s of n)r.push(t(s));return r}let i={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=t(n[r]));return i}return t(o)}function An(o){return typeof o=="string"?o:`#${(o.r||0).toString(16).padStart(2,"0")}${(o.g||0).toString(16).padStart(2,"0")}${(o.b||0).toString(16).padStart(2,"0")}${o.a===void 0?"":o.a.toString(16).padStart(2,"0")}`}var Q=class{constructor(){this.events={};this.maxListeners=10}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this.events[e].length>this.maxListeners&&console.warn(`NarraLeaf-React: Event ${e} has more than ${this.maxListeners} listeners (total: ${this.events[e].length}), this may cause performance issues.`),this.emit("event:EventDispatcher.register",e,t),{type:e,listener:t,cancel:()=>{this.off(e,t)}}}depends(e){return{cancel:()=>{e.forEach(t=>t.cancel())}}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(n=>n!==t))}emit(e,...t){if(!this.events[e])return 0;let n=this.events[e].length;return this.events[e].forEach(i=>{i(...t)}),n}once(e,t){let n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n)}async any(e,...t){if(this.events[e]||(this.events[e]=[]),this.events[e].length>0){await Promise.all(this.events[e].map(n=>n(...t)));return}return new Promise(n=>{let i="event:EventDispatcher.register",r=this.on(i,(s,a)=>{if(s===e){this.off(i,r);let c=a?.(...t);c!==null&&typeof c=="object"&&c.then?c.then(n):n(c)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function Fo(o=1){let e=new Error().stack;return e?e.split(`
2
2
  `).slice(o+1).join(`
3
- `).trim():""}function Ci(o){return new Promise(e=>setTimeout(e,o))}var xi=class xi{constructor(e){this.abortHandler=e;this.events=new q;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(xi.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};xi.EventTypes={"event:skipController.abort":"event:skipController.abort"};var H=xi;var Gn=class{constructor(){this.locked=!1;this.listeners=[];this.unlockListeners=[]}lock(){return this.locked=!0,this}unlock(){this.locked=!1;for(let e of this.listeners)e();for(let e of this.unlockListeners)e();return this.listeners=[],this}onUnlock(e){return this.unlockListeners.push(e),e}offUnlock(e){this.unlockListeners=this.unlockListeners.filter(t=>t!==e)}async nextUnlock(){if(this.locked)return new Promise(e=>{this.listeners.push(e)})}isLocked(){return this.locked}},gn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Gn;return this.locks.push(t),t}off(e){this.locks=this.locks.filter(t=>t!==e)}async nextUnlock(){let e=this.locks.map(t=>t.nextUnlock());return Promise.all(e)}isLocked(){return this.locks.some(e=>e.isLocked())}};function wi(o,e,t={}){return o?e:t}function ls(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var vi=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function us(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function ps(o,e){return new Promise((t,n)=>{fetch(o,e).then(i=>i.blob()).then(i=>{let r=new FileReader;r.onload=()=>{t(r.result)},r.readAsDataURL(i)}).catch(n)})}var yn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}get size(){return this.tasks.length}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),this.tasks.length!==0&&(await Ci(this.delay),await e())};await e()}};function nt(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function ds(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var tt=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function ms(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function fs(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function Mo(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function No(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!No(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Si=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function ki(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function hs(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Ti=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},bi=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var Ai=class{constructor(e){this.items=[];this.pushValidator=[];e&&(this.items=[...e])}addPushValidator(e){return this.pushValidator.push(e),this}removePushValidator(e){this.pushValidator=this.pushValidator.filter(t=>t!==e)}push(...e){for(let t of e)this.pushValidator.some(n=>!n(t))||this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}toArray(){return[...this.items]}forEach(e){this.items.forEach(e)}forEachReverse(e){for(let t=this.items.length-1;t>=0;t--)e(this.items[t])}map(e){return this.items.map(e)}get(e){return this.items[e]}};function gs(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function ys(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,c=16777216,l=r*a>>>0,u=r*c+s*a>>>0,d=s*c+(u>>>0)>>>0;e=l,t=d}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Vn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Ro(),this._id="",this._staticId=null}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};Vn.ActionTypes={action:"action"};var $=class extends Vn{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new T(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var Go=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},w=class o extends Go{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var Pi={center:"center",left:"left",right:"right"};import{animate as Sc}from"motion/react";var Sn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(Sn||{}),vs={left:"33.33%",center:"50%",right:"66.66%"},ct=class ct{static isUnknown(e){return e===ct.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},c=t?{right:s}:{left:s};return this.wrap({...a,...c})}static calc(e,t,n){if(!e||ct.isUnknown(e))return"auto";let i=!(t===void 0||ct.isUnknown(t));if(typeof n=="number"&&n>0){let s=ct.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}return i?`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`:`calc(${e} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(it.isCommonPositionType(e))return lt.fromCommonPosition(e);if(lt.isCoord2DPosition(e))return e;if(an.isAlignPosition(e))return lt.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return ct.isUnknown(e)||e===void 0?ct.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return lt.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:ct.isUnknown(t.x)?0:t.x,y:ct.isUnknown(t.y)?0:t.y,xoffset:ct.isUnknown(t.xoffset)?0:t.xoffset,yoffset:ct.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(Sn).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof it||e instanceof lt||e instanceof an}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return lt.fromCommonPosition(new it(e));if(this.isRawAlignPosition(e))return lt.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new lt(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};ct.Unknown=Symbol("Unknown");var N=ct,Ei=class Ei{static isCommonPositionType(e){return e instanceof Ei}constructor(e){this.position=e}toCSS(){return{x:vs[this.position],y:"50%",xoffset:0,yoffset:0}}};Ei.Positions=Sn;var it=Ei,lt=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:vs[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||N.isUnknown(n)?N.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:N.isUnknown(t.x)?e.x:t.x,y:N.isUnknown(t.y)?e.y:t.y,xoffset:N.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:N.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=N.orUnknown(e.x),this.y=N.orUnknown(e.y),this.xoffset=N.orUnknown(e.xoffset),this.yoffset=N.orUnknown(e.yoffset)):(this.x=N.orUnknown(e),this.y=N.orUnknown(t),this.xoffset=N.Unknown,this.yoffset=N.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},an=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=N.orUnknown(e.xalign),this.yalign=N.orUnknown(e.yalign),this.xoffset=N.orUnknown(e.xoffset),this.yoffset=N.orUnknown(e.yoffset)):(this.xalign=N.orUnknown(e),this.yalign=N.orUnknown(t),this.xoffset=N.Unknown,this.yoffset=N.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:N.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:N.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var B=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Vo(this.mergeWithDefaultConfig(e))}copy(){return new o(z({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?z({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},Vo=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(z({},this.config))}join(e){let t=ds(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var Tc={[Pi.left]:"25.33%",[Pi.center]:"50%",[Pi.right]:"75.66%"},ht=class ht{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new ht(ht.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?N.toCoord2D(N.tryParsePosition(e||t)):N.mergePosition(N.tryParsePosition(e),N.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=ht.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return Mo(Y.constructStyle(e,this.state,t))}toStyle(e,t){return Mo(Y.constructStyle(e,this.state,t))}serialize(){return ht.TransformStateSerializer.serialize(this.state)}clone(){return new ht(ht.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=ht.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};ht.DefaultTransformState=new B({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new it("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),ht.TransformStateSerializer=new tt({position:e=>N.serializePosition(N.tryParsePosition(e))},{position:e=>N.toCoord2D(e)});var Q=ht,Pe=class Pe{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Pe.defaultConfig,t||{});else{let[n,i]=[e,t||Pe.defaultOptions];this.sequences.push({props:n,options:i||Pe.defaultOptions}),this.config=Object.assign({},Pe.defaultConfig)}}static isPosition(e){return it.isCommonPositionType(e)||lt.isCoord2DPosition(e)||an.isAlignPosition(e)}static immediate(e){return new Pe(e,{duration:0,ease:"linear"})}static left(e,t){return new Pe({position:it.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Pe({position:it.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Pe({position:it.Positions.Center},{duration:e,ease:t})}static create(e){return new Pe([],e)}static positionToCSS(e,t,n,i){return e?N.isRawPosition(e)?N.D2PositionToCSS(N.rawPositionToCoord2D(e),n,t,i):N.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?N.toCoord2D(N.tryParsePosition(e||t)):N.mergePosition(N.tryParsePosition(e),N.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...z(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(p,g,y){return typeof p>"u"?typeof y<"u"?g(y):"":g(p)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,p=>`rotate(${p}deg)`,0),c(t.scaleX,p=>`scaleX(${p*a})`,1),c(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,c=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...Pe.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?vn(t.fontColor):void 0,transform:Pe.propToCSSTransform(e,t),...Pe.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,WebkitMaskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:r,sequences:s,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current});s.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),u=Sc(s,a),d=()=>{e.overwrite(l,r.get()).unlock(l),u.complete(),c=!0},p=new T().registerSkipController(new H(d)),g=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),p.resolve()};return u.then(g,(y=>{t.logger.error("Failed to animate transform. "+(y?.toString?.()||""));try{g()}catch{p.resolve()}})),u.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),p}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Pe.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i}){let r=t.clone(),s=r.lock(),a=this.sequences.map(({props:c,options:l})=>{let u=r.assign(s,c).toFramesDefinition(e,n);return[i,u,this.getOptions(l)]});return{finalState:r.unlock(s).freeze(),sequences:a,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new Pe(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new te("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new te("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};Pe.defaultConfig={sync:!0},Pe.defaultOptions={duration:0,ease:"linear"},Pe.CommonImagePositionMap=Tc;var Y=Pe;var Di=class{constructor(){this.id="";this._staticId=null}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}reset(){}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var Ss=Symbol("_Chained"),Ts;Ts=Ss;var Fo=class Fo{constructor(e){this[Ts]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Ss]}static toActions(e){return e.flat(2).map(t=>Fo.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},Ve=Fo,Tn=class extends Di{chain(e){let t=Ve.isChained(this)?this:this.proxy(this,new Ve(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var ae=class extends Tn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var wt=class extends ${executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",c=s.action?s.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};wt.ActionTypes=os;var Fn=64;function As(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function Ho(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Li(o,e=0,t=new Set){if(e>Fn)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Li(n,e+1,t)):As(o)?Object.values(o).every(n=>Li(n,e+1,t)):!1}finally{t.delete(o)}}function xs(o,e){let t=[],n=[];return{data:Uo(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function Uo(o,e,t,n,i,r,s){if(t>Fn)throw new L(`A stored value nests deeper than ${Fn} levels and cannot be saved
4
- at ${s}, ${Ho(e)}
3
+ `).trim():""}function Di(o){return new Promise(e=>setTimeout(e,o))}var Ei=class Ei{constructor(e){this.abortHandler=e;this.events=new Q;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Ei.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Ei.EventTypes={"event:skipController.abort":"event:skipController.abort"};var V=Ei;var Un=class{constructor(){this.locked=!1;this.listeners=[];this.unlockListeners=[]}lock(){return this.locked=!0,this}unlock(){this.locked=!1;for(let e of this.listeners)e();for(let e of this.unlockListeners)e();return this.listeners=[],this}onUnlock(e){return this.unlockListeners.push(e),e}offUnlock(e){this.unlockListeners=this.unlockListeners.filter(t=>t!==e)}async nextUnlock(){if(this.locked)return new Promise(e=>{this.listeners.push(e)})}isLocked(){return this.locked}},Tn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Un;return this.locks.push(t),t}off(e){this.locks=this.locks.filter(t=>t!==e)}async nextUnlock(){let e=this.locks.map(t=>t.nextUnlock());return Promise.all(e)}isLocked(){return this.locks.some(e=>e.isLocked())}};function Li(o,e,t={}){return o?e:t}function Ss(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var xi=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function Ts(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function bs(o,e){return new Promise((t,n)=>{fetch(o,e).then(i=>i.blob()).then(i=>{let r=new FileReader;r.onload=()=>{t(r.result)},r.readAsDataURL(i)}).catch(n)})}var bn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}get size(){return this.tasks.length}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),this.tasks.length!==0&&(await Di(this.delay),await e())};await e()}};function rt(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function As(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var Xe=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function xs(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function Cs(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function Uo(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function Oo(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!Oo(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Ci=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Ii(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function ws(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var wi=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},ki=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var Pi=class{constructor(e){this.items=[];this.pushValidator=[];e&&(this.items=[...e])}addPushValidator(e){return this.pushValidator.push(e),this}removePushValidator(e){this.pushValidator=this.pushValidator.filter(t=>t!==e)}push(...e){for(let t of e)this.pushValidator.some(n=>!n(t))||this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}toArray(){return[...this.items]}forEach(e){this.items.forEach(e)}forEachReverse(e){for(let t=this.items.length-1;t>=0;t--)e(this.items[t])}map(e){return this.items.map(e)}get(e){return this.items[e]}};function ks(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function Ps(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,c=16777216,l=r*a>>>0,u=r*c+s*a>>>0,d=s*c+(u>>>0)>>>0;e=l,t=d}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var On=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Fo(),this._id="",this._staticId=null}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};On.ActionTypes={action:"action"};var $=class extends On{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new T(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var Bo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},C=class o extends Bo{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var Ri={center:"center",left:"left",right:"right"};import{animate as Dc}from"motion/react";var xn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(xn||{}),Es={left:"33.33%",center:"50%",right:"66.66%"},pt=class pt{static isUnknown(e){return e===pt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},c=t?{right:s}:{left:s};return this.wrap({...a,...c})}static calc(e,t,n){if(!e||pt.isUnknown(e))return"auto";let i=!(t===void 0||pt.isUnknown(t));if(typeof n=="number"&&n>0){let s=pt.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}return i?`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`:`calc(${e} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(st.isCommonPositionType(e))return dt.fromCommonPosition(e);if(dt.isCoord2DPosition(e))return e;if(pn.isAlignPosition(e))return dt.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return pt.isUnknown(e)||e===void 0?pt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return dt.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:pt.isUnknown(t.x)?0:t.x,y:pt.isUnknown(t.y)?0:t.y,xoffset:pt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:pt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(xn).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof st||e instanceof dt||e instanceof pn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return dt.fromCommonPosition(new st(e));if(this.isRawAlignPosition(e))return dt.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new dt(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};pt.Unknown=Symbol("Unknown");var R=pt,Mi=class Mi{static isCommonPositionType(e){return e instanceof Mi}constructor(e){this.position=e}toCSS(){return{x:Es[this.position],y:"50%",xoffset:0,yoffset:0}}};Mi.Positions=xn;var st=Mi,dt=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:Es[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||R.isUnknown(n)?R.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:R.isUnknown(t.x)?e.x:t.x,y:R.isUnknown(t.y)?e.y:t.y,xoffset:R.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:R.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=R.orUnknown(e.x),this.y=R.orUnknown(e.y),this.xoffset=R.orUnknown(e.xoffset),this.yoffset=R.orUnknown(e.yoffset)):(this.x=R.orUnknown(e),this.y=R.orUnknown(t),this.xoffset=R.Unknown,this.yoffset=R.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},pn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=R.orUnknown(e.xalign),this.yalign=R.orUnknown(e.yalign),this.xoffset=R.orUnknown(e.xoffset),this.yoffset=R.orUnknown(e.yoffset)):(this.xalign=R.orUnknown(e),this.yalign=R.orUnknown(t),this.xoffset=R.Unknown,this.yoffset=R.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:R.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:R.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var K=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Ko(this.mergeWithDefaultConfig(e))}copy(){return new o(z({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?z({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},Ko=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(z({},this.config))}join(e){let t=As(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var Lc={[Ri.left]:"25.33%",[Ri.center]:"50%",[Ri.right]:"75.66%"},St=class St{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new St(St.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?R.toCoord2D(R.tryParsePosition(e||t)):R.mergePosition(R.tryParsePosition(e),R.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=St.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return Uo(_.constructStyle(e,this.state,t))}toStyle(e,t){return Uo(_.constructStyle(e,this.state,t))}serialize(){return St.TransformStateSerializer.serialize(this.state)}clone(){return new St(St.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=St.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};St.DefaultTransformState=new K({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new st("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),St.TransformStateSerializer=new Xe({position:e=>R.serializePosition(R.tryParsePosition(e))},{position:e=>R.toCoord2D(e)});var Y=St,De=class De{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},De.defaultConfig,t||{});else{let[n,i]=[e,t||De.defaultOptions];this.sequences.push({props:n,options:i||De.defaultOptions}),this.config=Object.assign({},De.defaultConfig)}}static isPosition(e){return st.isCommonPositionType(e)||dt.isCoord2DPosition(e)||pn.isAlignPosition(e)}static immediate(e){return new De(e,{duration:0,ease:"linear"})}static left(e,t){return new De({position:st.Positions.Left},{duration:e,ease:t})}static right(e,t){return new De({position:st.Positions.Right},{duration:e,ease:t})}static center(e,t){return new De({position:st.Positions.Center},{duration:e,ease:t})}static create(e){return new De([],e)}static positionToCSS(e,t,n,i){return e?R.isRawPosition(e)?R.D2PositionToCSS(R.rawPositionToCoord2D(e),n,t,i):R.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?R.toCoord2D(R.tryParsePosition(e||t)):R.mergePosition(R.tryParsePosition(e),R.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...z(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(p,g,h){return typeof p>"u"?typeof h<"u"?g(h):"":g(p)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,p=>`rotate(${p}deg)`,0),c(t.scaleX,p=>`scaleX(${p*a})`,1),c(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,c=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...De.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?An(t.fontColor):void 0,transform:De.propToCSSTransform(e,t),...De.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,WebkitMaskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:r,sequences:s,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current});s.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),u=Dc(s,a),d=()=>{e.overwrite(l,r.get()).unlock(l),u.complete(),c=!0},p=new T().registerSkipController(new V(d)),g=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),p.resolve()};return u.then(g,(h=>{t.logger.error("Failed to animate transform. "+(h?.toString?.()||""));try{g()}catch{p.resolve()}})),u.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),p}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...De.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i}){let r=t.clone(),s=r.lock(),a=this.sequences.map(({props:c,options:l})=>{let u=r.assign(s,c).toFramesDefinition(e,n);return[i,u,this.getOptions(l)]});return{finalState:r.unlock(s).freeze(),sequences:a,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new De(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new ie("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new ie("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};De.defaultConfig={sync:!0},De.defaultOptions={duration:0,ease:"linear"},De.CommonImagePositionMap=Lc;var _=De;var Ni=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var Ds=Symbol("_Chained"),Ls;Ls=Ds;var Wo=class Wo{constructor(e){this[Ls]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Ds]}static toActions(e){return e.flat(2).map(t=>Wo.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},Oe=Wo,Cn=class extends Ni{chain(e){let t=Oe.isChained(this)?this:this.proxy(this,new Oe(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var ue=class extends Cn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Dt=class extends ${executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",c=s.action?s.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Dt.ActionTypes=fs;var Bn=64;function Rs(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function zo(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Gi(o,e=0,t=new Set){if(e>Bn)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Gi(n,e+1,t)):Rs(o)?Object.values(o).every(n=>Gi(n,e+1,t)):!1}finally{t.delete(o)}}function Ms(o,e){let t=[],n=[];return{data:$o(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function $o(o,e,t,n,i,r,s){if(t>Bn)throw new P(`A stored value nests deeper than ${Bn} levels and cannot be saved
4
+ at ${s}, ${zo(e)}
5
5
  A saved game this deep is almost always a data-structure bug. Flatten the value,
6
- or keep the deep part outside the store and save an id for it.`);if(o===void 0)return r.push([...e]),null;if(o===null)return null;if(o instanceof Date)return i.push([...e]),o.toISOString();if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="object"){if(n.has(o))throw new L(`A stored value refers back to itself and cannot be saved
7
- at ${s}, ${Ho(e)}
6
+ or keep the deep part outside the store and save an id for it.`);if(o===void 0)return r.push([...e]),null;if(o===null)return null;if(o instanceof Date)return i.push([...e]),o.toISOString();if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="object"){if(n.has(o))throw new P(`A stored value refers back to itself and cannot be saved
7
+ at ${s}, ${zo(e)}
8
8
  A saved game is a tree. Cutting the back-edge would save a different object graph
9
9
  than the one you built, so this is refused rather than guessed at \u2014 break the
10
- reference, or store an id in place of the object.`);if(Array.isArray(o)||As(o)){n.add(o);try{if(Array.isArray(o))return o.map((c,l)=>Uo(c,[...e,l],t+1,n,i,r,s));let a={};return Object.entries(o).forEach(([c,l])=>{a[c]=Uo(l,[...e,c],t+1,n,i,r,s)}),a}finally{n.delete(o)}}}return console.warn(`Value of type "${bc(o)}" cannot be saved and was stored as null
11
- at ${s}, ${Ho(e)}`),null}function bc(o){return typeof o!="object"||o===null?typeof o:o.constructor?.name??"object"}function Cs(o,e,t){let n=bs(o,e,Oo);return n=bs(n,t,()=>{}),n}function bs(o,e,t){if(!Array.isArray(e)||!e.length)return o;let n=o;for(let i of e){if(!Array.isArray(i))continue;if(!i.length){n=t(n);continue}let r=n;for(let a=0;a<i.length-1&&r!==null&&typeof r=="object";a++)r=r[i[a]];if(r===null||typeof r!="object")continue;let s=i[i.length-1];r[s]=t(r[s])}return n}function Oo(o){return o instanceof Date?o:typeof o=="string"||typeof o=="number"?new Date(o):new Date(NaN)}function ws(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function Ko(o,e,t=0){if(Object.is(o,e))return!0;if(t>Fn)return!1;if(o instanceof Date||e instanceof Date)return o instanceof Date&&e instanceof Date&&o.getTime()===e.getTime();if(Array.isArray(o)||Array.isArray(e))return Array.isArray(o)&&Array.isArray(e)&&o.length===e.length&&o.every((n,i)=>Ko(n,e[i],t+1));if(ws(o)&&ws(e)){let n=Object.keys(o);return n.length===Object.keys(e).length&&n.every(i=>Object.prototype.hasOwnProperty.call(e,i)&&Ko(o[i],e[i],t+1))}return!1}var kt=class o{constructor(e,t,n){this.owner=null;this.name=e,this.key=n||e,this.content=z({},t),this.defaultContent=t}static isSerializable(e){return Li(e)}set(e,t){let n=this.content[e];return o.isSerializable(t)?(this.content[e]=t,this.reportChange(e,n,t),this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
12
- at namespace "${this.name}"`),this.content[e]=t,this.reportChange(e,n,t),this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){let e=this.content;return this.content=z({},this.defaultContent),new Set([...Object.keys(e),...Object.keys(this.content)]).forEach(n=>{this.reportChange(n,e[n],this.content[n])}),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content={},this.deserialize(e)}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n,t)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)}),this.owner?.reportRestore(this.key)}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e,t){let n=`namespace "${this.name}"`+(t===void 0?"":`, key "${t}"`),i={any:s=>{let a=xs(s,n),c={type:"any",data:a.data};return a.dates.length&&(c.dates=a.dates),a.undefineds.length&&(c.undefineds=a.undefineds),c},date:s=>({type:"date",data:s.toISOString()})},r=this.toTypeName(e);return i[r](e)}unwrap(e){let n={any:i=>Cs(i.data,i.dates,i.undefineds),date:i=>Oo(i.data)}[e?.type];return n?n(e):(console.warn(`Unknown stored value type "${e?.type}", reading it as-is
13
- at namespace "${this.name}"`),e?.data)}attach(e){return this.owner=e,this}detach(e){return this.owner===e&&(this.owner=null),this}reportChange(e,t,n){!this.owner||Ko(t,n)||this.owner.reportChange({namespace:this.key,key:String(e),previous:t,next:n})}},Xt=class Xt{constructor(){this.events=new q;this.namespaces={};this.restoreBatch=null;this.events.setMaxListeners(64)}static createNamespace(e,t,n){return new kt(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,e.attach(this),this}getNamespace(e){if(!this.namespaces[e])throw new L(`Namespace ${e} is not initialized, did you forget to register it?
14
- Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new L("No listener provided when subscribing to storable changes");return this.events.on(Xt.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(Xt.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new kt(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(Xt.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(Xt.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(Xt.EventTypes["event:storable.restore"],{namespaces:[e]})}};Xt.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var Hn=Xt;var Je=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===xt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===xt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===xt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=T.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===xt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===xt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===xt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===xt.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=T.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===xt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};Je.ActionTypes=xt;var Ye={bgm:"bgm",sound:"sound",voice:"voice"},Ii=8,Jt=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function bn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var On=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=c=>{t.set(c.id,{id:c.id,parentId:c.parentId??null,volume:bn(c.volume)})};Object.values(Ye).forEach(c=>n({id:c}));let i=new Set;e.forEach(c=>{let l=c?.id;if(typeof l!="string"||l.trim().length===0)throw new Jt(`Audio bus id must be a non-empty string, got ${JSON.stringify(l)}.`);if(i.has(l))throw new Jt(`Audio bus "${l}" is declared more than once.`);i.add(l),n(c)}),o.assertResolvable(t);let r=[],s=new Map,a=c=>{let l=s.get(c);if(l)return l;let u=t.get(c),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(c,p),r.push(p),p};return t.forEach(c=>a(c.id)),new o(r,s)}static isSeeded(e){return Object.values(Ye).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new Jt(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new Jt(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>Ii)throw new Jt(`Audio bus "${t.id}" nests deeper than ${Ii}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=Ii;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},Bo=On.resolve();function Ac(o){Bo=o}function Wo(){return Bo}function Ri(o,e){let t=Bo;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var ks={[Ye.bgm]:"bgmVolume",[Ye.sound]:"soundVolume",[Ye.voice]:"voiceVolume"};function Ps(o){let e={};return Object.entries(ks).forEach(([t,n])=>{e[t]={get:()=>bn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var Un=class Un{constructor(e,t={}){this.declarations=e;this.events=new q;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,bn(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(Un.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=On.resolve(this.declarations()??[]),Ac(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=bn(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?bn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return bn(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(Un.EventTypes["event:audioBus.volumeChange"],e)}};Un.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var Kn=Un;var Es=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Es||{}),xe=class xe extends ae{static toSound(e){return e==null?null:typeof e=="string"?new xe({src:e}):e}static isSound(e){return e instanceof xe}static voice(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=xe.DefaultUserConfig.create(t),[i]=n.extract(xe.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){return Wo().isUnder(this.config.type,Ye.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(Je.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(Je.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(Je.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(Je.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(Je.ActionTypes.setRate,[e])}pause(e){return this.pushAction(Je.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(Je.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(Je.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:xe.StateSerializer.serialize(this.state)}}fromData(e){return this.state=xe.StateSerializer.deserialize(e.state),this}copy(){return new xe(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return xe.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new Je(this.chain(),e,new w().setContent(t)))}};xe.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",xe.DefaultUserConfig=new B({src:xe.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultConfig=new B({src:xe.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultState=new B({volume:1,rate:1,paused:!1,muted:!1}),xe.StateSerializer=new tt;var Ae=xe;var Ds=2;var Dd={};var An=class extends Tn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let c=a.getFutureActions(e,i).filter(l=>!r.has(l));s.push(...c)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var cn=class cn{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===cn.SrcTypes.image?t.add(s):r===cn.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof R?R.getSrcURL(e):e.type==="image"?R.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(ce,X.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(k.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof ge){let n=t;if(t.is(ge,at.setSrc)){let i=t.contentNode.getContent()[0];if(k.isImageSrc(i))return{type:"image",src:k.srcToURL(i),activeType:"scene"}}else{if(t.type===at.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===at.setAppearance){let i=t.contentNode.getContent()[0];if(R.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(R.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:R.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof Ae){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof R||k.isStaticImageData(e)){if(e instanceof R){if(!k.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(R.getSrcURL(e)))return this}else if(this.isSrcRegistered(k.srcToURL(e.src)))return this;this.src.push({type:"image",src:k.isStaticImageData(e)?k.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof Ae?t:new Ae({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof Ae?e.getSrc():e;return this.src.some(n=>n.type===cn.SrcTypes.audio?t===n.src.getSrc():n.type===cn.SrcTypes.image?t===R.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};cn.SrcTypes={image:"image",video:"video",audio:"audio"};var Ee=cn;var Fe=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var ot=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};var He=class He{static isWord(e){return e instanceof He}static color(e,t){return He.isWord(e)?e.copy().assign({color:t}):new He(e,{color:t})}static bold(e){return He.isWord(e)?e.copy().assign({bold:!0}):new He(e,{bold:!0})}static italic(e){return He.isWord(e)?e.copy().assign({italic:!0}):new He(e,{italic:!0})}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=z(He.defaultConfig,t)}evaluate(e){if(Fe.isPause(this.text))return[this];if(ot.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>He.isWord(n)?n.inherit(this.config).evaluate(e):new He(n,this.config)).flat():He.isWord(t)?t.inherit(this.config).evaluate(e):[new He(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this}assign(e){return this.config=z(this.config,e),this}copy(){return new He(this.text,this.config)}isPause(){return Fe.isPause(this.text)}isTextEvent(){return ot.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};He.defaultConfig={},He.defaultColor="#000";var J=He;var Yt=class extends ${executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};Yt.ActionTypes=rs;var Ce=class o extends ae{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new Yt(t,Yt.ActionTypes.action,new w().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new Yt(this.chain(),Yt.ActionTypes.action,new w().setContent(e))]}};var Mi=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};var Ie=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),nt(()=>{this.preventAttach()})}static proxy(e){let t=new T,n=new T,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new L("Cannot create an 'any' timeline with no awaitables.");let t=new T,n=new T,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new L("Cannot create an 'all' timeline with no awaitables.");let t=new T,n=new T,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new T,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?nt(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new H(()=>(i&&i.abort(),t))),i=e(t),i?nt(()=>s()):nt(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?nt(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new L(`Attaching to this timeline violates the timeline's state.
10
+ reference, or store an id in place of the object.`);if(Array.isArray(o)||Rs(o)){n.add(o);try{if(Array.isArray(o))return o.map((c,l)=>$o(c,[...e,l],t+1,n,i,r,s));let a={};return Object.entries(o).forEach(([c,l])=>{a[c]=$o(l,[...e,c],t+1,n,i,r,s)}),a}finally{n.delete(o)}}}return console.warn(`Value of type "${Ic(o)}" cannot be saved and was stored as null
11
+ at ${s}, ${zo(e)}`),null}function Ic(o){return typeof o!="object"||o===null?typeof o:o.constructor?.name??"object"}function Ns(o,e,t){let n=Is(o,e,jo);return n=Is(n,t,()=>{}),n}function Is(o,e,t){if(!Array.isArray(e)||!e.length)return o;let n=o;for(let i of e){if(!Array.isArray(i))continue;if(!i.length){n=t(n);continue}let r=n;for(let a=0;a<i.length-1&&r!==null&&typeof r=="object";a++)r=r[i[a]];if(r===null||typeof r!="object")continue;let s=i[i.length-1];r[s]=t(r[s])}return n}function jo(o){return o instanceof Date?o:typeof o=="string"||typeof o=="number"?new Date(o):new Date(NaN)}function Gs(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function qo(o,e,t=0){if(Object.is(o,e))return!0;if(t>Bn)return!1;if(o instanceof Date||e instanceof Date)return o instanceof Date&&e instanceof Date&&o.getTime()===e.getTime();if(Array.isArray(o)||Array.isArray(e))return Array.isArray(o)&&Array.isArray(e)&&o.length===e.length&&o.every((n,i)=>qo(n,e[i],t+1));if(Gs(o)&&Gs(e)){let n=Object.keys(o);return n.length===Object.keys(e).length&&n.every(i=>Object.prototype.hasOwnProperty.call(e,i)&&qo(o[i],e[i],t+1))}return!1}var Lt=class o{constructor(e,t,n){this.owner=null;this.name=e,this.key=n||e,this.content=z({},t),this.defaultContent=t}static isSerializable(e){return Gi(e)}set(e,t){let n=this.content[e];return o.isSerializable(t)?(this.content[e]=t,this.reportChange(e,n,t),this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
12
+ at namespace "${this.name}"`),this.content[e]=t,this.reportChange(e,n,t),this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){let e=this.content;return this.content=z({},this.defaultContent),new Set([...Object.keys(e),...Object.keys(this.content)]).forEach(n=>{this.reportChange(n,e[n],this.content[n])}),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content={},this.deserialize(e)}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n,t)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)}),this.owner?.reportRestore(this.key)}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e,t){let n=`namespace "${this.name}"`+(t===void 0?"":`, key "${t}"`),i={any:s=>{let a=Ms(s,n),c={type:"any",data:a.data};return a.dates.length&&(c.dates=a.dates),a.undefineds.length&&(c.undefineds=a.undefineds),c},date:s=>({type:"date",data:s.toISOString()})},r=this.toTypeName(e);return i[r](e)}unwrap(e){let n={any:i=>Ns(i.data,i.dates,i.undefineds),date:i=>jo(i.data)}[e?.type];return n?n(e):(console.warn(`Unknown stored value type "${e?.type}", reading it as-is
13
+ at namespace "${this.name}"`),e?.data)}attach(e){return this.owner=e,this}detach(e){return this.owner===e&&(this.owner=null),this}reportChange(e,t,n){!this.owner||qo(t,n)||this.owner.reportChange({namespace:this.key,key:String(e),previous:t,next:n})}},Zt=class Zt{constructor(){this.events=new Q;this.namespaces={};this.restoreBatch=null;this.events.setMaxListeners(64)}static createNamespace(e,t,n){return new Lt(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,e.attach(this),this}getNamespace(e){if(!this.namespaces[e])throw new P(`Namespace ${e} is not initialized, did you forget to register it?
14
+ Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new P("No listener provided when subscribing to storable changes");return this.events.on(Zt.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(Zt.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new Lt(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(Zt.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(Zt.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(Zt.EventTypes["event:storable.restore"],{namespaces:[e]})}};Zt.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var Kn=Zt;var et=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Pt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Pt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Pt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=T.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===Pt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Pt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Pt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Pt.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=T.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===Pt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=T.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};et.ActionTypes=Pt;var tt={bgm:"bgm",sound:"sound",voice:"voice"},Vi=8,_t=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function wn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var zn=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=c=>{t.set(c.id,{id:c.id,parentId:c.parentId??null,volume:wn(c.volume)})};Object.values(tt).forEach(c=>n({id:c}));let i=new Set;e.forEach(c=>{let l=c?.id;if(typeof l!="string"||l.trim().length===0)throw new _t(`Audio bus id must be a non-empty string, got ${JSON.stringify(l)}.`);if(i.has(l))throw new _t(`Audio bus "${l}" is declared more than once.`);i.add(l),n(c)}),o.assertResolvable(t);let r=[],s=new Map,a=c=>{let l=s.get(c);if(l)return l;let u=t.get(c),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(c,p),r.push(p),p};return t.forEach(c=>a(c.id)),new o(r,s)}static isSeeded(e){return Object.values(tt).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new _t(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new _t(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>Vi)throw new _t(`Audio bus "${t.id}" nests deeper than ${Vi}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=Vi;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},Qo=zn.resolve();function Rc(o){Qo=o}function Xo(){return Qo}function Hi(o,e){let t=Qo;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var Vs={[tt.bgm]:"bgmVolume",[tt.sound]:"soundVolume",[tt.voice]:"voiceVolume"};function Hs(o){let e={};return Object.entries(Vs).forEach(([t,n])=>{e[t]={get:()=>wn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var Wn=class Wn{constructor(e,t={}){this.declarations=e;this.events=new Q;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,wn(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(Wn.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=zn.resolve(this.declarations()??[]),Rc(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=wn(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?wn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return wn(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(Wn.EventTypes["event:audioBus.volumeChange"],e)}};Wn.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var $n=Wn;var Fs=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Fs||{}),xe=class xe extends ue{static toSound(e){return e==null?null:typeof e=="string"?new xe({src:e}):e}static isSound(e){return e instanceof xe}static voice(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=xe.DefaultUserConfig.create(t),[i]=n.extract(xe.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){return Xo().isUnder(this.config.type,tt.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(et.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(et.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(et.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(et.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(et.ActionTypes.setRate,[e])}pause(e){return this.pushAction(et.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(et.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(et.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:xe.StateSerializer.serialize(this.state)}}fromData(e){return this.state=xe.StateSerializer.deserialize(e.state),this}copy(){return new xe(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return xe.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new et(this.chain(),e,new C().setContent(t)))}};xe.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",xe.DefaultUserConfig=new K({src:xe.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultConfig=new K({src:xe.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultState=new K({volume:1,rate:1,paused:!1,muted:!1}),xe.StateSerializer=new Xe;var Ae=xe;var Us=3;var Kd={};var kn=class extends Cn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let c=a.getFutureActions(e,i).filter(l=>!r.has(l));s.push(...c)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var dn=class dn{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===dn.SrcTypes.image?t.add(s):r===dn.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof L?L.getSrcURL(e):e.type==="image"?L.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(pe,J.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(k.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof ge){let n=t;if(t.is(ge,ut.setSrc)){let i=t.contentNode.getContent()[0];if(k.isImageSrc(i))return{type:"image",src:k.srcToURL(i),activeType:"scene"}}else{if(t.type===ut.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===ut.setAppearance){let i=t.contentNode.getContent()[0];if(L.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(L.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:L.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof Ae){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof L||k.isStaticImageData(e)){if(e instanceof L){if(!k.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(L.getSrcURL(e)))return this}else if(this.isSrcRegistered(k.srcToURL(e.src)))return this;this.src.push({type:"image",src:k.isStaticImageData(e)?k.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof Ae?t:new Ae({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof Ae?e.getSrc():e;return this.src.some(n=>n.type===dn.SrcTypes.audio?t===n.src.getSrc():n.type===dn.SrcTypes.image?t===L.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};dn.SrcTypes={image:"image",video:"video",audio:"audio"};var Le=dn;var Be=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var at=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};var Ke=class Ke{static isWord(e){return e instanceof Ke}static color(e,t){return Ke.isWord(e)?e.copy().assign({color:t}):new Ke(e,{color:t})}static bold(e){return Ke.isWord(e)?e.copy().assign({bold:!0}):new Ke(e,{bold:!0})}static italic(e){return Ke.isWord(e)?e.copy().assign({italic:!0}):new Ke(e,{italic:!0})}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=z(Ke.defaultConfig,t)}evaluate(e){if(Be.isPause(this.text))return[this];if(at.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Ke.isWord(n)?n.inherit(this.config).evaluate(e):new Ke(n,this.config)).flat():Ke.isWord(t)?t.inherit(this.config).evaluate(e):[new Ke(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this}assign(e){return this.config=z(this.config,e),this}copy(){return new Ke(this.text,this.config)}isPause(){return Be.isPause(this.text)}isTextEvent(){return at.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Ke.defaultConfig={},Ke.defaultColor="#000";var Z=Ke;var en=class extends ${executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};en.ActionTypes=hs;var Ce=class o extends ue{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new en(t,en.ActionTypes.action,new C().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new en(this.chain(),en.ActionTypes.action,new C().setContent(e))]}};var Fi=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};var Ne=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),rt(()=>{this.preventAttach()})}static proxy(e){let t=new T,n=new T,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new P("Cannot create an 'any' timeline with no awaitables.");let t=new T,n=new T,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new P("Cannot create an 'all' timeline with no awaitables.");let t=new T,n=new T,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new T,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?rt(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new V(()=>(i&&i.abort(),t))),i=e(t),i?rt(()=>s()):rt(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?rt(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new P(`Attaching to this timeline violates the timeline's state.
15
15
  Timeline attaching is only allowed synchronously after the timeline is created.
16
- Current _ableToAttach: `+this._ableToAttach);let t=T.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved&&this.children.every(t=>t.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},Ni=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof Ie?e:new Ie(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var gt=class gt extends ${static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:i,voice:r}=t.config;return!i&&!r?null:Ae.toSound(n.getVoice(i)||r)}static endVoiceWithPreference(e,t){let{voiceEndMode:n,voiceFadeDuration:i}=e.game.preference.getPreferences();if(n==="none")return null;let r=n==="fade"?Math.max(0,i):0;return e.audioManager.stop(t,r)}static cutTrailingVoice(e,t){let n=gt.trailingVoice.get(e);n&&n!==t&&e.audioManager.isPlaying(n)&&e.timelines.attachTimeline(e.audioManager.stop(n,0)),t?gt.trailingVoice.set(e,t):gt.trailingVoice.delete(e)}executeAction(e,t){if(this.type===qt.say){let n=null,i="",r=null,s=new T(h=>h).registerSkipController(new H(()=>{n?.()})),a=new Ie(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),d=e.createPresentationSnapshot(),p=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,g=gt.getVoice(e,c);if(g){gt.cutTrailingVoice(e,g);let h=e.audioManager.play(g);a.attachChild(h)}let y=g?e.events.on(I.EventTypes["event:state.player.lineEnd"],()=>{let h=gt.endVoiceWithPreference(e,g);h&&e.timelines.attachTimeline(h),y?.cancel()}):null;if(l){let h=this.getId(),m=(e.getActiveNvlDialogForAction(h)||e.getLatestNvlDialogForAction(h))?.id||e.allocateNvlDialogId(h),v=c.evaluate(Ce.getCtx({gameState:e}));i=J.getText(v),u.events.emit(Pt.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let x=!1,b=()=>{x||(x=!0,e.events.emit(I.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(f),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:S}=e.ensureNvlDialog({id:m,actionId:h,character:this.callee,sentence:c,text:i});r=m;let C=e.consumeNvlTypingSuppression(),E=S&&!C?"typing":"awaitAdvance";e.activateNvlDialog(m,E,!S);let O=e.waitForNvlAdvance(m,()=>{e.settleNvlDialog(m),b()});n=()=>{O.cancel()}}else{let h=e.idManager.generateId(),A=e.createDialog(h,c,()=>{e.settleAdvDialog(h),e.gameHistory.resolvePending(f),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(h,this.getId()),i=A.text,n=()=>{e.settleAdvDialog(h),A.cancel()}}u.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:f}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(y?.cancel(),g&&e.audioManager.isPlaying(g)){let h=gt.endVoiceWithPreference(e,g);h&&a.attachChild(h)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(d),p?u.setLastDialog(p.sentence,p.speaker):u.lastDialog=null});return e.gameHistory.push({token:f,action:this,element:{type:"say",text:i,voice:g?g.getSrc():null,voiceId:c.config.voiceId??null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),s}else if(this.type===qt.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.name=i},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};gt.ActionTypes=qt,gt.trailingVoice=new WeakMap;var Ze=gt;function $o(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function Rs(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return Is(o);let i=zo(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=zo(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=zo(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function zo(o,e){if(o===!1||typeof o>"u")return{resolved:!1,source:null};if(typeof o=="function"){let t=o(e);return{resolved:typeof t<"u",source:t??null}}return{resolved:!0,source:o}}function Is(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function Ms(o,e){let t=[],n=i=>{i&&typeof i!="function"&&k.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n($o(i).avatar);return t}var Zt=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===yi.setText){let i=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.text=r},[i]),super.executeAction(e,t)}else if(this.type===yi.setFontSize){let i=this.callee.state.fontSize;this.callee.state.fontSize=this.contentNode.getContent()[0];let r=e.getExposedStateForce(this.callee);return r.flush(),r.updateStyleSync(),e.actionHistory.push(n,s=>{this.callee.state.fontSize=s},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};Zt.ActionTypes=yi;var De=class extends ${executeAction(e,t){if(this.type===ke.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===ke.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===ke.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new T().registerSkipController(new H(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t),l=t.transformState.clone(),u=c.applyTransform(n,a),d=e.timelines.attachTimeline(s).attachChild(u);return u.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},p=>{s.isSettled()||s.abort(),u.abort(),t.transformState.forceOverwrite(p.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new T().registerSkipController(new H(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),l.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new T().registerSkipController(new H(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};De.ActionTypes=ke;var rt=class o extends ae{constructor(){super(...arguments);this.srcManager=new Ee}pos(t,n,i){return this.transform(new Y({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new Y({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new Y({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new Y({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new Y({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new Y({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new Y({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new Y(t,n))}mask(t,n={}){let i=k.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c,...l}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c},l)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Ue,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Ue,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...c}=t,l={duration:s,ease:a,...c},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,l]]);return r?this.combineActions(new Ue,g=>g.transform(p).clearClip({duration:0})):this.transform(p)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new De(n,ke.applyTransform,new w().setContent([t.copy()]));return n.chain(i)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new Y(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof Y?t.copy():new Y({opacity:1},t),r=new De(n,ke.applyTransform,new w().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof Y?t.copy():new Y({opacity:0},t),r=new De(n,ke.applyTransform,new w().setContent([i]));return n.chain(r)}};var yt=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(yt||{});import{animate as xc}from"motion/react";var Et=class{requestAnimations(e){let t=e.map(f=>f.start),n=[],i=0,r=!1,s=!1,a=!1,c=[],l=[],u=[],d=()=>{e.forEach((f,h)=>{t[h]=f.end}),i=e.length,c.forEach(f=>f(t)),l.forEach(f=>f())};return{onUpdate:f=>(c.push(f),{cancel:()=>{let h=c.indexOf(f);h!==-1&&c.splice(h,1)}}),onComplete:f=>(l.push(f),{cancel:()=>{let h=l.indexOf(f);h!==-1&&l.splice(h,1)}}),onCanceled:f=>(u.push(f),{cancel:()=>{let h=u.indexOf(f);h!==-1&&u.splice(h,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(f=>f.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){d();return}e.forEach((f,h)=>{n.push(this.requestMotion(f,{onComplete:()=>{t[h]=f.end,c.forEach(A=>A(t)),i++,i===e.length&&l.forEach(A=>A())},onUpdate:A=>{t[h]=A,c.forEach(m=>m(t))}}))})}},cancel:()=>{s=!0,n.forEach(f=>f.cancel()),u.forEach(f=>f())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return xc(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Et.AnimationType=yt;var Bn=class extends Et{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new L(`Trying to access text state, but element is not set
17
- This should not happen, please report this issue to the developers`);return this._element.state}};var Gi=class o extends Bn{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var we=class we extends rt{static get DefaultUserConfig(){return we._defaultUserConfig??(we._defaultUserConfig=new B({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...Q.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}))}static get DefaultTextTransformState(){return we._defaultTextTransformState??(we._defaultTextTransformState=new B({fontColor:"#000000",...Q.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=we.DefaultUserConfig.create(n),r=we.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new Zt(t,Zt.ActionTypes.setText,new w().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new Y({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Ue,i=>{if(t){let s=new Gi({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new Zt(i,Zt.ActionTypes.setFontSize,new w().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:we.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=we.StateSerializer.deserialize(e.state),this.transformState=Q.deserialize(e.transformState),this}_init(e){return new De(this.chain(),ke.init,new w().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(we.DefaultTextTransformState.keys());return new Q(we.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new De(e,ke.applyTransition,new w().setContent([t,n=>n._setElement(this)]))}getInitialState(){return we.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};we._defaultUserConfig=null,we.DefaultTextConfig=new B({alignX:"center",alignY:"center",className:"",layer:void 0}),we.DefaultTextState=new B({fontSize:16,display:!1,text:""}),we._defaultTextTransformState=null,we.StateSerializer=new tt;var ln=we;var Wn=class extends ${executeAction(e,t){if(this.type===Xe.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===Xe.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===Xe.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===Xe.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===Xe.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===Xe.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let c=new T().registerSkipController(new H(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{c.isSettled()||c.resolve(super.executeAction(e,t))});let l=e.timelines.attachTimeline(c);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:l},()=>{c.isSettled()||c.abort()}),c}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};Wn.ActionTypes=Xe;var Re=class Re extends rt{constructor(t){super();this.events=new q;this.instance=null;this.status="unmounted";let n=Re.DefaultUserConfig.create(t),i=Re.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new te("Puppet must have a backend name");if(!this.config.src)throw new te("Puppet must have a src")}static get DefaultUserConfig(){return Re._defaultUserConfig??(Re._defaultUserConfig=new B({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...Q.DefaultTransformState.getDefaultConfig()},{position:t=>N.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:Re.copyParams(n.params),slots:Re.copySlots(n.slots)}}static mergeState(t,n){return Re.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(Xe.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(Xe.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(Xe.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(Xe.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(Xe.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(Xe.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:Re.normalizeState(this.state),transformState:this.transformState.serialize()}}fromData(t){return this.state=Re.normalizeState(t.state),this.transformState=Q.deserialize(t.transformState),this}_init(t){return new De(this.chain(),ke.init,new w().setContent([t||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=Re.normalizeState(this.state);return this.state=Re.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(Re.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new Wn(this.chain(),t,w.create(n))}getInitialTransformState(t){let[n]=t.extract(Q.DefaultTransformState.keys());return new Q(Q.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return Re.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};Re._defaultUserConfig=null,Re.DefaultPuppetConfig=new B({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var vt=Re;var zn=class zn extends ${executeAction(e,t){let n=this;if(n.is(zn,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let c=s.get(i);s.set(i,r(c))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.set(i,c)},[a]),super.executeAction(e,t)}else if(n.is(zn,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(c=>{s[c]=r.get(c),r.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{r.set(l,c[l])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};zn.ActionTypes=Nn;var Vi=zn;var st=class st{static isSentence(e){return e instanceof st}static toSentence(e){return st.isSentence(e)?e:new st(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return J.isWord(e)?e:new J(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[J.isWord(e)?e:new J(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(st.isSingleWord):st.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||J.isWord(e)||Fe.isPause(e)||ot.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=st.format(e),this.config=z(st.defaultConfig,{...t,voice:typeof t.voice=="string"?Ae.voice(t.voice):Ae.toSound(t.voice)}),this.state=cs(st.defaultState)}toData(){return null}fromData(e){return this.state=z(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...st.formatStaticWord(i))}return t}copy(){return new st([...this.text],this.config)}};st.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},st.defaultState={};var Se=st;var $n=class $n extends ae{constructor(e,t={}){super(),this.config=z($n.defaultConfig,t),this.state={name:e||""};let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>Se.isSingleWord(c))){let c=e,l=Se.format([t,...n]),u=new Se(us(c,l),{character:this}),d=new Ze(this.chain(),Ze.ActionTypes.say,new w().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new Se(r,{...i,character:this}):(Se.isSentence(r)?r:new Se(r,{...i,character:this})).copy();s.setCharacter(this);let a=new Ze(this.chain(),Ze.ActionTypes.say,new w().setContent(s));return this.chain(a)}setName(e){let t=new Ze(this.chain(),Ze.ActionTypes.setName,new w().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&Se.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):Se.isSentence(e)?this.say(e):this.say(e,t)}};$n.defaultCharacterColor="#000",$n.defaultConfig={portraits:[]};var Fi=$n,Kt=new Fi(null);var j=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},jo=class o extends ae{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new Me(`ELSE condition already set
18
- You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:j.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new Me(`ELSE condition already set
19
- You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(wt,[this,wt.ActionTypes.action,new w().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,c=r[s+1]?.contentNode;c&&a.setChild(c),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return Ve.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=j.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new wt(i,wt.ActionTypes.action,new w().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Kt.say(n).getActions():Ve.toActions([n]))}};var Hi=class Hi extends ae{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new kt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Nn.set,[e,t]))}assign(e){return this.chain(this.createAction(Nn.assign,[e]))}equals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new j(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new J(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new J(i=>j.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new j(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=Hi.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new Vi(this.chain(),e,w.create(t))}};Hi.NamespacePrefix="persistent";var xn=Hi,Ui=class Ui extends xn{constructor(e){super(e,{}),this.namespace=this.prefix(e,Ui.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new kt(this.namespace,this.defaultContent))}};Ui.LocalNamespacePrefix="local";var Cn=Ui;var wn=class extends ${executeAction(e,t){if(this.type===sn.action)return super.executeAction(e,t);if(this.type===sn.setZIndex){let[n]=this.contentNode.getContent(),i=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.zIndex=r},[i]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};wn.ActionTypes=sn;var _e=class _e extends rt{static get DefaultUserConfig(){return _e._defaultUserConfig??(_e._defaultUserConfig=new B({zIndex:0,...Q.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e,t={}){super();let n=_e.DefaultUserConfig.create(t),i=_e.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState()}include(e){return(Array.isArray(e)?e:[e]).forEach(n=>{n.useLayer(this)}),this}setZIndex(e){return this.chain(new wn(this.chain(),sn.setZIndex,new w().setContent([e])))}toData(){return{state:_e.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=_e.StateSerializer.deserialize(e.state),this.transformState=Q.deserialize(e.transformState),this}copy(){return new _e(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new wn(this.chain(),sn.action,new w),new De(this.chain(),ke.init,new w().setContent([e,null,!1]))]}getInitialState(){return _e.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(Q.DefaultTransformState.keys());return new Q(Q.DefaultTransformState.create(e.get()).get())}};_e._defaultUserConfig=null,_e.DefaultConfig=new B({name:"(anonymous)",zIndex:0}),_e.StateSerializer=new tt,_e.DefaultState=new B({zIndex:0});var kn=_e;var jn=class extends ae{constructor(e){super(),this.scene=e}show(e){let t=new ce(this.scene.chain(),X.nvlShow,new w().setContent([e]));return this.chain(t)}hide(e){let t=new ce(this.scene.chain(),X.nvlHide,new w().setContent([e]));return this.chain(t)}end(){let e=new ce(this.scene.chain(),X.nvlEnd,new w().setContent([]));return this.chain(e)}};var Ne=class Ne extends An{constructor(t,n){super();this.srcManager=new Ee;this.events=new q;this.actions=[];this.voiceCache=new Map;this._futureActions_=[];this.labelMap=new Map;let i=Ne.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Ne.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Ne.DefaultUserConfig.create(n),a=Ne.DefaultSceneConfig.create({...s.get(),name:t,layers:[...s.get().layers,i,r],defaultBackgroundLayer:i,defaultDisplayableLayer:r});this.userConfig=s,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new Cn(t)}static get DefaultSceneConfig(){return Ne._defaultSceneConfig??(Ne._defaultSceneConfig=new B({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new kn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new kn("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=r=>typeof r=="object"&&r!==null,i=r=>typeof r=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(r=>{Ae.isSound(r)&&Ne.validateVoice(r)}),i(t))return t;throw new Me(`Invalid voices config: ${t}`)}}))}static validateVoice(t){if(!Ri(t.config.type,[Ye.voice,Ye.sound]))throw new Me(`Voice must be a voice, but got ${t.config.type}.
20
- To prevent unintended behavior and unexpected results, the sound have to be on the voice bus (or any bus beneath it). Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Ne}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new tt({backgroundImage:n=>n.toData(),backgroundMusic:n=>n?.toData()||null},{backgroundImage:n=>t.state.backgroundImage.fromData(n),backgroundMusic:n=>t.state.backgroundMusic&&n?t.state.backgroundMusic.fromData(n):null})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){return this.chain().chain(Ue.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new Ue({allowFutureScene:!1}),i=>{let s=z({},n instanceof Et?{transition:n}:n);return i.chain(new ce(i,"scene:preUnmount",new w().setContent([]))).chain(this._initScene(t))._transitionToScene(s.transition,t.state.backgroundImage.state.currentSrc).chain(this._exit()),i})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new ce(this.chain(),X.setBackgroundMusic,new w().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new jn(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new ce(this.chain(),X.nvlEnd,new w().setContent([l])),d=[...c,u];super.constructNodes(d);let p=new ce(this.chain(),X.nvlBlock,new w().setContent([d,l]));return this.chain(p)}action(t){return this.actions=t,this}preloadImage(t){if(!k.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(i=>{this.srcManager.register({type:"image",src:i})}),this}toData(){return{state:Ne.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=Ne.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new ce(this.chain(),"scene:action",new w);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(f=>Ve.isChained(f)?f.fromChained(f):f).flat(2),s=[],a=[],c=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(f=>{Ve.isChained(f)||(f instanceof R?s.push(f):f instanceof ln?a.push(f):f instanceof vt&&c.push(f))});let l=[],u=[],d=new Map;s.forEach(f=>{f.config.isWearable?u.push(f):f.config.autoInit&&l.push(f);for(let h of f.config.wearables){if(d.get(h)&&d.get(h)!==f)throw new Error(`Wearable image cannot be used multiple times
16
+ Current _ableToAttach: `+this._ableToAttach);let t=T.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved&&this.children.every(t=>t.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},Ui=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof Ne?e:new Ne(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var Tt=class Tt extends ${static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:i,voice:r}=t.config;return!i&&!r?null:Ae.toSound(n.getVoice(i)||r)}static endVoiceWithPreference(e,t){let{voiceEndMode:n,voiceFadeDuration:i}=e.game.preference.getPreferences();if(n==="none")return null;let r=n==="fade"?Math.max(0,i):0;return e.audioManager.stop(t,r)}static cutTrailingVoice(e,t){let n=Tt.trailingVoice.get(e);n&&n!==t&&e.audioManager.isPlaying(n)&&e.timelines.attachTimeline(e.audioManager.stop(n,0)),t?Tt.trailingVoice.set(e,t):Tt.trailingVoice.delete(e)}executeAction(e,t){if(this.type===zt.say){let n=null,i="",r=null,s=new T(y=>y).registerSkipController(new V(()=>{n?.()})),a=new Ne(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),d=e.createPresentationSnapshot(),p=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,g=Tt.getVoice(e,c);if(g){Tt.cutTrailingVoice(e,g);let y=e.audioManager.play(g);a.attachChild(y)}let h=g?e.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{let y=Tt.endVoiceWithPreference(e,g);y&&e.timelines.attachTimeline(y),h?.cancel()}):null;if(l){let y=this.getId(),f=(e.getActiveNvlDialogForAction(y)||e.getLatestNvlDialogForAction(y))?.id||e.allocateNvlDialogId(y),v=c.evaluate(Ce.getCtx({gameState:e}));i=Z.getText(v),u.events.emit(It.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let x=!1,S=()=>{x||(x=!0,e.events.emit(E.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:b}=e.ensureNvlDialog({id:f,actionId:y,character:this.callee,sentence:c,text:i});r=f;let w=e.consumeNvlTypingSuppression(),D=b&&!w?"typing":"awaitAdvance";e.activateNvlDialog(f,D,!b);let B=e.waitForNvlAdvance(f,()=>{e.settleNvlDialog(f),S()});n=()=>{B.cancel()}}else{let y=e.idManager.generateId(),A=e.createDialog(y,c,()=>{e.settleAdvDialog(y),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(y,this.getId()),i=A.text,n=()=>{e.settleAdvDialog(y),A.cancel()}}u.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:m}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(h?.cancel(),g&&e.audioManager.isPlaying(g)){let y=Tt.endVoiceWithPreference(e,g);y&&a.attachChild(y)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(d),p?u.setLastDialog(p.sentence,p.speaker):u.lastDialog=null});return e.gameHistory.push({token:m,action:this,element:{type:"say",text:i,voice:g?g.getSrc():null,voiceId:c.config.voiceId??null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),s}else if(this.type===zt.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.name=i},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};Tt.ActionTypes=zt,Tt.trailingVoice=new WeakMap;var nt=Tt;function Jo(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function Ks(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return Bs(o);let i=Yo(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=Yo(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=Yo(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function Yo(o,e){if(o===!1||typeof o>"u")return{resolved:!1,source:null};if(typeof o=="function"){let t=o(e);return{resolved:typeof t<"u",source:t??null}}return{resolved:!0,source:o}}function Bs(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function Ws(o,e){let t=[],n=i=>{i&&typeof i!="function"&&k.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(Jo(i).avatar);return t}var tn=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ai.setText){let i=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.text=r},[i]),super.executeAction(e,t)}else if(this.type===Ai.setFontSize){let i=this.callee.state.fontSize;this.callee.state.fontSize=this.contentNode.getContent()[0];let r=e.getExposedStateForce(this.callee);return r.flush(),r.updateStyleSync(),e.actionHistory.push(n,s=>{this.callee.state.fontSize=s},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};tn.ActionTypes=Ai;var Ie=class extends ${executeAction(e,t){if(this.type===Ee.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===Ee.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===Ee.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new T().registerSkipController(new V(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t),l=t.transformState.clone(),u=c.applyTransform(n,a),d=e.timelines.attachTimeline(s).attachChild(u);return u.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},p=>{s.isSettled()||s.abort(),u.abort(),t.transformState.forceOverwrite(p.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new T().registerSkipController(new V(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),l.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new T().registerSkipController(new V(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Ie.ActionTypes=Ee;var ct=class o extends ue{constructor(){super(...arguments);this.srcManager=new Le}pos(t,n,i){return this.transform(new _({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new _({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new _({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new _({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new _({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new _({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new _({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new _(t,n))}mask(t,n={}){let i=k.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c,...l}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c},l)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new We,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new We,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...c}=t,l={duration:s,ease:a,...c},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,l]]);return r?this.combineActions(new We,g=>g.transform(p).clearClip({duration:0})):this.transform(p)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new Ie(n,Ee.applyTransform,new C().setContent([t.copy()]));return n.chain(i)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new _(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof _?t.copy():new _({opacity:1},t),r=new Ie(n,Ee.applyTransform,new C().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof _?t.copy():new _({opacity:0},t),r=new Ie(n,Ee.applyTransform,new C().setContent([i]));return n.chain(r)}};var bt=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(bt||{});import{animate as Mc}from"motion/react";var Rt=class{requestAnimations(e){let t=e.map(m=>m.start),n=[],i=0,r=!1,s=!1,a=!1,c=[],l=[],u=[],d=()=>{e.forEach((m,y)=>{t[y]=m.end}),i=e.length,c.forEach(m=>m(t)),l.forEach(m=>m())};return{onUpdate:m=>(c.push(m),{cancel:()=>{let y=c.indexOf(m);y!==-1&&c.splice(y,1)}}),onComplete:m=>(l.push(m),{cancel:()=>{let y=l.indexOf(m);y!==-1&&l.splice(y,1)}}),onCanceled:m=>(u.push(m),{cancel:()=>{let y=u.indexOf(m);y!==-1&&u.splice(y,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(m=>m.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){d();return}e.forEach((m,y)=>{n.push(this.requestMotion(m,{onComplete:()=>{t[y]=m.end,c.forEach(A=>A(t)),i++,i===e.length&&l.forEach(A=>A())},onUpdate:A=>{t[y]=A,c.forEach(f=>f(t))}}))})}},cancel:()=>{s=!0,n.forEach(m=>m.cancel()),u.forEach(m=>m())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return Mc(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Rt.AnimationType=bt;var jn=class extends Rt{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new P(`Trying to access text state, but element is not set
17
+ This should not happen, please report this issue to the developers`);return this._element.state}};var Oi=class o extends jn{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var we=class we extends ct{static get DefaultUserConfig(){return we._defaultUserConfig??(we._defaultUserConfig=new K({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...Y.DefaultTransformState.getDefaultConfig()},{position:e=>R.tryParsePosition(e)}))}static get DefaultTextTransformState(){return we._defaultTextTransformState??(we._defaultTextTransformState=new K({fontColor:"#000000",...Y.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=we.DefaultUserConfig.create(n),r=we.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new tn(t,tn.ActionTypes.setText,new C().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new _({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new We,i=>{if(t){let s=new Oi({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new tn(i,tn.ActionTypes.setFontSize,new C().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:we.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=we.StateSerializer.deserialize(e.state),this.transformState=Y.deserialize(e.transformState),this}_init(e){return new Ie(this.chain(),Ee.init,new C().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(we.DefaultTextTransformState.keys());return new Y(we.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Ie(e,Ee.applyTransition,new C().setContent([t,n=>n._setElement(this)]))}getInitialState(){return we.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};we._defaultUserConfig=null,we.DefaultTextConfig=new K({alignX:"center",alignY:"center",className:"",layer:void 0}),we.DefaultTextState=new K({fontSize:16,display:!1,text:""}),we._defaultTextTransformState=null,we.StateSerializer=new Xe;var mn=we;var qn=class extends ${executeAction(e,t){if(this.type===_e.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===_e.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===_e.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===_e.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===_e.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===_e.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let c=new T().registerSkipController(new V(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{c.isSettled()||c.resolve(super.executeAction(e,t))});let l=e.timelines.attachTimeline(c);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:l},()=>{c.isSettled()||c.abort()}),c}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};qn.ActionTypes=_e;var Ge=class Ge extends ct{constructor(t){super();this.events=new Q;this.instance=null;this.status="unmounted";let n=Ge.DefaultUserConfig.create(t),i=Ge.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new ie("Puppet must have a backend name");if(!this.config.src)throw new ie("Puppet must have a src")}static get DefaultUserConfig(){return Ge._defaultUserConfig??(Ge._defaultUserConfig=new K({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...Y.DefaultTransformState.getDefaultConfig()},{position:t=>R.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:Ge.copyParams(n.params),slots:Ge.copySlots(n.slots)}}static mergeState(t,n){return Ge.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(_e.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(_e.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(_e.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(_e.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(_e.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(_e.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:Ge.normalizeState(this.state),transformState:this.transformState.serialize()}}fromData(t){return this.state=Ge.normalizeState(t.state),this.transformState=Y.deserialize(t.transformState),this}_init(t){return new Ie(this.chain(),Ee.init,new C().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=Ge.normalizeState(this.state);return this.state=Ge.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(Ge.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new qn(this.chain(),t,C.create(n))}getInitialTransformState(t){let[n]=t.extract(Y.DefaultTransformState.keys());return new Y(Y.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return Ge.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};Ge._defaultUserConfig=null,Ge.DefaultPuppetConfig=new K({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var At=Ge;var Qn=class Qn extends ${executeAction(e,t){let n=this;if(n.is(Qn,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let c=s.get(i);s.set(i,r(c))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.set(i,c)},[a]),super.executeAction(e,t)}else if(n.is(Qn,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(c=>{s[c]=r.get(c),r.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{r.set(l,c[l])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};Qn.ActionTypes=Fn;var Bi=Qn;var lt=class lt{static isSentence(e){return e instanceof lt}static toSentence(e){return lt.isSentence(e)?e:new lt(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return Z.isWord(e)?e:new Z(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[Z.isWord(e)?e:new Z(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(lt.isSingleWord):lt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||Z.isWord(e)||Be.isPause(e)||at.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=lt.format(e),this.config=z(lt.defaultConfig,{...t,voice:typeof t.voice=="string"?Ae.voice(t.voice):Ae.toSound(t.voice)}),this.state=vs(lt.defaultState)}toData(){return null}fromData(e){return this.state=z(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...lt.formatStaticWord(i))}return t}copy(){return new lt([...this.text],this.config)}};lt.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},lt.defaultState={};var Se=lt;var nn=class nn extends ue{constructor(e,t={}){super(),this.config=z(nn.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>Se.isSingleWord(c))){let c=e,l=Se.format([t,...n]),u=new Se(Ts(c,l),{character:this}),d=new nt(this.chain(),nt.ActionTypes.say,new C().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new Se(r,{...i,character:this}):(Se.isSentence(r)?r:new Se(r,{...i,character:this})).copy();s.setCharacter(this);let a=new nt(this.chain(),nt.ActionTypes.say,new C().setContent(s));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.ActionTypes.setName,new C().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&Se.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):Se.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:nn.StateSerializer.serialize(this.state)}}fromData(e){return this.state=nn.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};nn.defaultCharacterColor="#000",nn.defaultConfig={portraits:[]},nn.StateSerializer=new Xe;var Ki=nn,$t=new Ki(null);var j=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},Zo=class o extends ue{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new Ve(`ELSE condition already set
18
+ You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:j.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new Ve(`ELSE condition already set
19
+ You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(Dt,[this,Dt.ActionTypes.action,new C().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,c=r[s+1]?.contentNode;c&&a.setChild(c),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return Oe.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=j.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new Dt(i,Dt.ActionTypes.action,new C().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?$t.say(n).getActions():Oe.toActions([n]))}};var Wi=class Wi extends ue{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new Lt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Fn.set,[e,t]))}assign(e){return this.chain(this.createAction(Fn.assign,[e]))}equals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new j(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new Z(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new Z(i=>j.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new j(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=Wi.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new Bi(this.chain(),e,C.create(t))}};Wi.NamespacePrefix="persistent";var Pn=Wi,zi=class zi extends Pn{constructor(e){super(e,{}),this.namespace=this.prefix(e,zi.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new Lt(this.namespace,this.defaultContent))}};zi.LocalNamespacePrefix="local";var En=zi;var Dn=class extends ${executeAction(e,t){if(this.type===un.action)return super.executeAction(e,t);if(this.type===un.setZIndex){let[n]=this.contentNode.getContent(),i=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.zIndex=r},[i]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};Dn.ActionTypes=un;var it=class it extends ct{static get DefaultUserConfig(){return it._defaultUserConfig??(it._defaultUserConfig=new K({zIndex:0,...Y.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e,t={}){super();let n=it.DefaultUserConfig.create(t),i=it.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState()}include(e){return(Array.isArray(e)?e:[e]).forEach(n=>{n.useLayer(this)}),this}setZIndex(e){return this.chain(new Dn(this.chain(),un.setZIndex,new C().setContent([e])))}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(),this}toData(){return{state:it.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=it.StateSerializer.deserialize(e.state),this.transformState=Y.deserialize(e.transformState),this}copy(){return new it(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Dn(this.chain(),un.action,new C),new Ie(this.chain(),Ee.init,new C().setContent([e,null,!1]))]}getInitialState(){return it.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(Y.DefaultTransformState.keys());return new Y(Y.DefaultTransformState.create(e.get()).get())}};it._defaultUserConfig=null,it.DefaultConfig=new K({name:"(anonymous)",zIndex:0}),it.StateSerializer=new Xe,it.DefaultState=new K({zIndex:0});var Ln=it;var Xn=class extends ue{constructor(e){super(),this.scene=e}show(e){let t=new pe(this.scene.chain(),J.nvlShow,new C().setContent([e]));return this.chain(t)}hide(e){let t=new pe(this.scene.chain(),J.nvlHide,new C().setContent([e]));return this.chain(t)}end(){let e=new pe(this.scene.chain(),J.nvlEnd,new C().setContent([]));return this.chain(e)}};var He=class He extends kn{constructor(t,n){super();this.srcManager=new Le;this.events=new Q;this.actions=[];this.voiceCache=new Map;this._futureActions_=[];this.labelMap=new Map;let i=He.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=He.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=He.DefaultUserConfig.create(n),a=He.DefaultSceneConfig.create({...s.get(),name:t,layers:[...s.get().layers,i,r],defaultBackgroundLayer:i,defaultDisplayableLayer:r});this.userConfig=s,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new En(t)}static get DefaultSceneConfig(){return He._defaultSceneConfig??(He._defaultSceneConfig=new K({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Ln("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Ln("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=r=>typeof r=="object"&&r!==null,i=r=>typeof r=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(r=>{Ae.isSound(r)&&He.validateVoice(r)}),i(t))return t;throw new Ve(`Invalid voices config: ${t}`)}}))}static validateVoice(t){if(!Hi(t.config.type,[tt.voice,tt.sound]))throw new Ve(`Voice must be a voice, but got ${t.config.type}.
20
+ To prevent unintended behavior and unexpected results, the sound have to be on the voice bus (or any bus beneath it). Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof He}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new Xe({backgroundImage:n=>n.toData(),backgroundMusic:n=>n?.toData()||null},{backgroundImage:n=>t.state.backgroundImage.fromData(n),backgroundMusic:n=>t.state.backgroundMusic&&n?t.state.backgroundMusic.fromData(n):null})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){return this.chain().chain(We.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new We({allowFutureScene:!1}),i=>{let s=z({},n instanceof Rt?{transition:n}:n);return i.chain(new pe(i,"scene:preUnmount",new C().setContent([]))).chain(this._initScene(t))._transitionToScene(s.transition,t.state.backgroundImage.state.currentSrc).chain(this._exit()),i})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new pe(this.chain(),J.setBackgroundMusic,new C().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new Xn(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new pe(this.chain(),J.nvlEnd,new C().setContent([l])),d=[...c,u];super.constructNodes(d);let p=new pe(this.chain(),J.nvlBlock,new C().setContent([d,l]));return this.chain(p)}action(t){return this.actions=t,this}preloadImage(t){if(!k.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(i=>{this.srcManager.register({type:"image",src:i})}),this}toData(){return{state:He.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=He.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new pe(this.chain(),"scene:action",new C);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>Oe.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[],c=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{Oe.isChained(m)||(m instanceof L?s.push(m):m instanceof mn?a.push(m):m instanceof At&&c.push(m))});let l=[],u=[],d=new Map;s.forEach(m=>{m.config.isWearable?u.push(m):m.config.autoInit&&l.push(m);for(let y of m.config.wearables){if(d.get(y)&&d.get(y)!==m)throw new Error(`Wearable image cannot be used multiple times
21
21
  Maybe you bind the same wearable image to multiple parent images
22
- Parent Conflict (src: `+d.get(h)?.state.currentSrc+`)
23
- Current Parent (src: `+f.state.currentSrc+")");d.set(h,f)}});let p=[...this._initScene(this),...l.map(f=>f._init(this)),...u.map(f=>{if(!d.has(f))throw new Error("Wearable image must have a parent image");return d.get(f)._initWearable(f)}),...a.map(f=>f._init()),...c.map(f=>f._init()),...r],g=super.constructNodes(p),y=new w(this.sceneRoot,void 0,g||void 0).setContent(this);return g?.setParent(y),this.sceneRoot?.setContentNode(y),this._futureActions_=p,this.constructLabels(t),this}constructLabels(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!1}),i=new Map;for(let r of n)if(r instanceof ne&&r.type===ee.label){let[s]=r.contentNode.getContent();if(i.has(s))throw new Me(`Duplicate label "${s}" in scene "${this.config.name}". Label names must be unique within a scene.`);i.set(s,r)}this.labelMap=i;for(let r of n)if(r instanceof ne&&r.type===ee.jump){let[s]=r.contentNode.getContent(),a=i.get(s);if(!a)throw new Me(`Jump target label "${s}" not found in scene "${this.config.name}". Control.jump can only jump to a Control.label declared in the same scene.`);r.setJumpTarget(a)}}getLabel(t){return this.labelMap.get(t)||null}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Kt.say(n).getActions():Ve.toActions([n]))}isSceneRootConstructed(){return!!this.sceneRoot}registerSrc(t,n=new Set){if(!this.sceneRoot)return;let i=new Set,r=new Set,s=[this.sceneRoot],a=new Set;for(;s.length;){let c=s.shift();if(!i.has(c)){if(i.add(c),c instanceof ce){let l=c.callee;if(k.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:k.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===X.jumpTo){let u=c,d=Ne.getScene(t,u.contentNode.getContent()[0]);if(!d)throw c._sceneNotFoundError(c.getSceneName(u.contentNode.getContent()[0]));let p=Ee.getPreloadableSrc(t,c);if(p&&this.srcManager.register(p),r.has(u)||n.has(d))continue;r.add(u),a.add(d),n.add(d)}}else if(c instanceof ge){let l=Ee.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof Je)this.srcManager.register(c.callee);else if(c instanceof Ze){let l=c.type===qt.say?c.contentNode.getContent():null;for(let u of Ms(c.callee,l))this.srcManager.register({type:"image",src:k.srcToURL(u)})}else if(c instanceof ne){let u=c.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else c instanceof De&&this.srcManager.register(c.callee.srcManager.getSrc());s.push(...c.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(c=>{c.registerSrc(t,n),this.srcManager.registerFuture(c.srcManager)})}assignActionId(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}),i=new Set;n.forEach(a=>{let c=a.getStaticId();if(c){if(i.has(c))throw new Me(`Duplicate static action id: ${c}`);i.add(c)}});let r=0,s=()=>{let a=`a-${r++}`;for(;i.has(a);)a=`a-${r++}`;return i.add(a),a};n.forEach(a=>{let c=a.getStaticId();a.resolveId(c||s())})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((i,r)=>{i.resolveId(`e-${r}`)})}getVoice(t){if(!t)return null;let n=this.config.voices;if(n){if(typeof n=="function"){let r=n(t);return typeof r=="string"?this.voiceOfSrc(r):(Ne.validateVoice(r),r)}let i=n[t];return typeof i=="string"?this.voiceOfSrc(i):i||null}return null}voiceOfSrc(t){let n=this.voiceCache.get(t);if(n)return n;let i=Ae.voice(t);return this.voiceCache.set(t,i),i}getSceneRoot(){if(!this.sceneRoot)throw new Error("Scene root is not constructed");return this.sceneRoot}stringify(t,n,i){return super.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).map(r=>r.stringify(t,n,i)).join(";")}reset(){this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&!Ri(t.backgroundMusic.config.type,[Ye.bgm]))throw new Me(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
24
- To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new R({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new ce(this.chain(),"scene:jumpTo",new w().setContent([t])))}_exit(){return new ce(this.chain(),"scene:exit",new w().setContent([]))}_transitionToScene(t,n){let i=this.chain();if(t&&n){let r=this.state.backgroundImage.char(n,t);i.chain(r.getActions())}return i}_init(t){return new ce(this.chain(),"scene:init",new w().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};Ne.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},Ne.DefaultUserConfig=new B({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Ne._defaultSceneConfig=null;var ut=Ne;import*as Hs from"howler";var Oi=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let i=[],r=[],s=[];return this.prefix?(i.push(`%c${this.prefix} [${t}]`),r.push(`color: ${e}`)):(i.push(`%c[${t}]`),r.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(i.push(`%c${a}`),r.push(`color: ${e}`)):(i.push("%O"),s.push(a),r.push(""))}),[i.join(" ")].concat(r,s)}};var Cc={volume:1,limit:1/0},wc=class Gs{constructor(e,t,n,i){this.subChannels=new Map,this.tokens=new Set,this.tokenQueue=[],this.muted=!1,this.removed=!1,this.name=e,this.audioProvider=t,this.parentChannel=i??null,this.options={...Cc,...n},this.volume=this.options.volume;let r=this.audioProvider.getAudioContext();this.gainNode=r.createGain(),this.gainNode.gain.value=this.muted?0:this.volume,this.connectToParent()}connectToParent(){this.parentChannel?this.gainNode.connect(this.parentChannel.getGainNode()):this.gainNode.connect(this.audioProvider.getAudioContext().destination)}getGainNode(){return this.gainNode}ensureNotRemoved(){if(this.removed)throw new Error(`Channel "${this.name}" has been removed and cannot be used.`)}getName(){return this.name}async play(e,t){if(this.ensureNotRemoved(),this.tokens.size>=this.options.limit){let r=this.tokenQueue.shift();r&&r.stop()}let n=await this.audioProvider.createToken(e,t,this.gainNode);this.tokens.add(n),this.tokenQueue.push(n);let i=()=>{this.tokens.delete(n);let r=this.tokenQueue.indexOf(n);r!==-1&&this.tokenQueue.splice(r,1)};return n.once("ended",i),n.once("stop",i),n}createChannel(e,t){if(this.ensureNotRemoved(),this.subChannels.has(e))throw new Error(`Channel "${e}" already exists under "${this.name}".`);this.audioProvider.checkChannelLimit();let n=new Gs(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},Vs=!1;function kc(o){Vs=o}function _t(o,e){Vs||(e!==void 0?console.warn(o,e):console.warn(o))}var Pc=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.eventListeners=new Map,this.audioContext=o,this.gainNode=e}setSource(o){this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.setupEventListeners()}getSource(){return this.currentSource}refreshSource(o){let e=new Map(this.eventListeners);this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.eventListeners=e,this.setupEventListeners()}disconnectSource(){if(this.currentSource){if(this.removeAllEventListeners(),this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.disconnect()}catch(o){_t("Failed to disconnect AudioBufferSourceNode in disconnectSource().",o)}else this.currentSource instanceof HTMLAudioElement&&(this.currentSource.pause(),this.currentSource.src="",this.currentSource.load());if(this.mediaElementSource){try{this.mediaElementSource.disconnect()}catch(o){_t("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=o=>{this.emit("ended")},this.currentSource instanceof HTMLAudioElement?this.currentSource.addEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.addEventListener("ended",this.endedHandler))}removeAllEventListeners(){!this.currentSource||!this.endedHandler||(this.currentSource instanceof HTMLAudioElement?this.currentSource.removeEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.removeEventListener("ended",this.endedHandler),this.endedHandler=null)}emit(o){let e=this.eventListeners.get(o);e&&[...e].forEach((t,n)=>{try{t.callback()}catch(i){console.error(`Error in event listener for '${o}':`,i)}t.once&&e.splice(e.indexOf(t),1)})}on(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!1})}off(o,e){let t=this.eventListeners.get(o);if(!t)return;let n=t.findIndex(i=>i.callback===e);n!==-1&&t.splice(n,1)}once(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!0})}stop(){if(this.currentSource){if(this.currentSource instanceof HTMLAudioElement)this.currentSource.pause(),this.currentSource.currentTime=0;else if(this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.stop()}catch(o){_t("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){this.currentSource instanceof AudioBufferSourceNode?this.currentSource.start(o,e):this.currentSource instanceof HTMLAudioElement&&this.currentSource.play()}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},Ns=class{constructor(o,e){this.token=o,this.endVolume=e,this.cancelled=!1,this.finishedInternal=!1,this._finished=new Promise(t=>{this.resolveFinished=t})}get finished(){return this._finished}cancel(){this.cancelled||this.finishedInternal||(this.cancelled=!0,this.resolveFinished())}finish(){this.finishedInternal||(this.finishedInternal=!0,this.token.setVolume(this.endVolume),this.resolveFinished())}isCancelled(){return this.cancelled}isFinished(){return this.finishedInternal}getTargetVolume(){return this.endVolume}},Ec=class{constructor(o,e,t={},n){this._isPlaying=!1,this._isPaused=!1,this._isMuted=!1,this.volume=1,this.rate=1,this.contextStartTime=0,this.startOffset=0,this.pauseOffset=0,this.duration=0,this.currentFade=null,this.audioContext=o,this.volume=t.volume??1,this.rate=t.rate??1,this.startOffset=t.startOffset??0,this.duration=t.duration??0,this.outputNode=n??o.destination,this.gainNode=o.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.outputNode),this.sourceController=new Pc(o,this.gainNode),this.sourceController.setSource(e);let i=this.startOffset;this.sourceController.start(0,i),this.contextStartTime=this.audioContext.currentTime,this._isPlaying=!0,this.duration>0&&setTimeout(()=>{this._isPlaying&&this.stop()},this.duration*1e3)}emit(o){if(this.sourceController.emit(o),o==="ended"){this._isPlaying=!1;try{this.gainNode.disconnect()}catch(e){_t("Failed to disconnect gain node on natural end.",e)}}}setVolume(o){return this.currentFade&&(this.currentFade.cancel(),this.currentFade=null),o=Math.max(0,Math.min(1,o)),this.volume=o,this._isMuted||(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=o),this}getVolume(){return this.volume}mute(o){let e=o!==void 0?o:!0;if(this._isMuted=e,this.currentFade&&!this.currentFade.isFinished()&&!this.currentFade.isCancelled()){let t=this.currentFade.getTargetVolume();this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.volume=t,this.gainNode.gain.value=e?0:t,this.currentFade.finish(),this.currentFade=null}else this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=e?0:this.volume;return this}unmute(){return this.mute(!1)}isMuted(){return this._isMuted}pause(){if(!this._isPlaying||this._isPaused)return this;let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?(o.pause(),this.pauseOffset=o.currentTime):o instanceof AudioBufferSourceNode&&(this.pauseOffset=this.getCurrentTime(),this.sourceController.stop()),this._isPlaying=!1,this._isPaused=!0,this.emit("pause"),this}resume(){if(!this._isPaused)return this;let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement){let e=o.play();e&&typeof e.catch=="function"&&e.catch(()=>{this._isPlaying=!1,this._isPaused=!0})}else if(o instanceof AudioBufferSourceNode){let e=this.audioContext.createBufferSource();e.buffer=o.buffer,e.playbackRate.value=this.rate,e.loop=o.loop,e.loopStart=o.loopStart,e.loopEnd=o.loopEnd,this.sourceController.refreshSource(e),this.startOffset=this.pauseOffset,this.contextStartTime=this.audioContext.currentTime,this.sourceController.start(0,this.pauseOffset)}return this._isPlaying=!0,this._isPaused=!1,this.emit("resume"),this}isPlaying(){return this._isPlaying}isPaused(){return this._isPaused}stop(o={}){let{fadeDuration:e=0}=o;return e>0?this.fade(this.getVolume(),0,e).finished.then(()=>{this.doStop()}):this.doStop(),this}doStop(){this.sourceController.stop(),this._isPlaying=!1,this._isPaused=!1,this.emit("stop"),this.sourceController.destroy();try{this.gainNode.disconnect()}catch(o){_t("Failed to disconnect gain node on stop().",o)}}setRate(o){o=Math.max(.001,o),this.rate=o;let e=this.sourceController.getSource();return e instanceof HTMLAudioElement?e.playbackRate=o:e instanceof AudioBufferSourceNode&&(e.playbackRate.value=o),this}getRate(){return this.rate}seek(o){o=Math.max(0,o);let e=this.sourceController.getSource();if(e instanceof HTMLAudioElement)e.currentTime=o,this.emit("seek");else if(e instanceof AudioBufferSourceNode){let t=this.getCurrentTime();if(Math.abs(o-t)>.01){if(this._isPlaying){this.sourceController.stop();let n=this.audioContext.createBufferSource();n.buffer=e.buffer,n.playbackRate.value=this.rate,n.loop=e.loop,n.loopStart=e.loopStart,n.loopEnd=e.loopEnd,this.sourceController.refreshSource(n),this.startOffset=this.audioContext.currentTime-o,this.sourceController.start(0,o)}else this._isPaused&&(this.pauseOffset=o);this.emit("seek")}}return this}getCurrentTime(){let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement)return o.currentTime;if(o instanceof AudioBufferSourceNode){if(this._isPaused)return this.pauseOffset;if(this._isPlaying)return(this.audioContext.currentTime-this.contextStartTime)*this.rate+this.startOffset}return 0}getDuration(){let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?o.duration||0:o instanceof AudioBufferSourceNode&&o.buffer?o.buffer.duration:this.duration}fade(o,e,t){if(this.currentFade&&this.currentFade.cancel(),o=Math.max(0,Math.min(1,o)),e=Math.max(0,Math.min(1,e)),t=Math.max(0,t),t===0){this.setVolume(e);let r=new Ns(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new Ns(this,e);this.currentFade=n;let i=this.audioContext.currentTime;return this.gainNode.gain.setValueAtTime(o,i),this.gainNode.gain.linearRampToValueAtTime(e,i+t/1e3),setTimeout(()=>{!n.isCancelled()&&!n.isFinished()&&(this.volume=e,n.finish(),this.currentFade=null)},t),n}on(o,e){return this.sourceController.on(o,e),this}off(o,e){return this.sourceController.off(o,e),this}once(o,e){return this.sourceController.once(o,e),this}},Dc=class{constructor(o){this.alive=!0,this.refCount=0,this.audioBuffer=o}addRef(){this.refCount++}releaseRef(){this.refCount>0&&this.refCount--}getRefCount(){return this.refCount}async unload(){this.refCount>0||(this.alive=!1)}async forceUnload(){this.alive=!1,this.refCount=0}isAlive(){return this.alive}raw(){if(!this.alive)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}},Lc=10*1024*1024,Ic=class{constructor(o){this.cache=new Map,this.loadingPromises=new Map,this.audioContext=o}async load(o){let e=this.cache.get(o);if(e&&e.isAlive())return e;let t=this.loadingPromises.get(o);if(t)return t;let n=this.doLoad(o);this.loadingPromises.set(o,n);try{let i=await n;return this.cache.set(o,i),i}finally{this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new Dc(t)}clear(){for(let o of this.cache.values())o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size}}},Rc={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},Fs=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...Rc,...o},kc(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new Ic(this.audioContext),this.masterChannel=new wc("__master__",this,{volume:this.options.volume},null),this.initialize()}async onceReady(){return this.readyPromise?(await this.readyPromise,this):this}initialize(){this.isReady||(this.readyPromise=this.waitForUnlock())}waitForUnlock(){return typeof document>"u"?(this.isReady=!0,Promise.resolve()):this.audioContext.state==="running"?(this.isReady=!0,Promise.resolve()):new Promise(o=>{let e=()=>{if(this.destroyed){this.clearUnlockHandler(),o();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,o())}).catch(t=>{_t("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let d=new Ec(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,g=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",g),d.once("stop",g)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<Lc?"full":"stream"}catch(t){return _t("Failed to resolve load mode via HEAD request, falling back to 'stream'.",t),"stream"}}createStreamSource(o){let e=new Audio(o);return e.crossOrigin="anonymous",e}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(o){this.registeredChannels.add(o)}unregisterChannel(o){this.registeredChannels.delete(o)}setVolume(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(o),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(o){return this.ensureNotDestroyed(),this.ensureReady(),o===void 0?this.masterChannel.mute():this.masterChannel.mute(o),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(o,e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(o,e)}getChannel(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(o)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(o){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(o)}async play(o,e){this.ensureNotDestroyed(),this.ensureReady();let t=this.masterChannel.getTokens();for(let n of t)try{n.stop()}catch{}return this.masterChannel.play(o,e)}getTokens(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getTokens()}destroy(){this.destroyed||(this.destroyed=!0,this.clearUnlockHandler(),this.audioCache.clear(),this.masterChannel.remove(),this.registeredChannels.clear(),this.audioContext.close().catch(o=>{_t("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var ye=class ye{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new Fs({maxChannels:ye.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=ye.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,ye.BusRampTimeConstant),r.setValueAtTime(s,a+ye.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${Ye.sound}" instead.`)),this.channels.get(Ye.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=ye.defaultFade(e)){let n=new T;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=ye.clipRegionOf(e),a=await i.play(r,{volume:0,...ye.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ye.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(l=>{a.once("ended",()=>l())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=ye.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new L(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=ye.clipRegionOf(e),s=await n.play(i,{volume:0,...ye.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ye.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new T;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new T;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}pause(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),i.token.fade(0,i.originalVolume,t).finished.then(()=>{e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return T.resolve(void 0);let n=this.state.get(e),i=ye.clampToRegion(t,ye.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),T.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,T.resolve(void 0)):T.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=ye.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...ye.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&ye.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(ye.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c,e.state.paused?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};ye.MaxChannels=1024,ye.BusRampTimeConstant=.02,ye.BusRampSettle=ye.BusRampTimeConstant*5;var Ki=ye;import*as Mc from"html-to-image";var Bi=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new q}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new T,n=new Ie(t);return t.registerSkipController(new H(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};var Wi=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=ki(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),console.log("NarraLeaf-React [ActionHistory] Undoing",this.history[r].action.type,this.history[r]),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var zi=class o{constructor(e){this.history=[];this.actionHistoryMgr=e,this.actionHistoryMgr.onUndo(t=>{this.crossFilter(t)}),this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){return this.history.push(e),this}getHistory(){return this.history}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.map(e=>o.toSerialized(e))}serializeUntil(e){let t=this.history.findIndex(n=>n.token===e);return t<0?[]:this.history.slice(0,t+1).map(n=>o.toSerialized(n))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:ki(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}}reset(){this.history=[]}static toSerialized(e){return{actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(n=>n.id));this.history=this.history.filter(n=>!t.has(n.token))}};var un=class extends ${executeAction(e,t){let n=new T().registerSkipController(new H(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(l,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};un.ActionTypes=ss;var pn=class pn extends ae{constructor(t,n={}){super();this.choices=[];this.prompt=Se.isSentence(t)?t:t===null?null:new Se(t),this.config=z(pn.defaultConfig,n)}static prompt(t,n={}){return new pn(t!==void 0?t:null,n)}static choose(t,n){return new pn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return Se.isSentence(t)&&n?i.choices.push({prompt:Se.toSentence(t),action:this.narrativeToActions(n),config:{}}):(J.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:Se.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:Se.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?j.from(t.config.disabled):void 0,hidden:t.config?.hidden?j.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Me("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=j.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Me("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=j.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:j.not(j.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:j.not(j.from(t))}})}fromChained(t){return[new un(this.chain(),un.ActionTypes.action,new w().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?Kt.say(n).getActions():Ve.toActions([n])))}constructNodes(t,n,i){for(let r=0;r<t.length;r++){let s=t[r].contentNode,a=t[r+1]?.contentNode;a&&s.setChild(a),r===this.choices.length-1&&n&&s.setChild(n),r===0&&i&&i.setChild(s)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};pn.defaultConfig={},pn.targetAction=un;var qo=pn;var Dt=class Dt extends rt{static get DefaultUserConfig(){return Dt._defaultUserConfig??(Dt._defaultUserConfig=new B({...Q.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e={}){super();let t=Dt.DefaultUserConfig.create(e),n=Dt.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}reset(e,t){return this.transform(new Y({position:new it("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,filter:"none"},{duration:e,ease:t}))}toData(){return{transformState:this.transformState.serialize()}}fromData(e){return this.transformState=Q.deserialize(e.transformState),this}copy(){return new Dt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(Q.DefaultTransformState.keys());return new Q(Q.DefaultTransformState.create(e.get()).get())}};Dt._defaultUserConfig=null,Dt.DefaultConfig=new B({name:"(camera)"});var qn=Dt;var en=class en extends An{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.name=t;let{camera:i,...r}=n;this.config=z(en.defaultConfig,r),this._camera=i??new qn}static empty(){return new en("empty").entry(new ut("empty"))}get camera(){return this._camera}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new xn(t,n);return this.registerPersistent(i),i}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new Me(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return ys(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,i)=>{if(!n.serialize||typeof n.serialize!="function")return;let r=n.serialize();if(r!==null){{if(r instanceof Promise)throw new te(`Service ${i} serialize method should not return a promise`);if(!No(r))throw new te(`Service ${i} serialize method should return a pure object.
22
+ Parent Conflict (src: `+d.get(y)?.state.currentSrc+`)
23
+ Current Parent (src: `+m.state.currentSrc+")");d.set(y,m)}});let p=[...this._initScene(this),...l.map(m=>m._init(this)),...u.map(m=>{if(!d.has(m))throw new Error("Wearable image must have a parent image");return d.get(m)._initWearable(m)}),...a.map(m=>m._init()),...c.map(m=>m._init()),...r],g=super.constructNodes(p),h=new C(this.sceneRoot,void 0,g||void 0).setContent(this);return g?.setParent(h),this.sceneRoot?.setContentNode(h),this._futureActions_=p,this.constructLabels(t),this}constructLabels(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!1}),i=new Map;for(let r of n)if(r instanceof oe&&r.type===ne.label){let[s]=r.contentNode.getContent();if(i.has(s))throw new Ve(`Duplicate label "${s}" in scene "${this.config.name}". Label names must be unique within a scene.`);i.set(s,r)}this.labelMap=i;for(let r of n)if(r instanceof oe&&r.type===ne.jump){let[s]=r.contentNode.getContent(),a=i.get(s);if(!a)throw new Ve(`Jump target label "${s}" not found in scene "${this.config.name}". Control.jump can only jump to a Control.label declared in the same scene.`);r.setJumpTarget(a)}}getLabel(t){return this.labelMap.get(t)||null}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?$t.say(n).getActions():Oe.toActions([n]))}isSceneRootConstructed(){return!!this.sceneRoot}registerSrc(t,n=new Set){if(!this.sceneRoot)return;let i=new Set,r=new Set,s=[this.sceneRoot],a=new Set;for(;s.length;){let c=s.shift();if(!i.has(c)){if(i.add(c),c instanceof pe){let l=c.callee;if(k.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:k.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===J.jumpTo){let u=c,d=He.getScene(t,u.contentNode.getContent()[0]);if(!d)throw c._sceneNotFoundError(c.getSceneName(u.contentNode.getContent()[0]));let p=Le.getPreloadableSrc(t,c);if(p&&this.srcManager.register(p),r.has(u)||n.has(d))continue;r.add(u),a.add(d),n.add(d)}}else if(c instanceof ge){let l=Le.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof et)this.srcManager.register(c.callee);else if(c instanceof nt){let l=c.type===zt.say?c.contentNode.getContent():null;for(let u of Ws(c.callee,l))this.srcManager.register({type:"image",src:k.srcToURL(u)})}else if(c instanceof oe){let u=c.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else c instanceof Ie&&this.srcManager.register(c.callee.srcManager.getSrc());s.push(...c.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(c=>{c.registerSrc(t,n),this.srcManager.registerFuture(c.srcManager)})}assignActionId(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}),i=new Set;n.forEach(a=>{let c=a.getStaticId();if(c){if(i.has(c))throw new Ve(`Duplicate static action id: ${c}`);i.add(c)}});let r=0,s=()=>{let a=`a-${r++}`;for(;i.has(a);)a=`a-${r++}`;return i.add(a),a};n.forEach(a=>{let c=a.getStaticId();a.resolveId(c||s())})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((i,r)=>{i.resolveId(`e-${r}`)})}getVoice(t){if(!t)return null;let n=this.config.voices;if(n){if(typeof n=="function"){let r=n(t);return typeof r=="string"?this.voiceOfSrc(r):(He.validateVoice(r),r)}let i=n[t];return typeof i=="string"?this.voiceOfSrc(i):i||null}return null}voiceOfSrc(t){let n=this.voiceCache.get(t);if(n)return n;let i=Ae.voice(t);return this.voiceCache.set(t,i),i}getSceneRoot(){if(!this.sceneRoot)throw new Error("Scene root is not constructed");return this.sceneRoot}stringify(t,n,i){return super.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).map(r=>r.stringify(t,n,i)).join(";")}reset(){super.reset(),this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&!Hi(t.backgroundMusic.config.type,[tt.bgm]))throw new Ve(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
24
+ To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new L({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new pe(this.chain(),"scene:jumpTo",new C().setContent([t])))}_exit(){return new pe(this.chain(),"scene:exit",new C().setContent([]))}_transitionToScene(t,n){let i=this.chain();if(t&&n){let r=this.state.backgroundImage.char(n,t);i.chain(r.getActions())}return i}_init(t){return new pe(this.chain(),"scene:init",new C().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};He.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},He.DefaultUserConfig=new K({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),He._defaultSceneConfig=null;var mt=He;import*as Qs from"howler";var $i=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let i=[],r=[],s=[];return this.prefix?(i.push(`%c${this.prefix} [${t}]`),r.push(`color: ${e}`)):(i.push(`%c[${t}]`),r.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(i.push(`%c${a}`),r.push(`color: ${e}`)):(i.push("%O"),s.push(a),r.push(""))}),[i.join(" ")].concat(r,s)}};var Nc={volume:1,limit:1/0},Gc=class $s{constructor(e,t,n,i){this.subChannels=new Map,this.tokens=new Set,this.tokenQueue=[],this.muted=!1,this.removed=!1,this.name=e,this.audioProvider=t,this.parentChannel=i??null,this.options={...Nc,...n},this.volume=this.options.volume;let r=this.audioProvider.getAudioContext();this.gainNode=r.createGain(),this.gainNode.gain.value=this.muted?0:this.volume,this.connectToParent()}connectToParent(){this.parentChannel?this.gainNode.connect(this.parentChannel.getGainNode()):this.gainNode.connect(this.audioProvider.getAudioContext().destination)}getGainNode(){return this.gainNode}ensureNotRemoved(){if(this.removed)throw new Error(`Channel "${this.name}" has been removed and cannot be used.`)}getName(){return this.name}async play(e,t){if(this.ensureNotRemoved(),this.tokens.size>=this.options.limit){let r=this.tokenQueue.shift();r&&r.stop()}let n=await this.audioProvider.createToken(e,t,this.gainNode);this.tokens.add(n),this.tokenQueue.push(n);let i=()=>{this.tokens.delete(n);let r=this.tokenQueue.indexOf(n);r!==-1&&this.tokenQueue.splice(r,1)};return n.once("ended",i),n.once("stop",i),n}createChannel(e,t){if(this.ensureNotRemoved(),this.subChannels.has(e))throw new Error(`Channel "${e}" already exists under "${this.name}".`);this.audioProvider.checkChannelLimit();let n=new $s(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},js=!1;function Vc(o){js=o}function on(o,e){js||(e!==void 0?console.warn(o,e):console.warn(o))}var Hc=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.eventListeners=new Map,this.audioContext=o,this.gainNode=e}setSource(o){this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.setupEventListeners()}getSource(){return this.currentSource}refreshSource(o){let e=new Map(this.eventListeners);this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.eventListeners=e,this.setupEventListeners()}disconnectSource(){if(this.currentSource){if(this.removeAllEventListeners(),this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.disconnect()}catch(o){on("Failed to disconnect AudioBufferSourceNode in disconnectSource().",o)}else this.currentSource instanceof HTMLAudioElement&&(this.currentSource.pause(),this.currentSource.src="",this.currentSource.load());if(this.mediaElementSource){try{this.mediaElementSource.disconnect()}catch(o){on("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=o=>{this.emit("ended")},this.currentSource instanceof HTMLAudioElement?this.currentSource.addEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.addEventListener("ended",this.endedHandler))}removeAllEventListeners(){!this.currentSource||!this.endedHandler||(this.currentSource instanceof HTMLAudioElement?this.currentSource.removeEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.removeEventListener("ended",this.endedHandler),this.endedHandler=null)}emit(o){let e=this.eventListeners.get(o);e&&[...e].forEach((t,n)=>{try{t.callback()}catch(i){console.error(`Error in event listener for '${o}':`,i)}t.once&&e.splice(e.indexOf(t),1)})}on(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!1})}off(o,e){let t=this.eventListeners.get(o);if(!t)return;let n=t.findIndex(i=>i.callback===e);n!==-1&&t.splice(n,1)}once(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!0})}stop(){if(this.currentSource){if(this.currentSource instanceof HTMLAudioElement)this.currentSource.pause(),this.currentSource.currentTime=0;else if(this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.stop()}catch(o){on("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){this.currentSource instanceof AudioBufferSourceNode?this.currentSource.start(o,e):this.currentSource instanceof HTMLAudioElement&&this.currentSource.play()}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},zs=class{constructor(o,e){this.token=o,this.endVolume=e,this.cancelled=!1,this.finishedInternal=!1,this._finished=new Promise(t=>{this.resolveFinished=t})}get finished(){return this._finished}cancel(){this.cancelled||this.finishedInternal||(this.cancelled=!0,this.resolveFinished())}finish(){this.finishedInternal||(this.finishedInternal=!0,this.token.setVolume(this.endVolume),this.resolveFinished())}isCancelled(){return this.cancelled}isFinished(){return this.finishedInternal}getTargetVolume(){return this.endVolume}},Fc=class{constructor(o,e,t={},n){this._isPlaying=!1,this._isPaused=!1,this._isMuted=!1,this.volume=1,this.rate=1,this.contextStartTime=0,this.startOffset=0,this.pauseOffset=0,this.duration=0,this.currentFade=null,this.audioContext=o,this.volume=t.volume??1,this.rate=t.rate??1,this.startOffset=t.startOffset??0,this.duration=t.duration??0,this.outputNode=n??o.destination,this.gainNode=o.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.outputNode),this.sourceController=new Hc(o,this.gainNode),this.sourceController.setSource(e);let i=this.startOffset;this.sourceController.start(0,i),this.contextStartTime=this.audioContext.currentTime,this._isPlaying=!0,this.duration>0&&setTimeout(()=>{this._isPlaying&&this.stop()},this.duration*1e3)}emit(o){if(this.sourceController.emit(o),o==="ended"){this._isPlaying=!1;try{this.gainNode.disconnect()}catch(e){on("Failed to disconnect gain node on natural end.",e)}}}setVolume(o){return this.currentFade&&(this.currentFade.cancel(),this.currentFade=null),o=Math.max(0,Math.min(1,o)),this.volume=o,this._isMuted||(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=o),this}getVolume(){return this.volume}mute(o){let e=o!==void 0?o:!0;if(this._isMuted=e,this.currentFade&&!this.currentFade.isFinished()&&!this.currentFade.isCancelled()){let t=this.currentFade.getTargetVolume();this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.volume=t,this.gainNode.gain.value=e?0:t,this.currentFade.finish(),this.currentFade=null}else this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=e?0:this.volume;return this}unmute(){return this.mute(!1)}isMuted(){return this._isMuted}pause(){if(!this._isPlaying||this._isPaused)return this;let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?(o.pause(),this.pauseOffset=o.currentTime):o instanceof AudioBufferSourceNode&&(this.pauseOffset=this.getCurrentTime(),this.sourceController.stop()),this._isPlaying=!1,this._isPaused=!0,this.emit("pause"),this}resume(){if(!this._isPaused)return this;let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement){let e=o.play();e&&typeof e.catch=="function"&&e.catch(()=>{this._isPlaying=!1,this._isPaused=!0})}else if(o instanceof AudioBufferSourceNode){let e=this.audioContext.createBufferSource();e.buffer=o.buffer,e.playbackRate.value=this.rate,e.loop=o.loop,e.loopStart=o.loopStart,e.loopEnd=o.loopEnd,this.sourceController.refreshSource(e),this.startOffset=this.pauseOffset,this.contextStartTime=this.audioContext.currentTime,this.sourceController.start(0,this.pauseOffset)}return this._isPlaying=!0,this._isPaused=!1,this.emit("resume"),this}isPlaying(){return this._isPlaying}isPaused(){return this._isPaused}stop(o={}){let{fadeDuration:e=0}=o;return e>0?this.fade(this.getVolume(),0,e).finished.then(()=>{this.doStop()}):this.doStop(),this}doStop(){this.sourceController.stop(),this._isPlaying=!1,this._isPaused=!1,this.emit("stop"),this.sourceController.destroy();try{this.gainNode.disconnect()}catch(o){on("Failed to disconnect gain node on stop().",o)}}setRate(o){o=Math.max(.001,o),this.rate=o;let e=this.sourceController.getSource();return e instanceof HTMLAudioElement?e.playbackRate=o:e instanceof AudioBufferSourceNode&&(e.playbackRate.value=o),this}getRate(){return this.rate}seek(o){o=Math.max(0,o);let e=this.sourceController.getSource();if(e instanceof HTMLAudioElement)e.currentTime=o,this.emit("seek");else if(e instanceof AudioBufferSourceNode){let t=this.getCurrentTime();if(Math.abs(o-t)>.01){if(this._isPlaying){this.sourceController.stop();let n=this.audioContext.createBufferSource();n.buffer=e.buffer,n.playbackRate.value=this.rate,n.loop=e.loop,n.loopStart=e.loopStart,n.loopEnd=e.loopEnd,this.sourceController.refreshSource(n),this.startOffset=this.audioContext.currentTime-o,this.sourceController.start(0,o)}else this._isPaused&&(this.pauseOffset=o);this.emit("seek")}}return this}getCurrentTime(){let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement)return o.currentTime;if(o instanceof AudioBufferSourceNode){if(this._isPaused)return this.pauseOffset;if(this._isPlaying)return(this.audioContext.currentTime-this.contextStartTime)*this.rate+this.startOffset}return 0}getDuration(){let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?o.duration||0:o instanceof AudioBufferSourceNode&&o.buffer?o.buffer.duration:this.duration}fade(o,e,t){if(this.currentFade&&this.currentFade.cancel(),o=Math.max(0,Math.min(1,o)),e=Math.max(0,Math.min(1,e)),t=Math.max(0,t),t===0){this.setVolume(e);let r=new zs(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new zs(this,e);this.currentFade=n;let i=this.audioContext.currentTime;return this.gainNode.gain.setValueAtTime(o,i),this.gainNode.gain.linearRampToValueAtTime(e,i+t/1e3),setTimeout(()=>{!n.isCancelled()&&!n.isFinished()&&(this.volume=e,n.finish(),this.currentFade=null)},t),n}on(o,e){return this.sourceController.on(o,e),this}off(o,e){return this.sourceController.off(o,e),this}once(o,e){return this.sourceController.once(o,e),this}},Uc=class{constructor(o){this.alive=!0,this.refCount=0,this.audioBuffer=o}addRef(){this.refCount++}releaseRef(){this.refCount>0&&this.refCount--}getRefCount(){return this.refCount}async unload(){this.refCount>0||(this.alive=!1)}async forceUnload(){this.alive=!1,this.refCount=0}isAlive(){return this.alive}raw(){if(!this.alive)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}},Oc=10*1024*1024,Bc=class{constructor(o){this.cache=new Map,this.loadingPromises=new Map,this.audioContext=o}async load(o){let e=this.cache.get(o);if(e&&e.isAlive())return e;let t=this.loadingPromises.get(o);if(t)return t;let n=this.doLoad(o);this.loadingPromises.set(o,n);try{let i=await n;return this.cache.set(o,i),i}finally{this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new Uc(t)}clear(){for(let o of this.cache.values())o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size}}},Kc={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},qs=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...Kc,...o},Vc(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new Bc(this.audioContext),this.masterChannel=new Gc("__master__",this,{volume:this.options.volume},null),this.initialize()}async onceReady(){return this.readyPromise?(await this.readyPromise,this):this}initialize(){this.isReady||(this.readyPromise=this.waitForUnlock())}waitForUnlock(){return typeof document>"u"?(this.isReady=!0,Promise.resolve()):this.audioContext.state==="running"?(this.isReady=!0,Promise.resolve()):new Promise(o=>{let e=()=>{if(this.destroyed){this.clearUnlockHandler(),o();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,o())}).catch(t=>{on("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let d=new Fc(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,g=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",g),d.once("stop",g)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<Oc?"full":"stream"}catch(t){return on("Failed to resolve load mode via HEAD request, falling back to 'stream'.",t),"stream"}}createStreamSource(o){let e=new Audio(o);return e.crossOrigin="anonymous",e}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(o){this.registeredChannels.add(o)}unregisterChannel(o){this.registeredChannels.delete(o)}setVolume(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(o),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(o){return this.ensureNotDestroyed(),this.ensureReady(),o===void 0?this.masterChannel.mute():this.masterChannel.mute(o),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(o,e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(o,e)}getChannel(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(o)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(o){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(o)}async play(o,e){this.ensureNotDestroyed(),this.ensureReady();let t=this.masterChannel.getTokens();for(let n of t)try{n.stop()}catch{}return this.masterChannel.play(o,e)}getTokens(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getTokens()}destroy(){this.destroyed||(this.destroyed=!0,this.clearUnlockHandler(),this.audioCache.clear(),this.masterChannel.remove(),this.registeredChannels.clear(),this.audioContext.close().catch(o=>{on("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var ye=class ye{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new qs({maxChannels:ye.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=ye.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,ye.BusRampTimeConstant),r.setValueAtTime(s,a+ye.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${tt.sound}" instead.`)),this.channels.get(tt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=ye.defaultFade(e)){let n=new T;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=ye.clipRegionOf(e),a=await i.play(r,{volume:0,...ye.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ye.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(l=>{a.once("ended",()=>l())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=ye.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new P(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=ye.clipRegionOf(e),s=await n.play(i,{volume:0,...ye.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ye.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new T;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new T;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}pause(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),i.token.fade(0,i.originalVolume,t).finished.then(()=>{e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return T.resolve(void 0);let n=this.state.get(e),i=ye.clampToRegion(t,ye.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),T.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,T.resolve(void 0)):T.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=ye.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...ye.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&ye.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(ye.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c,e.state.paused?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};ye.MaxChannels=1024,ye.BusRampTimeConstant=.02,ye.BusRampSettle=ye.BusRampTimeConstant*5;var ji=ye;import*as Wc from"html-to-image";var qi=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new Q}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new T,n=new Ne(t);return t.registerSkipController(new V(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};var Qi=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=Ii(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var Xi=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??Ii(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var fn=class extends ${executeAction(e,t){let n=new T().registerSkipController(new V(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(l,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};fn.ActionTypes=gs;var hn=class hn extends ue{constructor(t,n={}){super();this.choices=[];this.prompt=Se.isSentence(t)?t:t===null?null:new Se(t),this.config=z(hn.defaultConfig,n)}static prompt(t,n={}){return new hn(t!==void 0?t:null,n)}static choose(t,n){return new hn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return Se.isSentence(t)&&n?i.choices.push({prompt:Se.toSentence(t),action:this.narrativeToActions(n),config:{}}):(Z.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:Se.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:Se.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?j.from(t.config.disabled):void 0,hidden:t.config?.hidden?j.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Ve("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=j.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Ve("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=j.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:j.not(j.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:j.not(j.from(t))}})}fromChained(t){return[new fn(this.chain(),fn.ActionTypes.action,new C().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?$t.say(n).getActions():Oe.toActions([n])))}constructNodes(t,n,i){for(let r=0;r<t.length;r++){let s=t[r].contentNode,a=t[r+1]?.contentNode;a&&s.setChild(a),r===this.choices.length-1&&n&&s.setChild(n),r===0&&i&&i.setChild(s)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};hn.defaultConfig={},hn.targetAction=fn;var _o=hn;var Mt=class Mt extends ct{static get DefaultUserConfig(){return Mt._defaultUserConfig??(Mt._defaultUserConfig=new K({...Y.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e={}){super();let t=Mt.DefaultUserConfig.create(e),n=Mt.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}resetCamera(e,t){return this.transform(new _({position:new st("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,filter:"none"},{duration:e,ease:t}))}reset(){return super.reset(),this.transformState=this.getInitialTransformState(),this}toData(){return{transformState:this.transformState.serialize()}}fromData(e){return this.transformState=Y.deserialize(e.transformState),this}copy(){return new Mt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(Y.DefaultTransformState.keys());return new Y(Y.DefaultTransformState.create(e.get()).get())}};Mt._defaultUserConfig=null,Mt.DefaultConfig=new K({name:"(camera)"});var Yn=Mt;var rn=class rn extends kn{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.name=t;let{camera:i,...r}=n;this.config=z(rn.defaultConfig,r),this._camera=i??new Yn}static empty(){return new rn("empty").entry(new mt("empty"))}get camera(){return this._camera}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new Pn(t,n);return this.registerPersistent(i),i}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new Ve(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return Ps(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,i)=>{if(!n.serialize||typeof n.serialize!="function")return;let r=n.serialize();if(r!==null){{if(r instanceof Promise)throw new ie(`Service ${i} serialize method should not return a promise`);if(!Oo(r))throw new ie(`Service ${i} serialize method should return a pure object.
25
25
  A pure object should:
26
26
  1. be an object literal
27
27
  2. not have any prototype
28
28
  3. no circular reference
29
29
  4. sub objects should also be pure objects or serializable data
30
30
  Return null if nothing needs to be saved. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description
31
- Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(ut.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||te,[`Scene with name ${t} not found`]);return r}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this}getAllElementStates(){return this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).map(n=>({id:n.getId(),data:n.toData()})).filter(n=>!!n.data)}constructSceneRoots(t){let n=new Set,i=[],r=0;for(t.constructSceneRoot(this),i.push(t.getSceneRoot());i.length;){if(r++,r>en.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${en.MAX_DEPTH})`);let s=i.shift();if(ut.isScene(s.callee)){if(n.has(s.callee))continue;s.callee.isSceneRootConstructed()||s.callee.constructSceneRoot(this),n.add(s.callee)}let a=s.getFutureActions(this,{allowFutureScene:!0});i.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new $i(t).run(this)}};en.defaultConfig={origin:"bottom left"},en.MAX_DEPTH=32767;var Qn=en;var ji=class extends ${executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(Ce.getCtx({gameState:e}),n,i);return T.isAwaitable(r)?T.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var Qo=class extends ae{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let i=this.chain();return i.chain(this._createAction(i,t,n))}triggerAction(t,n,i){let r=this._handlers[n];if(!r){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(fs(r)){let s=[],a=new T().registerSkipController(new H(()=>{for(let l of s)l?.()}));return r({...t,onAbort:l=>{s.push(l)}},...i).then(()=>a.resolve()),a}r({...t,onAbort:()=>{}},...i)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,i){return new ji(t,"service:action",new w().setContent([n,i]))}},Xo=class extends Qo{},Xn=class extends Xo{};var Lt=class Lt extends ${executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(Lt,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(Lt,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(Lt,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(Lt,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(Lt,"video:show")){let s=i.state.display;return e.isVideoAdded(i)||(e.addVideo(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,a=>{i.state.display=a},[s]),this.changeState(e,a=>a.show(),t)}else if(n.is(Lt,"video:hide")){let s=i.state.display;return this.changeState(e,a=>{i.state.display=!1,e.actionHistory.push(r,c=>{i.state.display=c},[s]),a.hide(),e.removeVideo(i),e.stage.update()},t)}else if(n.is(Lt,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new L(`Video is being used before it is added to the game
32
- Use video.show() to add the video to the game`);let i=this.callee,r=new T,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new H(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};Lt.ActionTypes=Ct;var qi=Lt;var Pn=class Pn extends ae{constructor(e){super();let t=Pn.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new te("Video must have a src")}show(){return this.chain(this.createAction(Ct.show,[]))}hide(){return this.chain(this.createAction(Ct.hide,[]))}play(){return this.chain(this.createAction(Ct.play,[]))}pause(){return this.chain(this.createAction(Ct.pause,[]))}resume(){return this.chain(this.createAction(Ct.resume,[]))}stop(){return this.chain(this.createAction(Ct.stop,[]))}seek(e){return this.chain(this.createAction(Ct.seek,[e]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return this.state=this.getInitialState(),this}getInitialState(){return Pn.DefaultVideoState.create().get()}createAction(e,t){return new qi(this.chain(),e,w.create(t))}};Pn.DefaultVideoConfig=new B({src:"",muted:!1}),Pn.DefaultVideoState=new B({display:!1});var Jo=Pn;var tn=class tn extends ${executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(tn,"vfx:show")){let[s]=n.contentNode.getContent(),a=i.state.display;return e.isVfxAdded(i)||(e.addVfx(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,c=>{i.state.display=c},[a]),this.changeStateAsync(e,c=>c.show(s),t)}else if(n.is(tn,"vfx:hide")){if(!e.isVfxAdded(i))return e.logger.weakWarn("NarraLeaf-React: Vfx","Hiding a Vfx that is not shown, ignored. (src: "+i.config.src+")"),T.resolve(super.executeAction(e,t));let[s]=n.contentNode.getContent(),a=i.state.display;return this.changeStateAsync(e,async c=>{await c.hide(s),i.state.display=!1,e.actionHistory.push(r,l=>{i.state.display=l},[a]),e.removeVfx(i),e.stage.update()},t)}else{if(n.is(tn,"vfx:pause"))return this.changeState(e,s=>{i.state.paused=!0,s.pause()},t);if(n.is(tn,"vfx:resume"))return this.changeState(e,s=>{i.state.paused=!1,s.resume()},t);if(n.is(tn,"vfx:setRate"))return this.changeState(e,s=>s.setRate(n.contentNode.getContent()[0]),t)}throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVfxAdded(this.callee))throw new L(`Vfx is being used before it is added to the game
33
- Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new T,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Vfx Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new H(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VfxAction")}};tn.ActionTypes=Qt;var Qi=tn;var En=class En extends ae{constructor(e){super();let t=En.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new te("Vfx must have a src")}show(e){return this.chain(this.createAction(Qt.show,[e]))}hide(e){return this.chain(this.createAction(Qt.hide,[e]))}pause(){return this.chain(this.createAction(Qt.pause,[]))}resume(){return this.chain(this.createAction(Qt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Qt.setRate,[e]))}toData(){return{state:{display:this.state.display,paused:this.state.paused}}}fromData(e){let{state:t}=e;return this.state={display:t.display,paused:t.paused},this}reset(){return this.state=this.getInitialState(),this}getInitialState(){return En.DefaultVfxState.create().get()}createAction(e,t){return new Qi(this.chain(),e,w.create(t))}};En.DefaultVfxConfig=new B({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),En.DefaultVfxState=new B({display:!1,paused:!1});var Yo=En;var de=class de{constructor(e,t){this.state={sounds:[],videos:[],vfx:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new Gn;this.htmlToImage=Mc;this.pageRouter=null;this.stageClickBuffer=null;this.nvlAdvanceWaiters=new Map;this.advDialogState=null;this._fastForwarding=!1;this.stage=t,this.game=e,this.events=new q,this.logger=new Oi(e,"NarraLeaf-React"),this.audioManager=new Ki(this),this.guard=new Mi(e.config.app.guard).observe(this),this.timelines=new Ni(this.guard),this.notificationMgr=new Bi(this,[]),this.idManager=new Ti,this.actionHistory=new Wi(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new zi(this.actionHistory)}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}addVfx(e){return this.state.vfx.push(e),this}removeVfx(e){let t=this.state.vfx.indexOf(e);return t===-1?(this.logger.weakWarn("Vfx not found when removing",e.getId()),this):(this.state.vfx.splice(t,1),this)}isVfxAdded(e){return this.state.vfx.includes(e)}getVfx(){return this.state.vfx}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=ut.isScene(e)?e:e.entryScene;if(!t)throw new L("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(de.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}getCurrentScene(){return this.state.elements[0]?.scene||null}isFastForwarding(){return this._fastForwarding}setFastForwarding(e){this._fastForwarding=e}hasActiveMenu(){let e=this.getLastScene();return e?(this.findElementByScene(e)?.menus.length??0)>0:!1}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map($o);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let c=s[a];for(let l=c.length-1;l>=0;l--){let u=c[l],d=r.get(u);if(d&&this.isDisplayableVisible(u))return d}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(Ce.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Pt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:J.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1)},text:J.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(Ce.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(Pt.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?J.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(de.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(de.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(de.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(de.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>ce.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(de.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(de.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{ce.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(de.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(de.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}beginAdvDialog(e,t){return this.advDialogState={dialogId:e,actionId:t,ended:!1},this.events.emit(de.EventTypes["event:state.dialog.change"]),this}completeAdvDialogTyping(e){return!e||!this.advDialogState||this.advDialogState.dialogId!==e?this:(this.advDialogState.ended||(this.advDialogState.ended=!0,this.events.emit(de.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(de.EventTypes["event:state.dialog.change"])),this}getAdvDialogState(){return this.advDialogState}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new L(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.state.vfx=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Hs.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new L("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=Ie.proxy(T.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof rt&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(Y.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync(),"flush"in r&&r.flush()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new Ge("State already mounted");if(!e)throw new Ge("Invalid state key");return this.exposedState.set(e,t),this.events.emit(de.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new L("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let i=this.events.on(de.EventTypes["event.state.onExpose"],(r,s)=>{r===e&&(t(s),i.cancel())});return i}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(i=>i.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),vfx:this.state.vfx.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e;if(i.forEach(({sceneId:a,elements:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new L("Scene not found, id: "+a+`
34
- NarraLeaf cannot find the element with the id from the saved game`);let u={scene:l,layers:this.constructLayerMap(c.layers,t),menus:[],texts:[]};this.state.elements.push(u),this.registerSrcManager(l.srcManager),this.getExposedStateAsync(l,d=>{ce.initBackgroundMusic(l,d)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,c])=>{let l=t.get(a);if(!l)throw new L("Video not found, id: "+a+`
35
- NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),this.state.vfx=(e.vfx??[]).map(([a,c])=>{let l=t.get(a);if(!l)throw new L("Vfx not found, id: "+a+`
36
- NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(c=>{let l=c.characterId&&t.get(c.characterId)||null,u=c.text||"";return{id:c.id,actionId:c.actionId||c.id,character:l,sentence:new Se(u,{character:l}),text:u}});this.nvlState={active:e.nvlState.active,visible:e.nvlState.visible,sessionId:e.nvlState.sessionId,dialogs:a,options:e.nvlState.options||null,activeDialogId:e.nvlState.activeDialogId||null,phase:e.nvlState.phase||(e.nvlState.activeDialogId?"awaitAdvance":"idle"),pendingAdvance:e.nvlState.pendingAdvance||!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active&&this.events.emit(de.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],!0,this.nvlState.options?.showTransition),this.emitNvlStateChange()}}getLastSceneIfNot(e){let t=e||this.getLastScene();if(!t||!this.sceneExists(t))throw new L('Scene not found, please call "scene.activate()" first.');return t}createElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(i=>[i,i.toData()])]))}}fromElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(([i,r])=>(i.fromData(r),i))])),texts:[],menus:[]}}removeElements(e){let t=this.state.elements.findIndex(n=>n.scene===e);return t===-1?(this.logger.weakWarn("Scene not found when removing elements",e.getId()),this):(this.resetLayers(this.state.elements[t].layers),this.state.elements.splice(t,1),this.logger.debug("GameState","Removing elements",e.getId()),this)}resetLayers(e){e.forEach(t=>{t.forEach(n=>{n.reset()})})}syncNvlDerivedState(){this.nvlState.isTyping=this.nvlState.phase==="typing",this.nvlState.activeDialogId||(this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.nvlState.isTyping=!1)}emitNvlStateChange(){this.syncNvlDerivedState(),this.events.emit(de.EventTypes["event:state.nvl.change"],this.getNvlState()),this.stage.update()}resolveNvlAdvance(e){let t=this.nvlAdvanceWaiters.get(e);return t?(this.nvlAdvanceWaiters.delete(e),this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),t(),!0):!1}isDisplayableVisible(e){return(e.transformState.get().opacity??0)>0}createWaitableAction(e,t){return{action:e,onClick:(i=>{t&&t(i)})}}sceneNotFound(){return new L("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new L("Layer not found, target layer may not be activated. You may forget to add the layer to the scene config")}constructLayerMap(e,t){return new Map(Object.entries(e).map(([n,i])=>{let r=t.get(n);if(!r)throw new L("Layer not found, id: "+n+`
37
- NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new L("Displayable not found, id: "+s+`
31
+ Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(mt.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||ie,[`Scene with name ${t} not found`]);return r}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this.captureElementBaseline(),this}captureElementBaseline(){let t=new Map;this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).forEach(n=>{let i=n.toData();i&&t.set(n.getId(),JSON.stringify(i))}),this.elementBaseline=t}getAllElementStates(){let t=this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]),n=this.elementBaseline,i=[];for(let r of t){if(n&&!r.isDirty())continue;let s=r.toData();s&&(n&&JSON.stringify(s)===n.get(r.getId())||i.push({id:r.getId(),data:s}))}return i}findUnmarkedElements(){let t=this.elementBaseline;return t?this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).filter(n=>{if(n.isDirty())return!1;let i=n.toData();return!!i&&JSON.stringify(i)!==t.get(n.getId())}):[]}constructSceneRoots(t){let n=new Set,i=[],r=0;for(t.constructSceneRoot(this),i.push(t.getSceneRoot());i.length;){if(r++,r>rn.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${rn.MAX_DEPTH})`);let s=i.shift();if(mt.isScene(s.callee)){if(n.has(s.callee))continue;s.callee.isSceneRootConstructed()||s.callee.constructSceneRoot(this),n.add(s.callee)}let a=s.getFutureActions(this,{allowFutureScene:!0});i.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new Yi(t).run(this)}};rn.defaultConfig={origin:"bottom left"},rn.MAX_DEPTH=32767;var Jn=rn;var Ji=class extends ${executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(Ce.getCtx({gameState:e}),n,i);return T.isAwaitable(r)?T.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var er=class extends ue{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let i=this.chain();return i.chain(this._createAction(i,t,n))}triggerAction(t,n,i){let r=this._handlers[n];if(!r){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(Cs(r)){let s=[],a=new T().registerSkipController(new V(()=>{for(let l of s)l?.()}));return r({...t,onAbort:l=>{s.push(l)}},...i).then(()=>a.resolve()),a}r({...t,onAbort:()=>{}},...i)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,i){return new Ji(t,"service:action",new C().setContent([n,i]))}},tr=class extends er{},Zn=class extends tr{};var Nt=class Nt extends ${executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(Nt,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(Nt,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(Nt,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(Nt,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(Nt,"video:show")){let s=i.state.display;return e.isVideoAdded(i)||(e.addVideo(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,a=>{i.state.display=a},[s]),this.changeState(e,a=>a.show(),t)}else if(n.is(Nt,"video:hide")){let s=i.state.display;return this.changeState(e,a=>{i.state.display=!1,e.actionHistory.push(r,c=>{i.state.display=c},[s]),a.hide(),e.removeVideo(i),e.stage.update()},t)}else if(n.is(Nt,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new P(`Video is being used before it is added to the game
32
+ Use video.show() to add the video to the game`);let i=this.callee,r=new T,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new V(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};Nt.ActionTypes=Et;var Zi=Nt;var In=class In extends ue{constructor(e){super();let t=In.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ie("Video must have a src")}show(){return this.chain(this.createAction(Et.show,[]))}hide(){return this.chain(this.createAction(Et.hide,[]))}play(){return this.chain(this.createAction(Et.play,[]))}pause(){return this.chain(this.createAction(Et.pause,[]))}resume(){return this.chain(this.createAction(Et.resume,[]))}stop(){return this.chain(this.createAction(Et.stop,[]))}seek(e){return this.chain(this.createAction(Et.seek,[e]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return In.DefaultVideoState.create().get()}createAction(e,t){return new Zi(this.chain(),e,C.create(t))}};In.DefaultVideoConfig=new K({src:"",muted:!1}),In.DefaultVideoState=new K({display:!1});var nr=In;var sn=class sn extends ${executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(sn,"vfx:show")){let[s]=n.contentNode.getContent(),a=i.state.display;return e.isVfxAdded(i)||(e.addVfx(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,c=>{i.state.display=c},[a]),this.changeStateAsync(e,c=>c.show(s),t)}else if(n.is(sn,"vfx:hide")){if(!e.isVfxAdded(i))return e.logger.weakWarn("NarraLeaf-React: Vfx","Hiding a Vfx that is not shown, ignored. (src: "+i.config.src+")"),T.resolve(super.executeAction(e,t));let[s]=n.contentNode.getContent(),a=i.state.display;return this.changeStateAsync(e,async c=>{await c.hide(s),i.state.display=!1,e.actionHistory.push(r,l=>{i.state.display=l},[a]),e.removeVfx(i),e.stage.update()},t)}else{if(n.is(sn,"vfx:pause"))return this.changeState(e,s=>{i.state.paused=!0,s.pause()},t);if(n.is(sn,"vfx:resume"))return this.changeState(e,s=>{i.state.paused=!1,s.resume()},t);if(n.is(sn,"vfx:setRate"))return this.changeState(e,s=>s.setRate(n.contentNode.getContent()[0]),t)}throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVfxAdded(this.callee))throw new P(`Vfx is being used before it is added to the game
33
+ Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new T,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Vfx Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new V(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VfxAction")}};sn.ActionTypes=Jt;var _i=sn;var Rn=class Rn extends ue{constructor(e){super();let t=Rn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ie("Vfx must have a src")}show(e){return this.chain(this.createAction(Jt.show,[e]))}hide(e){return this.chain(this.createAction(Jt.hide,[e]))}pause(){return this.chain(this.createAction(Jt.pause,[]))}resume(){return this.chain(this.createAction(Jt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Jt.setRate,[e]))}toData(){return{state:{display:this.state.display,paused:this.state.paused}}}fromData(e){let{state:t}=e;return this.state={display:t.display,paused:t.paused},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return Rn.DefaultVfxState.create().get()}createAction(e,t){return new _i(this.chain(),e,C.create(t))}};Rn.DefaultVfxConfig=new K({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),Rn.DefaultVfxState=new K({display:!1,paused:!1});var ir=Rn;var me=class me{constructor(e,t){this.state={sounds:[],videos:[],vfx:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new Un;this.htmlToImage=Wc;this.pageRouter=null;this.stageClickBuffer=null;this.nvlAdvanceWaiters=new Map;this.advDialogState=null;this._fastForwarding=!1;this.stage=t,this.game=e,this.events=new Q,this.logger=new $i(e,"NarraLeaf-React"),this.audioManager=new ji(this),this.guard=new Fi(e.config.app.guard).observe(this),this.timelines=new Ui(this.guard),this.notificationMgr=new qi(this,[]),this.idManager=new wi,this.actionHistory=new Qi(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new Xi(this.actionHistory)}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}addVfx(e){return this.state.vfx.push(e),this}removeVfx(e){let t=this.state.vfx.indexOf(e);return t===-1?(this.logger.weakWarn("Vfx not found when removing",e.getId()),this):(this.state.vfx.splice(t,1),this)}isVfxAdded(e){return this.state.vfx.includes(e)}getVfx(){return this.state.vfx}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=mt.isScene(e)?e:e.entryScene;if(!t)throw new P("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(me.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}getCurrentScene(){return this.state.elements[0]?.scene||null}isFastForwarding(){return this._fastForwarding}setFastForwarding(e){this._fastForwarding=e}hasActiveMenu(){let e=this.getLastScene();return e?(this.findElementByScene(e)?.menus.length??0)>0:!1}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map(Jo);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let c=s[a];for(let l=c.length-1;l>=0;l--){let u=c[l],d=r.get(u);if(d&&this.isDisplayableVisible(u))return d}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(Ce.getCtx({gameState:this}));this.game.getLiveGame().events.emit(It.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:Z.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1)},text:Z.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(Ce.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(It.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?Z.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(me.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(me.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(me.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(me.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(me.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(me.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(me.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>pe.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(me.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(me.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(me.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(me.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{pe.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(me.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(me.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}beginAdvDialog(e,t){return this.advDialogState={dialogId:e,actionId:t,ended:!1},this.events.emit(me.EventTypes["event:state.dialog.change"]),this}completeAdvDialogTyping(e){return!e||!this.advDialogState||this.advDialogState.dialogId!==e?this:(this.advDialogState.ended||(this.advDialogState.ended=!0,this.events.emit(me.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(me.EventTypes["event:state.dialog.change"])),this}getAdvDialogState(){return this.advDialogState}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new P(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.state.vfx=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Qs.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new P("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=Ne.proxy(T.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof ct&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(_.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync(),"flush"in r&&r.flush()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new Fe("State already mounted");if(!e)throw new Fe("Invalid state key");return this.exposedState.set(e,t),this.events.emit(me.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new P("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let i=this.events.on(me.EventTypes["event.state.onExpose"],(r,s)=>{r===e&&(t(s),i.cancel())});return i}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(i=>i.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),vfx:this.state.vfx.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e;if(i.forEach(({sceneId:a,elements:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new P("Scene not found, id: "+a+`
34
+ NarraLeaf cannot find the element with the id from the saved game`);let u={scene:l,layers:this.constructLayerMap(c.layers,t),menus:[],texts:[]};this.state.elements.push(u),this.registerSrcManager(l.srcManager),this.getExposedStateAsync(l,d=>{pe.initBackgroundMusic(l,d)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,c])=>{let l=t.get(a);if(!l)throw new P("Video not found, id: "+a+`
35
+ NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),this.state.vfx=(e.vfx??[]).map(([a,c])=>{let l=t.get(a);if(!l)throw new P("Vfx not found, id: "+a+`
36
+ NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(c=>{let l=c.characterId&&t.get(c.characterId)||null,u=c.text||"";return{id:c.id,actionId:c.actionId||c.id,character:l,sentence:new Se(u,{character:l}),text:u}});this.nvlState={active:e.nvlState.active,visible:e.nvlState.visible,sessionId:e.nvlState.sessionId,dialogs:a,options:e.nvlState.options||null,activeDialogId:e.nvlState.activeDialogId||null,phase:e.nvlState.phase||(e.nvlState.activeDialogId?"awaitAdvance":"idle"),pendingAdvance:e.nvlState.pendingAdvance||!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active&&this.events.emit(me.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(me.EventTypes["event:state.nvl.visibilityChange"],!0,this.nvlState.options?.showTransition),this.emitNvlStateChange()}}getLastSceneIfNot(e){let t=e||this.getLastScene();if(!t||!this.sceneExists(t))throw new P('Scene not found, please call "scene.activate()" first.');return t}createElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(i=>[i,i.toData()])]))}}fromElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(([i,r])=>(i.fromData(r),i))])),texts:[],menus:[]}}removeElements(e){let t=this.state.elements.findIndex(n=>n.scene===e);return t===-1?(this.logger.weakWarn("Scene not found when removing elements",e.getId()),this):(this.resetLayers(this.state.elements[t].layers),this.state.elements.splice(t,1),this.logger.debug("GameState","Removing elements",e.getId()),this)}resetLayers(e){let t=this.getLiveGame().story?.camera??null;e.forEach((n,i)=>{i.reset(),n.forEach(r=>{t&&r===t||r.reset()})})}syncNvlDerivedState(){this.nvlState.isTyping=this.nvlState.phase==="typing",this.nvlState.activeDialogId||(this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.nvlState.isTyping=!1)}emitNvlStateChange(){this.syncNvlDerivedState(),this.events.emit(me.EventTypes["event:state.nvl.change"],this.getNvlState()),this.stage.update()}resolveNvlAdvance(e){let t=this.nvlAdvanceWaiters.get(e);return t?(this.nvlAdvanceWaiters.delete(e),this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),t(),!0):!1}isDisplayableVisible(e){return(e.transformState.get().opacity??0)>0}createWaitableAction(e,t){return{action:e,onClick:(i=>{t&&t(i)})}}sceneNotFound(){return new P("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new P("Layer not found, target layer may not be activated. You may forget to add the layer to the scene config")}constructLayerMap(e,t){return new Map(Object.entries(e).map(([n,i])=>{let r=t.get(n);if(!r)throw new P("Layer not found, id: "+n+`
37
+ NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new P("Displayable not found, id: "+s+`
38
38
  NarraLeaf cannot find the element with the id from the saved game
39
- This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};de.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.lineEnd":"event:state.player.lineEnd","event:state.dialog.change":"event:state.dialog.change","event:state.player.requestFlush":"event:state.player.requestFlush","event:state.player.stageClick":"event:state.player.stageClick","event:state.scene.mount":"event:state.scene.mount","event:state.scene.unmount":"event:state.scene.unmount","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes","event:state.nvl.enter":"event:state.nvl.enter","event:state.nvl.exit":"event:state.nvl.exit","event:state.nvl.dialogComplete":"event:state.nvl.dialogComplete","event:state.nvl.dialogAppend":"event:state.nvl.dialogAppend","event:state.nvl.visibilityChange":"event:state.nvl.visibilityChange","event:state.nvl.change":"event:state.nvl.change"};var I=de;var Us=32767,Nc=1e3,je=class o{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.loopConfig=null;this.loopBodyActions=[];this.loopCondition=null;this.loopStartTime=0;this.loopDebugCheckpoint=0;this.__tag=t,this.stack=new Ai().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new Ge("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new Ge("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(T.isAwaitable(i)&&!i.isSettled())throw new Ge("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!T.isAwaitable(n))throw new Ge("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof o}static createStackModel(e,t,n){let i=new o(e);return i.deserialize(t,n),i}static createCountLoop(e,t,n){let i=new o(e,"loop:count");return i.initLoop({type:"count",counter:0,limit:t,bodyActionIds:n.map(r=>r.getId()),broken:!1},n,null),i}static createConditionLoop(e,t,n,i){let r=new o(e,"loop:condition");return r.initLoop({type:"condition",counter:0,conditionActionId:n,bodyActionIds:i.map(s=>s.getId()),broken:!1},i,t),r}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!T.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?T.any(...t.map(n=>n.execute())):T.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}initLoop(e,t,n){this.loopConfig=e,this.loopBodyActions=t,this.loopCondition=n,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=0,this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody()}shouldContinueLoop(e){return!this.loopConfig||this.loopConfig.broken?!1:this.loopConfig.type==="count"?this.loopConfig.counter<(this.loopConfig.limit??0):this.loopCondition?this.loopCondition.evaluate({gameState:e}).value:!1}pushLoopBody(){if(this.loopBodyActions.length!==0)for(let e=this.loopBodyActions.length-1;e>=0;e--)this.stack.push(o.fromAction(this.loopBodyActions[e]))}onIterationComplete(){!this.loopConfig||this.loopConfig.broken||(this.loopConfig.counter++,this.liveGame.game.config.app.debug&&this.checkInfiniteLoop(),this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody())}checkInfiniteLoop(){if(!this.loopConfig)return;let e=this.loopConfig.counter;if(e>0&&e%Us===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=Us&&t<Nc){let i=new L(`[NarraLeaf] Potential infinite loop detected!
39
+ This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};me.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.lineEnd":"event:state.player.lineEnd","event:state.dialog.change":"event:state.dialog.change","event:state.player.requestFlush":"event:state.player.requestFlush","event:state.player.stageClick":"event:state.player.stageClick","event:state.scene.mount":"event:state.scene.mount","event:state.scene.unmount":"event:state.scene.unmount","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes","event:state.nvl.enter":"event:state.nvl.enter","event:state.nvl.exit":"event:state.nvl.exit","event:state.nvl.dialogComplete":"event:state.nvl.dialogComplete","event:state.nvl.dialogAppend":"event:state.nvl.dialogAppend","event:state.nvl.visibilityChange":"event:state.nvl.visibilityChange","event:state.nvl.change":"event:state.nvl.change"};var E=me;var Xs=32767,zc=1e3,Ye=class o{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.loopConfig=null;this.loopBodyActions=[];this.loopCondition=null;this.loopStartTime=0;this.loopDebugCheckpoint=0;this.__tag=t,this.stack=new Pi().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new Fe("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new Fe("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(T.isAwaitable(i)&&!i.isSettled())throw new Fe("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!T.isAwaitable(n))throw new Fe("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof o}static createStackModel(e,t,n){let i=new o(e);return i.deserialize(t,n),i}static createCountLoop(e,t,n){let i=new o(e,"loop:count");return i.initLoop({type:"count",counter:0,limit:t,bodyActionIds:n.map(r=>r.getId()),broken:!1},n,null),i}static createConditionLoop(e,t,n,i){let r=new o(e,"loop:condition");return r.initLoop({type:"condition",counter:0,conditionActionId:n,bodyActionIds:i.map(s=>s.getId()),broken:!1},i,t),r}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!T.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?T.any(...t.map(n=>n.execute())):T.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}initLoop(e,t,n){this.loopConfig=e,this.loopBodyActions=t,this.loopCondition=n,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=0,this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody()}shouldContinueLoop(e){return!this.loopConfig||this.loopConfig.broken?!1:this.loopConfig.type==="count"?this.loopConfig.counter<(this.loopConfig.limit??0):this.loopCondition?this.loopCondition.evaluate({gameState:e}).value:!1}pushLoopBody(){if(this.loopBodyActions.length!==0)for(let e=this.loopBodyActions.length-1;e>=0;e--)this.stack.push(o.fromAction(this.loopBodyActions[e]))}onIterationComplete(){!this.loopConfig||this.loopConfig.broken||(this.loopConfig.counter++,this.liveGame.game.config.app.debug&&this.checkInfiniteLoop(),this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody())}checkInfiniteLoop(){if(!this.loopConfig)return;let e=this.loopConfig.counter;if(e>0&&e%Xs===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=Xs&&t<zc){let i=new P(`[NarraLeaf] Potential infinite loop detected!
40
40
  Loop has executed ${e} iterations in ${t}ms.
41
41
  This is likely a bug in your game script. Check your loop conditions.
42
- Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new L("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(T.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(T.isAwaitable(t)){if(t.isFailed())throw t.error;let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=null,t=!1,n=new T().registerSkipController(new H(()=>{t=!0,e?.abort()}));return(async()=>{let r=0;for(;!t;){if(r++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){if(this.loopConfig&&!this.loopConfig.broken&&(this.onIterationComplete(),!this.stack.isEmpty()))continue;t=!0;break}let s=this.rollNext();if(s){if(T.isAwaitable(s)){if(s.isFailed())throw s.error;if(s.isSettled())continue;if(e=s,await new Promise(a=>{s.onSettled(a)}),s.isFailed())throw s.error;if(s.isAborted()){t=!0;break}}else if(o.isCalledActionResult(s))if(s.wait)e=o.executeStackModelGroup(s.wait.type,s.wait.stackModels),await e;else continue}}})().then(()=>n.resolve()).catch(r=>n.fail(r)),n}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&T.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):o.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getWaitingAwaitable(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&T.isAwaitable(e)&&!e.isSettled()?e:null}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(o.isCalledActionResult(n))return n;if(e)throw new Ge("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}peekTopActionId(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t))return t.node?.action?.getId()??null}return null}peekExecutingActionId(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&o.isCalledActionResult(e)?e.node?.action?.getId()??null:null}snapshot(){let e=[];for(let n=this.stack.size()-1;n>=0;n--){let i=this.stack.get(n);if(!o.isCalledActionResult(i))continue;let r={actionId:i.node?.action?.getId()??null,actionType:i.node?.action?.type??null};i.wait?.stackModels&&(r.branchWaitType=i.wait.type,r.branches=i.wait.stackModels.map(s=>s.snapshot())),e.push(r)}let t={frames:e};return this.__tag&&(t.tag=this.__tag),this.loopConfig&&(t.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,broken:this.loopConfig.broken}),t}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=i=>i?T.isAwaitable(i)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",i),this.stack.push(i),i):i.node?.action?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",i),this.stack.push(i),i):null:null;if(Array.isArray(t)){let i=null;for(let r of t){let s=n(r);s&&(i=s)}return i}else{let i=n(t);if(i)return i}return null}isWaiting(){let e=this.stack.peek();return e?T.isAwaitable(e)?!e.isSettled():o.isCalledActionResult(e)&&e.wait?o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=r=>{if(o.isCalledActionResult(r)){let s=r.node?.action?.getId()??null,a=r.node?.action?.type??null;return r.wait?.stackModels?{type:"link",actionType:a,action:s,stacks:r.wait.stackModels.map(c=>c.serialize()),stackWaitType:r.wait.type}:{type:"action",actionType:a,action:s}}return null},n=this.stack.map(t).filter(function(r){return r!==null});if(e&&this.waitingAction){let r=t(this.waitingAction);r&&n.push(r)}let i={items:n};return this.loopConfig&&(i.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,conditionActionId:this.loopConfig.conditionActionId,bodyActionIds:this.loopConfig.bodyActionIds,broken:this.loopConfig.broken}),i}reset(){this.stack.forEach(e=>{o.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):T.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear(),this.loopConfig=null,this.loopBodyActions=[],this.loopCondition=null,this.loopStartTime=0,this.loopDebugCheckpoint=0}deserialize(e,t){this.reset();let n=e.items;for(let i of n)if(i.type==="action"){if(!i.action)continue;let{actionType:r,action:s}=i,a=t.get(s);if(!a)throw new Error(`Action not found: ${s}`);this.stack.push({type:r,node:a.contentNode,wait:null})}else if(i.type==="link"){let{actionType:r,action:s,stacks:a,stackWaitType:c}=i;if(c==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:c,stackModels:a.map(l=>o.createStackModel(this.liveGame,l,t))}})}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let c=t.get(a);if(!c)throw new Error(`Loop body action not found: ${a}`);r.push(c)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let c=a.contentNode.getContent();Array.isArray(c)&&c.length>=2&&j.isLambda(c[1])&&(s=c[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var Oe=class Oe{constructor(e){this.events=new q;this.story=null;this.gameLock=new gn;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.lastDialog=null;this.mapCache=null;this._currentActionId=null;this.game=e,this._storable=new Hn,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new kt(Oe.GameSpacesKey.game,Oe.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.story;if(!e)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");return{name:this.currentSavedGame.name,meta:{version:Ds,created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:e.hash()},game:{...this.serializeGameState(),history:this.gameState.gameHistory.serialize()}}}serializeGameState(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates(),s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}captureGameState(){try{return this.serializeGameState()}catch(e){return this.gameState?.logger.warn("LiveGame.captureGameState",e),null}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");this.game.hooks.trigger("beforeRestore",[]),t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:i,stage:r,elementStates:s,services:a,stackModel:c,asyncStackModels:l}}=e,[u,d]=this.constructMaps();this.initNamespaces(),this._storable.load(i),s.forEach(({id:p,data:g})=>{t.logger.debug("restore element",p);let y=d.get(p);if(!y)throw new Error("Element not found, id: "+p+`
43
- NarraLeaf cannot find the element with the id from the saved game`);y.reset(),y.fromData(g)}),this.currentSavedGame=e,t.loadData(r,d),this.stackModel.deserialize(c,u),l.forEach(p=>{let g=je.createStackModel(this,p,u);this.asyncStackModels.add(g),t.timelines.attachTimeline(this.executeAsyncStackModel(g))}),n.deserializeServices(a),t.gameHistory.load(e.game.history??[],u),this.game.hooks.trigger("afterRestore",[]),t.events.once(I.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}undo(e){if(this.assertGameState(),!this.gameState.actionHistory.ableToUndo(this.gameState.gameHistory)){this.gameState.logger.warn("LiveGame.undo","No action to undo");return}let t=this.gameLock.register().lock();this.stackModel.abortStackTop();let n=e?this.gameState.actionHistory.undoUntil(e):this.gameState.actionHistory.undo(this.gameState.gameHistory);if(n){let[i]=this.constructMaps(),{rootStackSnapshot:r,stackModel:s}=n;n.action.type===qt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(r,i),s===this.stackModel&&this.stackModel.push(je.fromAction(n.action)),this.gameLock.off(t.unlock()),this.gameState.logger.info("LiveGame.undo","Undo until",e,"action",n),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0)}else this.gameState.logger.warn("LiveGame.undo","No action found"),this.gameLock.off(t.unlock())}restoreToHistory(e){this.assertGameState();let t=this.gameState.gameHistory.getByToken(e);if(!t)return this.gameState.logger.warn("LiveGame.restoreToHistory","No history entry for token",e),!1;if(!t.snapshot)return this.gameState.logger.warn("LiveGame.restoreToHistory","History entry has no restore snapshot",e),!1;let n=this.gameState.gameHistory.serializeUntil(e),i={name:this.currentSavedGame?.name??"",meta:this.currentSavedGame?.meta??this.getNewSavedGame().meta,game:{...t.snapshot,history:n}};return this.deserialize(i),!0}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=T.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new Ae({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(I.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Oe.FastForwardStepTimeout,c=i!==null?{reachedTarget:!1}:{},l=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...c};if(this.stackModel.isEmpty())return{reason:"end",...c};let d=this.stackModel.getWaitingAwaitable();if(d){if(!await Oe.settleSuspendedStep(t,d,a))return{reason:"stalled",...c}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...c}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(l)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,c=d=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(d))};if(a=t.onSettled(()=>c(!0)),r){a?.cancel?.();return}let l=Date.now()+n,u=()=>{if(!r&&(e.events.emit(I.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=l){c(!1);return}s=setTimeout(u,Oe.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Oe.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Oe.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Oe.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(je.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee)},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new je(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new je(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Oe.EventTypes["event:action.current"])&&this.events.emit(Oe.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type});let i=t.executeAction(e,n);return T.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Ge("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new je(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Ge("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[wt].some(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(ce,X.jumpTo)){let[c]=i.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw i.action._sceneNotFoundError(i.action.getSceneName(c));if(a.has(l)){i=null;continue}a.add(l),i=l.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(ne,ee.do)){let[c]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=c[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new Ge("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Ge("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:hs(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new L("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new L("Player Element Not Mounted")}};Oe.DefaultNamespaces={game:{}},Oe.GameSpacesKey={game:"game"},Oe.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Oe.FastForwardStepTimeout=1e4,Oe.FastForwardSkipInterval=16;var Pt=Oe;var Jn=class Jn{constructor(e){this.events=new q;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(Jn.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(Jn.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};Jn.EventTypes={"event:game.preference.change":"event:game.preference.change"};var Yn=Jn;import"client-only";import ka,{useEffect as yu,useRef as Cr}from"react";import"client-only";import Os,{useContext as Ks,useState as Gc}from"react";var Zo=Os.createContext(null);function Bs({children:o,game:e}){"use client";let t=new ie({}),[n]=Gc(e||t);return Os.createElement(Zo,{value:n},o)}function M(){let o=Ks(Zo);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function Ws(){return Ks(Zo)}import Vc,{createContext as Fc,useContext as zs}from"react";var $s="/",Xi=class Xi{constructor(e,t=Xi.rootPath){this.events=new q;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,c]=s.split("=");a&&(i[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let c=a.slice(1);n[c]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new L(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new L(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),nt(()=>{t()}))})}else nt(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};Xi.rootPath=$s;var nn=Xi,_o=Fc(null);function js({children:o}){let e=M();return Vc.createElement(_o,{value:{router:e.router}},o)}function It(){if(!zs(_o))throw new Error("useRouter must be used within a RouterProvider");return zs(_o).router}import Qs from"react";import zc from"clsx";import Hc,{createContext as Uc,useContext as Oc,useLayoutEffect as Kc,useReducer as Bc,useState as Wc}from"react";var Bt=class Bt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new q().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(Bt.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(Bt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(Bt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(Bt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(Bt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(Bt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};Bt.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var er=Bt,tr=Uc(null);function qs({children:o}){"use client";let[e]=Wc(()=>new er);return Hc.createElement(tr,{value:{ratio:e}},o)}function Te(){let o=Oc(tr),[,e]=Bc(n=>n+1,0);if(!tr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return Kc(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function Rt({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=Te(),s=r.getStyle();return Qs.createElement("div",{className:zc("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},Qs.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import $c,{useEffect as jc}from"react";function on(o){let e=M(),[t,n]=$c.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return jc(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import nr from"react";import Ji from"react";import Xs from"clsx";function Yi({children:o,className:e,style:t,...n}){let{ratio:i}=Te(),r=M();return Ji.createElement(Rt,{className:Xs("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},Ji.createElement("div",{className:"absolute inset-0 w-full h-full"},Ji.createElement("div",{className:"inset-0 w-full h-full"},Ji.createElement("div",{className:Xs("pointer-events-auto-rest",e),style:t},o))))}function qc({children:o,className:e,style:t}){return nr.createElement(nr.Fragment,null,nr.createElement(Yi,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import Js from"clsx";import Ys from"react";function Zi({className:o,children:e,...t}){let{ratio:n}=Te();return Ys.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:Js("w-full h-full")},Ys.createElement("div",{className:Js("z-20",o),...t},e))}import mt,{useState as Zs}from"react";import{motion as Qc}from"motion/react";function _i({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=M(),[l,u]=Zs(!1);if(!c.config.app.inspector)return mt.createElement(r,{...a,ref:s},o);let d={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return mt.createElement(r,{...d,ref:s},n&&l&&mt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function Xc({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=M(),[a,c]=Zs(!1);if(!s.config.app.inspector)return mt.createElement(i,{...r});let l={...r,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return mt.createElement("div",null,mt.createElement(i,{...l}),t&&a&&mt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function Jc(o){return mt.createElement(_i,{...o,as:"div"})}function Yc(o){return mt.createElement(_i,{...o,as:"span"})}function Zc(o){return mt.createElement(Xc,{...o,as:"img"})}function _c(o){return mt.createElement(_i,{...o,as:"button"})}function el(o){return mt.createElement(_i,{...o,as:Qc.div,ref:o.ref,layout:o.layout})}var tl={Div:Jc,Span:Yc,Button:_c,Img:Zc,mDiv:el},Mt=tl;import oo from"clsx";import Ke,{useEffect as Ln,useRef as oa,useState as ir}from"react";import{useEffect as nl,useState as il}from"react";function re(o){let[e,t]=il(0);nl(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import _s from"react";var dn=_s.createContext(null);function St(){let o=_s.useContext(dn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import eo,{useCallback as ol,useLayoutEffect as Zn,useMemo as ea,useRef as ta}from"react";import{useIsPresent as rl}from"motion/react";var Tt=class Tt{constructor(e){this.events=new q;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new vi,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e||this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(Tt.Events.complete):this.safeEmit(Tt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Tt.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Tt.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",this.config.gameState.completeAdvDialogTyping(this.config.action.id),e.getPreference(ie.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Tt.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.releaseVoiceWait(),this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Tt.Events.onFlush),this}onFlush(e){return this.events.on(Tt.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;if(!this._active||!e.getPreference(ie.Preferences.autoForward)||this.state!=="ended")return;this.releaseVoiceWait();let t=this.getPlayingVoiceToken();if(!t){this.scheduleAutoForwardDelay();return}let n=()=>{this.releaseVoiceWait(),this.scheduleAutoForwardDelay()};t.once("ended",n),t.once("stop",n),this.voiceWaitDisposer=()=>{t.off("ended",n),t.off("stop",n)}}scheduleAutoForwardDelay(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(ie.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Tt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(ie.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=Ze.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};Tt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Le=Tt;function _n({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=rl(),s=i&&r,a=ta(!1),c=ta(o),l=c.current!==o,u=ea(()=>o.sentence?.evaluate(Ce.getCtx({gameState:n})),[o.sentence,n]),d=ea(()=>new Le({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:l}),[o,n,t,u]),p=n.game.config.dialog,g=ol(y=>{!s||a.current||(a.current=!0,e?.(y))},[s,e]);return Zn(()=>{a.current=!1},[d]),Zn(()=>{c.current=o},[o]),Zn(()=>(d.setActive(s),()=>{d.setActive(!1)}),[d,s]),Zn(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",d),d.events.on(Le.Events.complete,y=>{n.logger.log("NarraLeaf-React: Say","Complete",d.isIdle()),s&&(d.isIdle()||y?g(!1):d.setIdle(!0))}).cancel),[d,g,n,s]),Zn(()=>n.events.on(I.EventTypes["event:state.player.skip"],y=>{s&&(y?(d.setIdle(!0),d.forceSkip()):d.isIdle()?g(!0):d.forceSkip())}).cancel,[d,g,n,s]),eo.createElement(eo.Fragment,null,eo.createElement(dn,{value:d},eo.createElement(p,null)))}import{useEffect as to,useState as cl}from"react";import{useEffect as sl,useState as al}from"react";function mn(o){let e=M(),[t,n]=al(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return sl(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Dn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Dn||{});function no({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=M(),[s]=mn("nextAction"),[a]=cl(()=>{let c=o.firedTextEvents??(o.firedTextEvents=new Set);return new Le({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:c})});return to(()=>{if(!n)return;let c=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},l=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(I.EventTypes["event:state.player.stageClick"],c),d=e.events.on(I.EventTypes["event:state.player.skip"],l);return()=>{u.cancel(),d.cancel()}},[a,o.id,e,n]),to(()=>{if(!n)return;let c=u=>{if(u.repeat||!r.keyMap.match("nextAction",u.key))return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()};if(r.config.useWindowListener){let u=r.getLiveGame().onWindowEvent("keydown",c);return()=>{u.cancel()}}let l=r.getLiveGame().onPlayerEvent("keydown",c);return()=>{l.cancel()}},[a,o.id,r,e,n,s]),to(()=>{let c=a.events.on(Le.Events.complete,l=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!l&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),to(()=>{let c=a.events.on(Le.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{c.cancel()}},[a,n]),a}function ll(o,e){let{expression:t,sound:n}=o.config;if(t){let{image:i,appearance:r}=t;i._setAppearanceSync(r),e.stage.update();let s=e.getExposedState(i);s&&(R.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function io(o,e,t){e.has(o)||(e.add(o),ll(o,t))}function na(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),io(r,e,t)}return n}function*rr(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(Fe.isPause(n.text)){yield Fe.from(n.text);continue}if(ot.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
42
+ Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new P("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(T.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(T.isAwaitable(t)){if(t.isFailed())throw t.error;let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=null,t=!1,n=new T().registerSkipController(new V(()=>{t=!0,e?.abort()}));return(async()=>{let r=0;for(;!t;){if(r++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){if(this.loopConfig&&!this.loopConfig.broken&&(this.onIterationComplete(),!this.stack.isEmpty()))continue;t=!0;break}let s=this.rollNext();if(s){if(T.isAwaitable(s)){if(s.isFailed())throw s.error;if(s.isSettled())continue;if(e=s,await new Promise(a=>{s.onSettled(a)}),s.isFailed())throw s.error;if(s.isAborted()){t=!0;break}}else if(o.isCalledActionResult(s))if(s.wait)e=o.executeStackModelGroup(s.wait.type,s.wait.stackModels),await e;else continue}}})().then(()=>n.resolve()).catch(r=>n.fail(r)),n}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&T.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):o.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getWaitingAwaitable(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&T.isAwaitable(e)&&!e.isSettled()?e:null}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(o.isCalledActionResult(n))return n;if(e)throw new Fe("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}peekTopActionId(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t))return t.node?.action?.getId()??null}return null}peekExecutingActionId(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&o.isCalledActionResult(e)?e.node?.action?.getId()??null:null}snapshot(){let e=[];for(let n=this.stack.size()-1;n>=0;n--){let i=this.stack.get(n);if(!o.isCalledActionResult(i))continue;let r={actionId:i.node?.action?.getId()??null,actionType:i.node?.action?.type??null};i.wait?.stackModels&&(r.branchWaitType=i.wait.type,r.branches=i.wait.stackModels.map(s=>s.snapshot())),e.push(r)}let t={frames:e};return this.__tag&&(t.tag=this.__tag),this.loopConfig&&(t.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,broken:this.loopConfig.broken}),t}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=i=>i?T.isAwaitable(i)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",i),this.stack.push(i),i):i.node?.action?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",i),this.stack.push(i),i):null:null;if(Array.isArray(t)){let i=null;for(let r of t){let s=n(r);s&&(i=s)}return i}else{let i=n(t);if(i)return i}return null}isWaiting(){let e=this.stack.peek();return e?T.isAwaitable(e)?!e.isSettled():o.isCalledActionResult(e)&&e.wait?o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=r=>{if(o.isCalledActionResult(r)){let s=r.node?.action?.getId()??null,a=r.node?.action?.type??null;return r.wait?.stackModels?{type:"link",actionType:a,action:s,stacks:r.wait.stackModels.map(c=>c.serialize()),stackWaitType:r.wait.type}:{type:"action",actionType:a,action:s}}return null},n=this.stack.map(t).filter(function(r){return r!==null});if(e&&this.waitingAction){let r=t(this.waitingAction);r&&n.push(r)}let i={items:n};return this.loopConfig&&(i.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,conditionActionId:this.loopConfig.conditionActionId,bodyActionIds:this.loopConfig.bodyActionIds,broken:this.loopConfig.broken}),i}reset(){this.stack.forEach(e=>{o.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):T.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear(),this.loopConfig=null,this.loopBodyActions=[],this.loopCondition=null,this.loopStartTime=0,this.loopDebugCheckpoint=0}deserialize(e,t){this.reset();let n=e.items;for(let i of n)if(i.type==="action"){if(!i.action)continue;let{actionType:r,action:s}=i,a=t.get(s);if(!a)throw new Error(`Action not found: ${s}`);this.stack.push({type:r,node:a.contentNode,wait:null})}else if(i.type==="link"){let{actionType:r,action:s,stacks:a,stackWaitType:c}=i;if(c==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:c,stackModels:a.map(l=>o.createStackModel(this.liveGame,l,t))}})}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let c=t.get(a);if(!c)throw new Error(`Loop body action not found: ${a}`);r.push(c)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let c=a.contentNode.getContent();Array.isArray(c)&&c.length>=2&&j.isLambda(c[1])&&(s=c[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var Re=class Re{constructor(e){this.events=new Q;this.story=null;this.gameLock=new Tn;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.elementAuditCountdown=0;this.lastDialog=null;this.mapCache=null;this._currentActionId=null;this.game=e,this._storable=new Kn,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new Lt(Re.GameSpacesKey.game,Re.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.story;if(!e)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");return{name:this.currentSavedGame.name,meta:{version:Us,created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:e.hash()},game:{...this.serializeGameState(),history:this.gameState.gameHistory.serialize()}}}serializeGameState(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates();this.auditElementDirtyMarks(t);let s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}auditElementDirtyMarks(e){if(!this.game.config.app.debug||this.elementAuditCountdown-- >0)return;this.elementAuditCountdown=Re.ElementAuditInterval;let t=e.findUnmarkedElements();t.length&&(t.forEach(n=>n.markDirty()),this.gameState?.logger.warn("LiveGame.auditElementDirtyMarks",`${t.length} element(s) had state that no longer matches the script but were never marked dirty, so the save just written left them out. They have been marked, so the next save will carry them - but something is writing element state outside the action dispatch: ${t.map(n=>n.getId()).join(", ")}`))}captureGameState(){try{return this.serializeGameState()}catch(e){return this.gameState?.logger.warn("LiveGame.captureGameState",e),null}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");this.game.hooks.trigger("beforeRestore",[]),t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:i,stage:r,elementStates:s,services:a,stackModel:c,asyncStackModels:l}}=e,[u,d]=this.constructMaps();this.initNamespaces(),this._storable.load(i),d.forEach(p=>p.reset()),s.forEach(({id:p,data:g})=>{t.logger.debug("restore element",p);let h=d.get(p);if(!h)throw new Error("Element not found, id: "+p+`
43
+ NarraLeaf cannot find the element with the id from the saved game`);h.fromData(g),h.markDirty()}),this.currentSavedGame=e,t.loadData(r,d),this.stackModel.deserialize(c,u),l.forEach(p=>{let g=Ye.createStackModel(this,p,u);this.asyncStackModels.add(g),t.timelines.attachTimeline(this.executeAsyncStackModel(g))}),n.deserializeServices(a),t.gameHistory.load(e.game.history??[],u),this.game.hooks.trigger("afterRestore",[]),t.events.once(E.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}getFuture(){return this.assertGameState(),this.gameState.gameHistory.getFuture()}canUndo(){return this.assertGameState(),this.gameState.gameHistory.canUndo()}canRedo(){return this.assertGameState(),this.gameState.gameHistory.canRedo()}undo(){this.assertGameState();let e=this.gameState.gameHistory;return e.canUndo()?this.restoreToIndex(e.getCursor()-1,"LiveGame.undo"):(this.gameState.logger.warn("LiveGame.undo","No line to step back to"),!1)}redo(){this.assertGameState();let e=this.gameState.gameHistory;return e.canRedo()?this.restoreToIndex(e.getCursor()+1,"LiveGame.redo"):(this.gameState.logger.warn("LiveGame.redo","No line to step forward to"),!1)}restoreToHistory(e){this.assertGameState();let t=this.gameState.gameHistory.indexOfToken(e);return t<0?(this.gameState.logger.warn("LiveGame.restoreToHistory","No history entry for token",e),!1):this.restoreToIndex(t,"LiveGame.restoreToHistory")}restoreToIndex(e,t){this.assertGameState();let n=this.gameState.gameHistory,i=n.getAt(e);if(!i)return this.gameState.logger.warn(t,"No history entry at",e),!1;if(e<n.getCursor()&&this.gameState.actionHistory.has(i.token)){let a=n.getCursor();if(n.setCursor(e),this.undoInPlace(i,t))return this.auditRestoredLine(i,t),!0;n.setCursor(a)}if(!i.snapshot)return this.gameState.logger.warn(t,"History entry has no restore snapshot",i.token),!1;let r=i.token,s={name:this.currentSavedGame?.name??"",meta:this.currentSavedGame?.meta??this.getNewSavedGame().meta,game:{...i.snapshot,history:n.serializeAll()}};return this.deserialize(s),this.gameState.gameHistory.setCursor(this.gameState.gameHistory.indexOfToken(r)),i.action.type===zt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),!0}undoInPlace(e,t){this.assertGameState();let n=this.gameState.actionHistory;if(!n.has(e.token))return!1;let i=this.gameLock.register().lock();this.stackModel.abortStackTop();let r=n.undoUntil(e.token);if(!r)return this.gameLock.off(i.unlock()),!1;let[s]=this.constructMaps(),{rootStackSnapshot:a,stackModel:c}=r;return r.action.type===zt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(a,s),c===this.stackModel&&this.stackModel.push(Ye.fromAction(r.action)),this.gameLock.off(i.unlock()),this.gameState.logger.debug(t,"Stepped back in place to",e.token),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0),!0}auditRestoredLine(e,t){if(!this.game.config.app.debug||!e.snapshot)return;let n=JSON.stringify([...e.snapshot.elementStates].sort((r,s)=>r.id.localeCompare(s.id))),i=JSON.stringify([...this.serializeGameState().elementStates].sort((r,s)=>r.id.localeCompare(s.id)));n!==i&&this.gameState?.logger.warn(t,`Stepping back in place did not reproduce the state this line's snapshot describes, so an action's undo does not fully reverse it. Restoring the snapshot would have been correct; this path was not.
44
+ expected: ${n}
45
+ actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=T.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new Ae({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(E.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Re.FastForwardStepTimeout,c=i!==null?{reachedTarget:!1}:{},l=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...c};if(this.stackModel.isEmpty())return{reason:"end",...c};let d=this.stackModel.getWaitingAwaitable();if(d){if(!await Re.settleSuspendedStep(t,d,a))return{reason:"stalled",...c}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...c}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(l)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,c=d=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(d))};if(a=t.onSettled(()=>c(!0)),r){a?.cancel?.();return}let l=Date.now()+n,u=()=>{if(!r&&(e.events.emit(E.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=l){c(!1);return}s=setTimeout(u,Re.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Re.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Re.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Re.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Ye.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee)},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Ye(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new Ye(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Re.EventTypes["event:action.current"])&&this.events.emit(Re.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type}),t.callee?.markDirty();let i=t.executeAction(e,n);return T.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Fe("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Ye(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Fe("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[Dt].some(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(pe,J.jumpTo)){let[c]=i.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw i.action._sceneNotFoundError(i.action.getSceneName(c));if(a.has(l)){i=null;continue}a.add(l),i=l.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(oe,ne.do)){let[c]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=c[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new Fe("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Fe("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:ws(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new P("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new P("Player Element Not Mounted")}};Re.DefaultNamespaces={game:{}},Re.GameSpacesKey={game:"game"},Re.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Re.ElementAuditInterval=50,Re.FastForwardStepTimeout=1e4,Re.FastForwardSkipInterval=16;var It=Re;var _n=class _n{constructor(e){this.events=new Q;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(_n.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(_n.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};_n.EventTypes={"event:game.preference.change":"event:game.preference.change"};var ei=_n;import"client-only";import Va,{useEffect as Lu,useRef as Nr}from"react";import"client-only";import Ys,{useContext as Js,useState as $c}from"react";var or=Ys.createContext(null);function Zs({children:o,game:e}){"use client";let t=new re({}),[n]=$c(e||t);return Ys.createElement(or,{value:n},o)}function I(){let o=Js(or);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function _s(){return Js(or)}import jc,{createContext as qc,useContext as ea}from"react";var ta="/",eo=class eo{constructor(e,t=eo.rootPath){this.events=new Q;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,c]=s.split("=");a&&(i[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let c=a.slice(1);n[c]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new P(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new P(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),rt(()=>{t()}))})}else rt(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};eo.rootPath=ta;var an=eo,rr=qc(null);function na({children:o}){let e=I();return jc.createElement(rr,{value:{router:e.router}},o)}function Gt(){if(!ea(rr))throw new Error("useRouter must be used within a RouterProvider");return ea(rr).router}import oa from"react";import el from"clsx";import Qc,{createContext as Xc,useContext as Yc,useLayoutEffect as Jc,useReducer as Zc,useState as _c}from"react";var jt=class jt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new Q().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(jt.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(jt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(jt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(jt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(jt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(jt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};jt.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var sr=jt,ar=Xc(null);function ia({children:o}){"use client";let[e]=_c(()=>new sr);return Qc.createElement(ar,{value:{ratio:e}},o)}function be(){let o=Yc(ar),[,e]=Zc(n=>n+1,0);if(!ar||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return Jc(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function Vt({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=be(),s=r.getStyle();return oa.createElement("div",{className:el("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},oa.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import tl,{useEffect as nl}from"react";function cn(o){let e=I(),[t,n]=tl.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return nl(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import cr from"react";import to from"react";import ra from"clsx";function no({children:o,className:e,style:t,...n}){let{ratio:i}=be(),r=I();return to.createElement(Vt,{className:ra("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},to.createElement("div",{className:"absolute inset-0 w-full h-full"},to.createElement("div",{className:"inset-0 w-full h-full"},to.createElement("div",{className:ra("pointer-events-auto-rest",e),style:t},o))))}function il({children:o,className:e,style:t}){return cr.createElement(cr.Fragment,null,cr.createElement(no,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import sa from"clsx";import aa from"react";function io({className:o,children:e,...t}){let{ratio:n}=be();return aa.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:sa("w-full h-full")},aa.createElement("div",{className:sa("z-20",o),...t},e))}import yt,{useState as ca}from"react";import{motion as ol}from"motion/react";function oo({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=I(),[l,u]=ca(!1);if(!c.config.app.inspector)return yt.createElement(r,{...a,ref:s},o);let d={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return yt.createElement(r,{...d,ref:s},n&&l&&yt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function rl({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=I(),[a,c]=ca(!1);if(!s.config.app.inspector)return yt.createElement(i,{...r});let l={...r,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return yt.createElement("div",null,yt.createElement(i,{...l}),t&&a&&yt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function sl(o){return yt.createElement(oo,{...o,as:"div"})}function al(o){return yt.createElement(oo,{...o,as:"span"})}function cl(o){return yt.createElement(rl,{...o,as:"img"})}function ll(o){return yt.createElement(oo,{...o,as:"button"})}function ul(o){return yt.createElement(oo,{...o,as:ol.div,ref:o.ref,layout:o.layout})}var pl={Div:sl,Span:al,Button:ll,Img:cl,mDiv:ul},Ht=pl;import uo from"clsx";import ze,{useEffect as Nn,useRef as fa,useState as mr}from"react";import{useEffect as dl,useState as ml}from"react";function se(o){let[e,t]=ml(0);dl(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import la from"react";var gn=la.createContext(null);function xt(){let o=la.useContext(gn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import ro,{useCallback as fl,useLayoutEffect as ti,useMemo as ua,useRef as pa}from"react";import{useIsPresent as hl}from"motion/react";var Ct=class Ct{constructor(e){this.events=new Q;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new xi,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e||this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(Ct.Events.complete):this.safeEmit(Ct.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Ct.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Ct.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",this.config.gameState.completeAdvDialogTyping(this.config.action.id),e.getPreference(re.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Ct.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.releaseVoiceWait(),this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Ct.Events.onFlush),this}onFlush(e){return this.events.on(Ct.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;if(!this._active||!e.getPreference(re.Preferences.autoForward)||this.state!=="ended")return;this.releaseVoiceWait();let t=this.getPlayingVoiceToken();if(!t){this.scheduleAutoForwardDelay();return}let n=()=>{this.releaseVoiceWait(),this.scheduleAutoForwardDelay()};t.once("ended",n),t.once("stop",n),this.voiceWaitDisposer=()=>{t.off("ended",n),t.off("stop",n)}}scheduleAutoForwardDelay(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(re.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Ct.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(re.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=nt.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};Ct.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Me=Ct;function ni({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=hl(),s=i&&r,a=pa(!1),c=pa(o),l=c.current!==o,u=ua(()=>o.sentence?.evaluate(Ce.getCtx({gameState:n})),[o.sentence,n]),d=ua(()=>new Me({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:l}),[o,n,t,u]),p=n.game.config.dialog,g=fl(h=>{!s||a.current||(a.current=!0,e?.(h))},[s,e]);return ti(()=>{a.current=!1},[d]),ti(()=>{c.current=o},[o]),ti(()=>(d.setActive(s),()=>{d.setActive(!1)}),[d,s]),ti(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",d),d.events.on(Me.Events.complete,h=>{n.logger.log("NarraLeaf-React: Say","Complete",d.isIdle()),s&&(d.isIdle()||h?g(!1):d.setIdle(!0))}).cancel),[d,g,n,s]),ti(()=>{let h=A=>{s&&(A?(d.setIdle(!0),d.forceSkip()):d.isIdle()?g(!0):d.forceSkip())},m=n.events.on(E.EventTypes["event:state.player.skip"],h),y=n.events.on(E.EventTypes["event:state.player.stageClick"],()=>h(!1));return()=>{m.cancel(),y.cancel()}},[d,g,n,s]),ro.createElement(ro.Fragment,null,ro.createElement(gn,{value:d},ro.createElement(p,null)))}import{useEffect as so,useState as vl}from"react";import{useEffect as gl,useState as yl}from"react";function yn(o){let e=I(),[t,n]=yl(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return gl(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Mn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Mn||{});function ao({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=I(),[s]=yn("nextAction"),[a]=vl(()=>{let c=o.firedTextEvents??(o.firedTextEvents=new Set);return new Me({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:c})});return so(()=>{if(!n)return;let c=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},l=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(E.EventTypes["event:state.player.stageClick"],c),d=e.events.on(E.EventTypes["event:state.player.skip"],l);return()=>{u.cancel(),d.cancel()}},[a,o.id,e,n]),so(()=>{if(!n)return;let c=u=>{if(u.repeat||!r.keyMap.match("nextAction",u.key))return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()};if(r.config.useWindowListener){let u=r.getLiveGame().onWindowEvent("keydown",c);return()=>{u.cancel()}}let l=r.getLiveGame().onPlayerEvent("keydown",c);return()=>{l.cancel()}},[a,o.id,r,e,n,s]),so(()=>{let c=a.events.on(Me.Events.complete,l=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!l&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),so(()=>{let c=a.events.on(Me.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{c.cancel()}},[a,n]),a}function Sl(o,e){let{expression:t,sound:n}=o.config;if(t){let{image:i,appearance:r}=t;i._setAppearanceSync(r),e.stage.update();let s=e.getExposedState(i);s&&(L.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function co(o,e,t){e.has(o)||(e.add(o),Sl(o,t))}function da(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),co(r,e,t)}return n}import lr from"react";var Tl=2;function lo(o){return o==="vertical-rl"||o==="vertical-lr"}function bl(o){return o===!1?0:typeof o=="number"?Number.isFinite(o)?Math.max(0,Math.round(o)):0:Tl}function pr(o,e){return lo(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var ur=/[0-9A-Za-z]+(?:[.:\-/][0-9A-Za-z]+)*/g;function Al(o,e){if(e<=0)return[{text:o,combineUpright:!1}];let t=[],n=0;ur.lastIndex=0;for(let i=ur.exec(o);i;i=ur.exec(o))i[0].length>e||(i.index>n&&t.push({text:o.slice(n,i.index),combineUpright:!1}),t.push({text:i[0],combineUpright:!0}),n=i.index+i[0].length);return(n<o.length||t.length===0)&&t.push({text:o.slice(n),combineUpright:!1}),t}function dr(o){return o?{wordBreak:"normal",overflowWrap:"break-word"}:{wordBreak:"break-all"}}function ii(o,e,t){if(!e)return o;let n=bl(t);if(n<=0)return o;let i=Al(o,n);return i.some(r=>r.combineUpright)?i.map((r,s)=>r.combineUpright?lr.createElement("span",{key:s,style:{textCombineUpright:"all"}},r.text):lr.createElement(lr.Fragment,{key:s},r.text)):o}function*hr(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(Be.isPause(n.text)){yield Be.from(n.text);continue}if(at.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
44
46
  `?yield`
45
- `:yield{text:r,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function or(o){let e=rr(o),t=[];for(let n of e)Fe.isPause(n)||ot.isTextEvent(n)||t.push(n);return t}function ra(o,e){o(t=>{let n=t[t.length-1];return n&&n!==`
47
+ `:yield{text:r,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function fr(o){let e=hr(o),t=[];for(let n of e)Be.isPause(n)||at.isTextEvent(n)||t.push(n);return t}function ha(o,e){o(t=>{let n=t[t.length-1];return n&&n!==`
46
48
  `&&e!==`
47
- `&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function ul(o,e,t){return t||(o!==void 0?Se.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new J(n.text,n.config)):[])}function pl(o,e,t){let n=Math.max(0,e??t);return typeof o=="object"?{enabled:o.enabled??!0,delay:Math.max(0,o.delay??n)}:{enabled:o??!0,delay:n}}function ia(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function ro(o){return o===void 0?void 0:vn(o)}function sr({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,...c}){let l=M(),u=l.getLiveGame().getGameState(),d=oa(null),[p,g]=ir(()=>n&&!n.config.useTypeEffect?or(n.config.evaluatedWords):[]),[y,f]=re();if(!n)throw new Error("Dialog state is required");Ln(()=>{if(!(!n.config.action.sentence||d.current))return u.logger.info("Initializing the sentence",n,d.current),u.schedule(({onCleanup:S})=>{if(!n.config.useTypeEffect){na(n.config.evaluatedWords,n.config.firedTextEvents??new Set,u),n.dispatchComplete();return}g([]),d.current=h(),y(),d.current.onComplete(()=>{n.dispatchComplete()}),S(()=>{d.current?.timeline?.abort()})},0)},[]),Ln(()=>n.events.depends([n.events.on(Le.Events.requestComplete,()=>{d.current?.interact()}),n.events.on(Le.Events.forceSkip,()=>{n.isEnded()||d.current?.forceSkip()})]).cancel,[n,f]),Ln(()=>l.preference.events.depends([l.preference.onPreferenceChange(ie.Preferences.gameSpeed,()=>{d.current?.update()}),l.preference.onPreferenceChange(ie.Preferences.autoForward,()=>{d.current?.update()}),l.preference.onPreferenceChange(ie.Preferences.cps,()=>{d.current?.update()})]).cancel,[]);function h(){let S=new T,C=new Ie(S).setGuard(u.guard),E=new Set,O=n.config.firedTextEvents??new Set,_=new Set,se=new Set,ze=rr(n.config.evaluatedWords),dt=null,et=[],be=[],K=()=>{et.forEach(P=>P()),et.length=0},le=()=>{if(be.length!==0)return{done:!1,value:be.shift()};let{done:P,value:V}=ze.next();return{done:P,value:V}},oe=P=>{let V=fe=>{P(fe),_.delete(V)};return _.add(V),{cancel:()=>{_.delete(V)}}},ue=P=>{ra(g,P)},F=(P=!1)=>{let V=!1;for(;!V;){let{done:fe,value:D}=le();if(fe){V=!0;break}if(Fe.isPause(D)){if(P)continue;V=!0,be.push(D);break}else ot.isTextEvent(D)?io(D,O,u):D===`
48
- `?g(he=>[...he,D]):typeof D=="object"&&"text"in D&&!E.has(D)&&(E.add(D),ue(D))}dt&&!dt.isSettled()?dt.abort():(se.forEach(fe=>fe()),S.resolve())};return u.schedule(async P=>{let V=!1,fe=!1;for(;!V;){let{done:D,value:he}=le();if(D){V=fe=!0;break}if(ot.isTextEvent(he)){io(he,O,u);continue}let Ot=new T;if(u.timelines.attachTimeline(Ot),Ot.registerSkipController(new H(()=>{K(),V=!0,P.retry()})),Ot.onSettled(()=>{K()}),dt=Ot,Fe.isPause(he)){let mi=Fe.from(he),fi=l.preference.getPreference(ie.Preferences.gameSpeed);if(mi.config.duration){let hi=mi.config.duration/fi;await Ci(hi)}else{let hi=l.preference.getPreference(ie.Preferences.autoForward),gi=T.race([T.create(gc=>{let yc=oe(vc=>{vc(),gc.resolve()});et.push(()=>yc.cancel())}),...hi?[T.delay(l.config.autoForwardDefaultPause/fi)]:[]]);u.timelines.attachTimeline(gi),await T.wait(gi)}}else{if(he!==`
49
- `&&E.has(he))continue;E.add(he),ue(he);let{gameSpeed:mi,cps:fi}=l.preference.getPreferences(),gi=1e3/((typeof he=="object"&&"cps"in he&&he.cps!==void 0?he.cps:fi)*mi);await Ci(gi)}}fe&&(se.forEach(D=>D()),S.resolve())},0),{getToken:()=>S,interact:()=>{let P=!1;_.forEach(V=>V(()=>P=!0)),!P&&F()},update:()=>{dt&&dt.abort()},forceSkip:()=>{F(!0)},timeline:C,onComplete:P=>(se.add(P),{cancel:()=>{se.delete(P)}})}}let A=n.config.action.sentence;if(!A)return null;let m=s??"bold",v={fontWeight:A.config.bold?m:r,fontSize:A.config.fontSize??i,color:ro(A.config.color??o),fontFamily:A.config.fontFamily??a,fontStyle:A.config.italic?"italic":void 0},x=S=>({fontWeight:S.config.bold||A.config.bold?m:r,fontSize:S.config.fontSize??A.config.fontSize??i,color:ro(S.config.color??A.config.color??o),fontFamily:S.config.fontFamily??A.config.fontFamily??a,fontStyle:S.config.italic??A.config.italic?"italic":void 0}),b=(S,C)=>S===`
50
- `?Ke.createElement("br",{key:C}):Ke.createElement(Mt.Span,{tag:`say.word.${C}`,key:C,style:{...x(S),...wi(l.config.app.debug,{outline:"1px dashed red"})},className:oo("inline-block break-all",S.config.className)},S.config.ruby?Ke.createElement("ruby",{className:"align-bottom inline-block"},Ke.createElement("rt",{className:"block text-center"},S.config.ruby),S.text):S.text);return Ke.createElement("div",{...c,className:oo("whitespace-pre-wrap",e),style:{...v,...t}},p.map(b))}function dl({text:o,sentence:e,words:t,useTypeEffect:n=!0,loop:i=!0,restartDelay:r,cps:s,gameSpeed:a,pauseDuration:c,defaultColor:l,className:u,style:d,fontSize:p,fontWeight:g,fontWeightBold:y,fontFamily:f,onCompleted:h,...A}){let m=Ws(),[,v]=ir(0),x=m?.config??ie.DefaultConfig,b=m?.preference.getPreferences()??ie.DefaultPreference,S=s??b.cps,C=a??b.gameSpeed,E=c??x.autoForwardDefaultPause,O=r??x.autoForwardDefaultPause,_=Ke.useMemo(()=>ul(o,e,t),[o,e,t]),se=Ke.useMemo(()=>pl(i,r,O),[i,r,O]),ze=oa(h),[dt,et]=ir(()=>n?[]:or(_));Ln(()=>{if(m)return m.preference.onPreferenceChange(()=>{v(F=>F+1)}).cancel},[m]),Ln(()=>{ze.current=h},[h]),Ln(()=>{let F=!1,me=[],ve=Math.max(.01,C),pe=V=>new Promise(fe=>{let D=setTimeout(fe,Math.max(0,V));me.push(D)}),Qe=()=>{F||ze.current?.()};return n?_.length===0?(et([]),()=>{F=!0}):((async()=>{do{let V=rr(_);for(et([]);!F;){let{done:fe,value:D}=V.next();if(fe)break;if(Fe.isPause(D)){let he=Fe.from(D);await pe((he.config.duration??E)/ve)}else{if(ot.isTextEvent(D))continue;ra(et,D),D===`
51
- `?await pe(ia(S,C)):await pe(ia(D.cps??S,C))}}if(F)return;Qe(),se.enabled&&await pe(se.delay)}while(!F&&se.enabled)})(),()=>{F=!0,me.forEach(V=>clearTimeout(V))}):(et(or(_)),Qe(),()=>{F=!0})},[_,n,se,S,C,E]);let be=e?.config,K=y??"bold",le={fontWeight:be?.bold?K:g,fontSize:be?.fontSize??p,color:ro(be?.color??l),fontFamily:be?.fontFamily??f,fontStyle:be?.italic?"italic":void 0},oe=F=>({fontWeight:F.config.bold||be?.bold?K:g,fontSize:F.config.fontSize??be?.fontSize??p,color:ro(F.config.color??be?.color??l),fontFamily:F.config.fontFamily??be?.fontFamily??f,fontStyle:F.config.italic??be?.italic?"italic":void 0}),ue=(F,me)=>F===`
52
- `?Ke.createElement("br",{key:me}):Ke.createElement("span",{key:me,style:oe(F),className:oo("inline-block break-all",F.config.className)},F.config.ruby?Ke.createElement("ruby",{className:"align-bottom inline-block"},Ke.createElement("rt",{className:"block text-center"},F.config.ruby),F.text):F.text);return Ke.createElement("div",{...A,className:oo("whitespace-pre-wrap",u),style:{...le,...d}},dt.map(ue))}function sa(o){return Ke.createElement(sr,{...o,key:o.dialog?.config.action.id})}function ml({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=no({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Ke.createElement(sr,{...r,dialog:s,key:s.config.action.id})}function fl(o){let e=St();return Ke.createElement(sr,{...o,dialog:e,key:e.config.action.id})}function rn(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Ke.createElement(ml,{...o}):Ke.createElement(fl,{...o})}var hl=rn;import ao,{useEffect as gl,useLayoutEffect as yl,useMemo as ca,useRef as vl,useState as Sl}from"react";import so from"react";var ar=so.createContext(null);function cr(){let o=so.useContext(ar);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var lr=so.createContext(null);function aa(){let o=so.useContext(lr);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function co({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let c=vl(null),{register:l,unregister:u,getIndex:d}=aa(),[p,g]=Sl(-1),{choose:y,evaluated:f,gameState:h}=cr(),A=p===-1?null:f[p],m=ca(()=>Ce.getCtx({gameState:h}),[h]),{hidden:v,disabled:x}=ca(()=>{if(!A)return{hidden:!1,disabled:!1};let C=A.config.hidden?.evaluate(m)?.value??!1,E=!C&&(A.config.disabled?.evaluate(m)?.value??!1);return{hidden:C,disabled:E}},[A,m]);yl(()=>{if(!c.current)return;let C=c;l(C);let E=d(C);return g(E),c.current.dataset.index=E.toString(),()=>u(C)},[l,u,d]),gl(()=>{if(!t)return;let C=E=>{E.key.toLowerCase()===t.toLowerCase()&&!E.ctrlKey&&!E.metaKey&&(E.preventDefault(),E.stopPropagation(),b())};return window.addEventListener("keydown",C,!0),()=>{window.removeEventListener("keydown",C,!0)}},[t]);function b(){if(p===-1||!f[p]||v||x)return;let C=f[p];y({...C,evaluated:J.getText(C.words||[])})}let S=A&&!v;return ao.createElement(ao.Fragment,null,ao.createElement("button",{className:o,style:{...e,display:S?e?.display??void 0:"none"},onClick:b,ref:c,disabled:x},S&&ao.createElement(sa,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Le({useTypeEffect:!1,action:{sentence:A.prompt,words:A.words,character:null},gameState:h,evaluatedWords:A.words})})))}import lo from"react";import{AnimatePresence as Tl}from"motion/react";function uo({children:o,...e}){let t=Tl;return lo.createElement(lo.Fragment,null,lo.createElement("div",{...e},lo.createElement(t,null,o)))}import la from"react";function Wt({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=la.useContext(dn),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return la.createElement("div",{...s,style:{color:l?vn(l):void 0,...r}},u)}import xl from"clsx";import Cl from"react";import ur,{createContext as bl,useContext as Al,useState as ua}from"react";var fn=class fn{constructor(){this.preloaded=[];this.events=new q}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(fn.EventTypes["event:preloaded.add"],e),this.events.emit(fn.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(i=>this.getSrc(i));return this.preloaded=this.preloaded.filter(i=>!n.includes(this.getSrc(i))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(fn.EventTypes["event:preloaded.remove"],e),this.events.emit(fn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Ee.getSrc(e)}};fn.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.complete":"event:preloaded.complete","event:preloaded.unmount":"event:preloaded.unmount"};var Be=fn;var po=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.decoded=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear(),this.decoded.clear()})}static getImage(e,t,n){return ps(e,{...n,signal:t})}static async decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return null;let t=new window.Image;if(t.src=e,typeof t.decode!="function")return null;try{await t.decode()}catch{return null}return t}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this.decoded.delete(e),this}get(e){return this.src.get(e)}isDecoded(e){return this.decoded.has(e)}clear(){return this.src.clear(),this.decoded.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t,n){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let i=t,r={};this.game.hooks.rawTrigger("preloadImage",()=>[i,(p,g)=>{i=p,r={...r,...g}}]);let s=new AbortController,a=s.signal,c=[],u={promise:o.getImage(i,a,r).then(async p=>{if(this.preloadTasks.delete(t),p){this.add(t,p);let g=await o.decodeImage(p);g&&n?.retainDecoded&&this.src.get(t)===p&&this.decoded.set(t,g)}}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),c.forEach(g=>g(p))}),controller:s};this.preloadTasks.set(t,u);let d={abort:()=>{s.abort(),this.preloadTasks.delete(t)},onFinished:p=>(u.promise.then(p),d),onErrored:p=>(c.push(p),d)};return d}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){let t=new Set(e);for(let n of this.src.keys())t.has(n)||(this.src.delete(n),this.decoded.delete(n));for(let n of this.decoded.keys())t.has(n)||this.decoded.delete(n);return this}};var pr=bl(null);function pa({children:o}){let e=M(),[t]=ua(()=>new Be),[n]=ua(()=>new po(e));return ur.createElement(ur.Fragment,null,ur.createElement(pr,{value:{preloaded:t,cacheManager:n}},o))}function Nt(){if(!pr)throw new Error("usePreloaded must be used within a PreloadedProvider");return Al(pr)}function da(){let o=St(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return Pl(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?R.getSrcURL(s):null,c=s&&R.isTagSrc(s)?[...s.state.currentSrc]:null,l=Rs({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=kl(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function wl({className:o,style:e,alt:t,...n}){let i=da(),{cacheManager:r}=Nt();if(!i.visible||!i.src)return null;let s=r.get(i.src)||i.src;return Cl.createElement("img",{...n,"data-element-type":"dialog-avatar",className:xl("dialog-avatar",o),src:s,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function kl(o){return o?k.srcToURL(o):null}function Pl(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var dr=wl;import{useEffect as El}from"react";function Dl(){let o=St(),[e]=re(o.deps),t=J.getText(o.config.evaluatedWords);return El(()=>o.events.on(Le.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as mo,useEffect as mr,useMemo as Ll,useRef as Il,useState as ma}from"react";function Rl(){let o=St(),[e]=re(o.deps),[t,n]=ma(!0),[i,r]=ma(!0),s=Il(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;mr(()=>o.events.on(Le.Events.onFlush,()=>{e()}).cancel,[o]);let u=Ll(()=>{if(!c)return null;try{return Ze.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);mr(()=>{s.current=null,r(!0)},[c]),mr(()=>{let f=!1,h=null,A=null,m=null;if(!u){n(!0);return}n(!1);let v=()=>{f||n(!0)};h=a.audioManager.getToken(u),h&&(h.isPlaying()||n(!0),A=()=>v(),m=()=>v(),h.once("ended",A),h.once("stop",m));let x=a.events.on(I.EventTypes["event:state.player.lineEnd"],()=>{v()});return()=>{f=!0,x.cancel(),h&&A&&h.off("ended",A),h&&m&&h.off("stop",m)}},[a,u]);let d=mo(async f=>{let h=f??u;if(!h)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let A=h instanceof URL?Ae.voice(h.toString()):typeof h=="string"?Ae.voice(h):h,m=await a.getLiveGame().playSound(A);s.current=m;let v=()=>{r(!0)};return m.once("ended",v),m.once("stop",v),m},[a,u]),p=mo(()=>u,[u]),g=mo(()=>l,[l]),y=mo(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:g,getVoiceSrc:y}}import fr,{createContext as zl,useContext as $l,useEffect as ga,useRef as jl}from"react";import{useState as Ml}from"react";function fo(o){let[e]=Ml(o);return e}import{AnimatePresence as Nl}from"motion/react";var ho=Nl;import ii,{createContext as Ul,useContext as Ol,useEffect as Kl,useRef as Bl}from"react";import{useEffect as ei,useLayoutEffect as Gl}from"react";function Vl(){let o=It(),[e]=re();return ei(()=>o.onChange(e).cancel,[]),o.getPathname()}function Fl(){let{router:o,path:e}=ni(),[t]=re();return ei(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function Hl(){let o=It(),[e]=re();return ei(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function go(o,e){let t=It();Gl(()=>t.onUpdate(()=>o(t)).cancel,e),ei(()=>{o(t)},[])}function ti(){let o=It(),[e]=re();return ei(()=>o.onChange(e).cancel,[]),e}var fa=Ul(null);function oi({children:o,path:e,consumedBy:t}){let i={router:It(),path:e,consumedBy:t};return ii.createElement(fa,{value:i},o)}function ni(){let o=Ol(fa);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new L(`Invalid useLayout call: Trying to access layout without a parent.
53
- This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Wl({children:o,name:e,propagate:t}){let n=M(),[i]=re(),{path:r,router:s,consumedBy:a}=ni(),c=s.joinPath(r,e),l=fo(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),d=Bl(!1),p=y=>{d.current=y,i()},g=s.matchPath(u,c);if(ti(),go(y=>{let f=y.matchPath(y.getCurrentPath(),c);if(d.current&&!f){if(!o){p(!1);return}y.registerUnmountingPath(l)}f&&y.isPathsUnmounting()&&y.unregisterUnmountingPath(l),f&&!d.current&&!y.isTransitioning()&&p(!0)},[g,o]),Kl(()=>{if(!g)return;let y=s.mount(c);return()=>{y.cancel()}},[c,s,g]),a)throw new L("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return ii.createElement(oi,{path:c},ii.createElement(ho,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),p(!1)}},g&&d.current&&o))}function ha({children:o}){return ti(),ii.createElement(oi,{path:nn.rootPath},ii.createElement(Yi,{"data-layout-path":nn.rootPath,key:nn.rootPath},o))}var hr=zl(null);function ql(){return $l(hr)}function Ql({children:o,name:e}){let[t]=re(),{path:n,router:i,consumedBy:r}=ni(),s=ql(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=fo(()=>i.createToken(l+"@page")),d=i.getCurrentPath(),p=!a,g=jl(!1),y=m=>{g.current=m,t()},f=p&&i.exactMatch(d,n)||i.exactMatch(d,l);if(r&&r!==c)throw new L("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");ti(),go(m=>{let v=p&&m.exactMatch(m.getCurrentPath(),n)||m.exactMatch(m.getCurrentPath(),l);if(g.current&&!v){if(!o){y(!1);return}m.registerUnmountingPath(u)}v&&m.isPathsUnmounting()&&m.unregisterUnmountingPath(u),v&&!g.current&&!m.isTransitioning()&&y(!0)},[f,o]),ga(()=>{if(!f)return;let m=p?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{m.cancel()}},[l,f]),ga(()=>()=>{i.unregisterUnmountingPath(u),y(!1)},[]);let h=fr.createElement(oi,{path:n,consumedBy:c},fr.createElement(ho,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),y(!1)}},f&&g.current&&o));return(m=>s?fr.createElement(hr,{value:{name:null}},m):m)(h)}import gr,{useCallback as Xl,useEffect as yr,useImperativeHandle as Jl,useMemo as ya,useRef as vr,useState as Yl}from"react";var Zl=50,_l={position:"relative",width:"100%",height:"100%",overflow:"hidden"},va={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function eu(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function Sa(o,e){return e==null?o:Math.max(o,e)}function tu(o,e,t){return o<=0||e<=0||t<=0?{width:o,height:e}:o/e>t?{width:e*t,height:e}:{width:o,height:o/t}}var Ta=gr.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:d},p){let g=vr(null),[y,f]=Yl({...va,width:"0px",height:"0px"}),h=vr(u),A=vr(null);yr(()=>{h.current=u},[u]);let m=Xl(()=>{let b=g.current;if(!b)return;let S=b.clientWidth,C=b.clientHeight;if(S<=0||C<=0||e<=0)return;let E=tu(S,C,e),O=Sa(E.width,n),_=Sa(E.height,i),se=A.current;(!se||se.width!==O||se.height!==_)&&(A.current={width:O,height:_},f({...va,width:`${O}px`,height:`${_}px`}));let ze=t>0?O/t:1;h.current?.({width:O,height:_,scale:ze,containerWidth:S,containerHeight:C})},[e,t,n,i]),v=ya(()=>ls(m,typeof r=="number"?r:Zl),[m,r]);yr(()=>{m()},[m]),yr(()=>{let b=new ResizeObserver(()=>{v()});g.current&&b.observe(g.current);let S=()=>{v()};return window.addEventListener("resize",S),()=>{b.disconnect(),window.removeEventListener("resize",S)}},[v]),Jl(p,()=>({requestUpdate:m}),[m]);let x=ya(()=>eu(l),[l]);return gr.createElement("div",{id:c,ref:g,style:_l,...x},gr.createElement("div",{className:s,style:{...y,...a}},d))}),ba=Ta;function nu(){return M().getLiveGame()}import br from"react";import iu,{createContext as ou,useContext as ru,useEffect as su,useState as Aa}from"react";var au={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},xa=ou({state:au,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function Gt(){return ru(xa)}function Sr(){let{dialogs:o}=Gt();return o}function cu(){let{isActive:o}=Gt();return o}function lu(){let{isVisible:o}=Gt();return o}function Tr({children:o}){let t=M().getLiveGame().getGameState(),[n,i]=Aa(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Aa(null);su(()=>{let c=y=>({...y,dialogs:[...y.dialogs]}),l=t.events.on(I.EventTypes["event:state.nvl.enter"],(y,f)=>{i(c(t.getNvlState())),s(f?.showTransition||null)}),u=t.events.on(I.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),d=t.events.on(I.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),p=t.events.on(I.EventTypes["event:state.nvl.visibilityChange"],(y,f)=>{i(c(t.getNvlState())),s(f||null)}),g=t.events.on(I.EventTypes["event:state.nvl.change"],y=>{i(c(y))});return()=>{l.cancel(),u.cancel(),d.cancel(),p.cancel(),g.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return iu.createElement(xa.Provider,{value:a},o)}import{AnimatePresence as uu,motion as pu}from"motion/react";import du from"clsx";function Ar({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=Gt(),{ratio:r}=Te(),s=M(),a=i?.duration?i.duration/1e3:.3;return br.createElement(uu,null,n&&br.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},br.createElement(pu.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:du("w-full h-full overflow-auto",e),style:{transform:s.config.useAspectScale?`scale(${r.state.scale})`:void 0,transformOrigin:"top left",width:s.config.useAspectScale?s.config.width:"100%",height:s.config.useAspectScale?s.config.height:"100%",...t}},o)))}import hn from"react";function xr({renderDialogItem:o,dialogs:e}){return hn.createElement(Ar,{className:"bg-black/80 text-white p-16 inset-8"},hn.createElement("div",{"data-element-type":"nvl-dialog-list",className:"flex flex-col space-y-4 p-4"},(e??[]).map((n,i)=>{let r=n.entry.character?hn.createElement(Wt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=hn.createElement(rn,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return hn.createElement("div",{key:`${n.entry.id}:${n.isActive?"active":"idle"}`,"data-element-type":"nvl-dialog-item","data-dialog-index":i,className:"nvl-dialog-item"},o?o({entry:n.entry,index:i,isActive:n.isActive,nametag:r,texts:s}):hn.createElement(hn.Fragment,null,r,s))})))}import pt,{useMemo as mu}from"react";import Ca from"clsx";function fu({children:o,className:e,style:t,renderDialogItem:n}){let i=Sr(),{state:r}=Gt();return pt.createElement("div",{"data-element-type":"nvl-dialog-list",className:Ca("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>pt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},pt.createElement(hu,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?pt.createElement(Wt,{className:"nvl-character-name font-bold mr-2"}):null,texts:pt.createElement(rn,{className:"nvl-dialog-text"})}):o?pt.Children.map(o,c=>pt.isValidElement(c)?pt.cloneElement(c,{entry:s,index:a}):c):pt.createElement(wa,{entry:s,index:a})))))}function wa({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??pt.createElement(rn,{className:"nvl-dialog-text"});return pt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Ca("nvl-dialog-item",t),style:n},r&&pt.createElement(Wt,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function hu({entry:o,children:e}){let n=M().getLiveGame().getGameState(),i=mu(()=>o.sentence.evaluate(Ce.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=no({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return pt.createElement(dn,{value:c},e)}function Pa({state:o}){let e=M(),t=It(),n=Cr(null),i=Cr(null),r=Cr(!1),[s]=on(ie.Preferences.skipDelay),[a]=on(ie.Preferences.skipInterval),[c]=mn("skipAction");return yu(()=>{if(!e.getLiveGame().gameState.playerCurrent){o.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){o.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let u=()=>{i.current&&(clearTimeout(i.current),i.current=null),n.current&&(clearInterval(n.current),n.current=null),r.current=!1},d=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(ie.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let y=()=>{n.current=setInterval(()=>{o.events.emit(I.EventTypes["event:state.player.skip"],!1)},a)};u(),o.events.emit(I.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?y():i.current=setTimeout(y,s)}},p=g=>{e.keyMap.match("skipAction",g.key)&&u()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",d).cancel,y=e.getLiveGame().onWindowEvent("keyup",p).cancel;return()=>{u(),g(),y()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",d).cancel,y=e.getLiveGame().onPlayerEvent("keyup",p).cancel;return()=>{u(),g(),y()}}},[t,s,a,c]),ka.createElement(ka.Fragment,null)}import Ea,{useEffect as vu}from"react";function Su(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var Da=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],Tu=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]'];function bu(o,e){return!o||e&&Da.some(t=>!!o.closest(t))?!1:[...Tu,...Da].some(t=>!!o.closest(t))}function La(o,e){if(!e)return!1;let t=e.getBoundingClientRect();return o.clientX>=t.left&&o.clientX<=t.right&&o.clientY>=t.top&&o.clientY<=t.bottom}function Ia({state:o}){let e=M();return vu(()=>{let t=e.getLiveGame().gameState?.playerCurrent;if(!t){o.logger.warn("StageClickAnnouncer","Failed to listen to playerElement events");return}let n=i=>{let r=i.target;if(!r||!t.contains(r)||!La(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!La(i,s))||Su(r)||bu(r,o.isNvlMode())||(o.events.emit(I.EventTypes["event:state.player.stageClick"]),o.recordStageClick())};if(e.config.useWindowListener){let i=e.getLiveGame().onWindowEvent("click",n);return()=>{i.cancel()}}else{let i=e.getLiveGame().onPlayerEvent("click",n);return()=>{i.cancel()}}},[e,o]),Ea.createElement(Ea.Fragment,null)}import{useEffect as Ra}from"react";function wr({gameState:o}){let e=o.audioManager,[t,n]=on("globalVolume");return Ra(()=>{n(e.getGlobalVolume())},[]),Ra(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as yo,useRef as Au}from"react";function Ma(o){let e=Ee.catSrc(o.srcManager?.src||[]),t=Ee.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=new Set;for(let s of e.image){let a=Ee.getSrc(s);!a||r.has(a)||(r.add(a),n.push(a))}for(let s of t.image){let a=Ee.getSrc(s);!a||r.has(a)||(r.add(a),i.push(a))}return{critical:n,lookAhead:i,all:[...n,...i],criticalAudio:e.audio}}function Na({state:o}){let{preloaded:e,cacheManager:t}=Nt(),n=M(),i=Au(new Set),[r]=re(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit(Be.EventTypes["event:preloaded.unmount"])}return yo(()=>o.events.on(I.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),yo(()=>{if(typeof fetch>"u")return e.events.emit(Be.EventTypes["event:preloaded.complete"]),e.events.emit(Be.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),u;if(!n.config.preloadAllImages)return e.events.emit(Be.EventTypes["event:preloaded.complete"]),e.events.emit(Be.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),u;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!l||!a)return l?o.logger.debug(s,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(s,"Story not found, skipping preload"),u;let d=performance.now(),p=Ma(a),g=new yn(n.config.preloadConcurrency,0),y=new yn(n.config.preloadConcurrency,n.config.preloadDelay),f=o.logger.group(s,!0),h=!1;o.logger.debug(s,"preloading:",p,a);let A=(m,v,x,b)=>{v.forEach((S,C)=>{if(t.has(S)||t.isPreloading(S)){o.logger.debug(s,`Image already loaded (${x} ${C+1}/${v.length})`,S);return}m.addTask(()=>new Promise(E=>{t.preload(o,S,{retainDecoded:b}).onFinished(()=>{o.logger.debug(s,`Image loaded (${x} ${C+1}/${v.length})`,S),E()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${x} ${C+1}/${v.length})`,S),E()})}))})};A(g,p.critical,"first scene",!0),A(y,p.lookAhead,"look-ahead",!1);for(let m of p.criticalAudio)o.audioManager.preload(m);return f.end(),g.start().then(async()=>{o.logger.info(s,"Image preload (first scene)",`loaded ${t.size()} images in ${performance.now()-d}ms`),e.events.emit(Be.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(Be.EventTypes["event:preloaded.ready"]),!h&&(await y.start(),!h&&(o.logger.info(s,"Image preload (look-ahead)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(p.all)))}),n.config.waitForPreload||e.events.emit(Be.EventTypes["event:preloaded.ready"]),e.events.emit(Be.EventTypes["event:preloaded.mount"]),()=>{h=!0,u()}},[a,l]),yo(()=>{i.current.clear()},[a]),yo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let d=performance.now(),p=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(m=>Ee.getPreloadableSrc(l,m)).filter(function(m){return m!==null});p.filter(function(m){return m?.activeType==="scene"}).forEach(m=>{i.current.has(m)||i.current.add(m)});let y=Ee.catSrc([...i.current,...p]),f=new yn(n.config.preloadConcurrency,n.config.preloadDelay),h=[],A=o.logger.group(s);o.logger.debug(s,"preloading:",y);for(let m of y.image){let v=Ee.getSrc(m);if(v){if(h.push(v),t.has(v)||t.isPreloading(v)){o.logger.debug(s,`Image already loaded (${y.image.indexOf(m)+1}/${y.image.length})`,v);continue}f.addTask(()=>new Promise(x=>{t.preload(o,v).onFinished(()=>{o.logger.debug(s,`Image loaded (${y.image.indexOf(m)+1}/${y.image.length})`,v),x()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${y.image.indexOf(m)+1}/${y.image.length})`,v),x()})}))}}A.end(),f.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(h)})},[c,l]),null}import ri from"react";import vo from"react";import kr,{useEffect as Pr,useLayoutEffect as Er,useRef as Dr,useState as Lr}from"react";function Vt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,u]=Lr(null),[d,p]=Lr(null),g=kr.useRef(null),[y]=Lr(()=>new Si("displayable.refGroup")),f=Dr(y.next()),h=Dr(et()),m=M().getLiveGame().getGameState(),v=typeof a=="function"?a(l):a,[x]=re([d,l,h]);Pr(()=>m.events.depends([m.events.on(I.EventTypes["event:state.player.skip"],dt)]).cancel,[d,l,h]),Er(()=>{if(C(),!l)return;if(h.current.some(([me])=>!me.current))throw new L("Displayable: Trying to access transition groups before they are mounted");let{controller:K,task:le}=l,oe=me=>{h.current.forEach(([ve],pe)=>{let Qe=le.resolve[pe],P=typeof Qe=="function"?Qe:Qe.resolver;if(!P)throw new L(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${pe}])`);let V=P(...me),fe=z(v[pe]||v[v.length-1]||{},V);O(ve,c?c(fe):fe)})},ue=K.onUpdate(oe);oe(le.animations.map(me=>me.start));let F=!1;return Promise.all(h.current.map(([me])=>{let ve=me.current;return ve?.waitForLoad?ve.waitForLoad():Promise.resolve()})).then(()=>{F||K.start()}),()=>{F=!0,ue.cancel()}},[l]),Pr(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Er(()=>{let K=e.toStyle(m,i);Object.assign(g.current.style,K),m.logger.debug("Displayable","Initial style applied",g.current,K)},[]);let b=Dr(()=>{});b.current=()=>{d||l||!g.current||(Object.assign(g.current.style,e.toStyle(m,i)),C())},Er(()=>{b.current()});let{ratio:S}=Te();Pr(()=>S.onUpdate(()=>{b.current(),requestAnimationFrame(()=>b.current())}),[S]);function C(){let K=typeof a=="function"?a(l):a;if(!h.current||!h.current.length)throw new L("Displayable: Transition group refs are not initialized correctly");h.current.some(([le])=>!le.current)||h.current.forEach(([le],oe)=>{O(le,K[oe]||K[K.length-1]||{})})}function E(K){m.logger.debug("Displayable","Transform applied",e.toStyle(m,i),g.current),x(),r?.(K)}function O(K,le){if(!K.current)throw new L("Displayable: Trying to assign properties to unmounted element");let oe=K.current,ue={},F={};Object.keys(le).forEach(ve=>{let pe=ve;pe==="style"&&le.style?Object.assign(ue,le.style):le[pe]!==void 0&&pe!=="key"&&(F[pe]=le[pe])}),Object.keys(ue).length>0&&Object.assign(oe.style,ue);let me=c?c(F):F;for(let[ve,pe]of Object.entries(me))oe.getAttribute(ve)!==pe&&oe.setAttribute(ve,pe)}function _(K,le){d&&(d.abort(),p(null));let oe=K.animate(e,{gameState:m,ref:g,overwrites:i}),ue=new Ie(oe);return m.timelines.attachTimeline(ue),oe.onSkipControllerRegister(F=>{F.onAbort(()=>{ue.abort(),p(null)})}),p(oe),oe.then(()=>{p(null),E(K),le()}),ue}function se(K,le){l&&l.controller.complete();let oe=K.createTask(m),ue=K.requestAnimations(oe.animations),F=new T().registerSkipController(new H(ue.cancel)),me=new Ie(F);F.skipController.onAbort(()=>{ue.cancel()}),ue.onCanceled(()=>{me.abort(),u(null),m.logger.debug("Displayable","Transition cancelled",K)}),ue.onComplete(()=>{be(),u(null),s?.(K),le(),F.resolve()}),m.timelines.attachTimeline(me),u({task:oe,controller:ue,transition:K,resolve:le});let ve;if(h.current=oe.resolve.map(pe=>{let Qe=kr.createRef(),P=typeof pe=="function"?void 0:pe.key;if(!P)return[Qe,y.next()];if(P==="target")return ve=y.next(),[Qe,ve];if(P==="current")return[Qe,f.current];throw new L("Displayable: Invalid key type")}),!ve)throw new L("Displayable: No target key found");return f.current=ve,me}function ze(K){return m.logger.debug("initDisplayable",o),_(Y.immediate(e.get()),K)}function dt(){t&&d&&(d.abort(),p(null),m.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),m.logger.debug("transition skipped"))}function et(){return[[kr.createRef(),f.current]]}function be(){h.current.forEach(([K])=>{K.current=null}),h.current=et()}return{transformRef:g,transitionRefs:h.current,transitionTask:l,initDisplayable:ze,applyTransform:_,applyTransition:se,updateStyleSync:C,flush:x,deps:[d,l,h]}}import{useEffect as xu}from"react";function ft(o,e,t=[]){let i=M().getLiveGame().getGameState();return xu(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Ir({state:o,text:e}){let{ratio:t}=Te(),[n]=re(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:u}=Vt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:d=>({width:"fit-content",transform:Y.propToCSSTransform(o,d,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return ft(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...u]),vo.createElement(Mt.Div,{"data-element-type":"text"},vo.createElement(Mt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([d,p])=>vo.createElement("span",{key:p,ref:d,className:e.config.className},vo.createElement("span",null,e.state.text)))))}import bt,{forwardRef as wu,useCallback as Va,useImperativeHandle as ku,useRef as bo,useState as Fa}from"react";import So,{useEffect as Rr,useRef as In,forwardRef as Cu}from"react";var Ga=Cu(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=In(null),{ratio:a}=Te(),[c,l]=So.useState(0),[u,d]=So.useState(0),p=In(null),g=In(null),y=M(),f=In(!1),h=In(null),A=In(null);So.useImperativeHandle(r,()=>s.current,[]),Rr(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>f.current,configurable:!0},waitForLoad:{value:()=>{let b=()=>{let S=s.current;return!S||typeof S.decode!="function"?Promise.resolve():S.decode().catch(()=>{})};return f.current?b():(h.current||(h.current=new Promise(S=>{A.current=S})),h.current.then(b))},configurable:!0}})},[]),Rr(()=>(m(),a.onUpdate(m)),[o]),Rr(()=>{let b=new MutationObserver(S=>{S.forEach(C=>{C.type==="attributes"&&C.attributeName==="src"&&s.current&&m()})});return s.current&&b.observe(s.current,{attributes:!0}),()=>{b.disconnect()}},[o]);function m(){if(s.current&&s.current.naturalWidth){let b,S,C;if(s.current.naturalWidth*s.current.naturalHeight===1)b=a.state.width,S=a.state.height,C=`${b} / ${S}`;else{let se=t?y.config.width/s.current.naturalWidth:1;b=s.current.naturalWidth*a.state.scale*se,S=s.current.naturalHeight*a.state.scale*se,C="auto"}let E=p.current,O=!E||E.w!==b||E.h!==S||E.ar!==C,_=!!o&&g.current!==o;if(!O&&!_)return;O&&(p.current={w:b,h:S,ar:C},l(b),d(S),s.current.style.aspectRatio=C),o&&(g.current=o,o(b,S))}}function v(){m(),f.current=!0,A.current&&(A.current(),A.current=null,h.current=null),e&&e()}function x(){f.current=!0,A.current&&(A.current(),A.current=null,h.current=null)}return So.createElement("img",{ref:s,onLoad:v,onError:x,width:c,height:u,alt:"",src:n,style:i})});Ga.displayName="AspectScaleImage";var To=Ga;import Ha from"clsx";import{motion as Pu}from"motion/react";var Eu={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Ua=wu(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=bo(null),a=bo([]),c=o.findIndex(l=>l!==null);return ku(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(l=>!l?.isLoaded||l.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(l=>l?.waitForLoad?l.waitForLoad():Promise.resolve())).then(()=>{})}),[]),bt.createElement("div",{ref:s},o.map((l,u)=>l===null?null:bt.createElement(To,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(l),style:Eu,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});Ua.displayName="LayerStack";function Du(o){return{willChange:"filter, opacity",position:"absolute",top:0,left:0,right:0,bottom:0,transform:"none",translate:"none",opacity:1,clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat",filter:`brightness(${1-o})`}}function Lu(o){return R.isStaticSrc(o)?o.state.currentSrc:R.getSrcURL(o)??void 0}var Iu={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function Ru({image:o,state:e}){let[t]=Fa(()=>new q),[n,i]=Fa([]),{cacheManager:r}=Nt(),s=bo([]),a=bo(null),c=R.isLayeredSrc(o)?R.getSrcURLs(o):null;function l(b){return!k.isDataURI(b)&&!r.has(b)&&!r.isPreloading(b)&&!s.current.includes(b)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${b}".
49
+ `&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function xl(o,e,t){return t||(o!==void 0?Se.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new Z(n.text,n.config)):[])}function Cl(o,e,t){let n=Math.max(0,e??t);return typeof o=="object"?{enabled:o.enabled??!0,delay:Math.max(0,o.delay??n)}:{enabled:o??!0,delay:n}}function ma(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function po(o){return o===void 0?void 0:An(o)}function gr({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,writingMode:c,textOrientation:l,tateChuYoko:u,...d}){let p=I(),g=p.getLiveGame().getGameState(),h=fa(null),[m,y]=mr(()=>n&&!n.config.useTypeEffect?fr(n.config.evaluatedWords):[]),[A,f]=se();if(!n)throw new Error("Dialog state is required");Nn(()=>{if(!(!n.config.action.sentence||h.current))return g.logger.info("Initializing the sentence",n,h.current),g.schedule(({onCleanup:G})=>{if(!n.config.useTypeEffect){da(n.config.evaluatedWords,n.config.firedTextEvents??new Set,g),n.dispatchComplete();return}y([]),h.current=v(),A(),h.current.onComplete(()=>{n.dispatchComplete()}),G(()=>{h.current?.timeline?.abort()})},0)},[]),Nn(()=>n.events.depends([n.events.on(Me.Events.requestComplete,()=>{h.current?.interact()}),n.events.on(Me.Events.forceSkip,()=>{n.isEnded()||h.current?.forceSkip()})]).cancel,[n,f]),Nn(()=>p.preference.events.depends([p.preference.onPreferenceChange(re.Preferences.gameSpeed,()=>{h.current?.update()}),p.preference.onPreferenceChange(re.Preferences.autoForward,()=>{h.current?.update()}),p.preference.onPreferenceChange(re.Preferences.cps,()=>{h.current?.update()})]).cancel,[]);function v(){let G=new T,de=new Ne(G).setGuard(g.guard),ke=new Set,ht=n.config.firedTextEvents??new Set,Ze=new Set,ot=new Set,q=hr(n.config.evaluatedWords),X=null,H=[],te=[],Pe=()=>{H.forEach(ce=>ce()),H.length=0},Te=()=>{if(te.length!==0)return{done:!1,value:te.shift()};let{done:ce,value:le}=q.next();return{done:ce,value:le}},ae=ce=>{let le=gt=>{ce(gt),Ze.delete(le)};return Ze.add(le),{cancel:()=>{Ze.delete(le)}}},fe=ce=>{ha(y,ce)},F=(ce=!1)=>{let le=!1;for(;!le;){let{done:gt,value:he}=Te();if(gt){le=!0;break}if(Be.isPause(he)){if(ce)continue;le=!0,te.push(he);break}else at.isTextEvent(he)?co(he,ht,g):he===`
50
+ `?y(qe=>[...qe,he]):typeof he=="object"&&"text"in he&&!ke.has(he)&&(ke.add(he),fe(he))}X&&!X.isSettled()?X.abort():(ot.forEach(gt=>gt()),G.resolve())};return g.schedule(async ce=>{let le=!1,gt=!1;for(;!le;){let{done:he,value:qe}=Te();if(he){le=gt=!0;break}if(at.isTextEvent(qe)){co(qe,ht,g);continue}let yi=new T;if(g.timelines.attachTimeline(yi),yi.registerSkipController(new V(()=>{Pe(),le=!0,ce.retry()})),yi.onSettled(()=>{Pe()}),X=yi,Be.isPause(qe)){let vi=Be.from(qe),Si=p.preference.getPreference(re.Preferences.gameSpeed);if(vi.config.duration){let Ti=vi.config.duration/Si;await Di(Ti)}else{let Ti=p.preference.getPreference(re.Preferences.autoForward),bi=T.race([T.create(kc=>{let Pc=ae(Ec=>{Ec(),kc.resolve()});H.push(()=>Pc.cancel())}),...Ti?[T.delay(p.config.autoForwardDefaultPause/Si)]:[]]);g.timelines.attachTimeline(bi),await T.wait(bi)}}else{if(qe!==`
51
+ `&&ke.has(qe))continue;ke.add(qe),fe(qe);let{gameSpeed:vi,cps:Si}=p.preference.getPreferences(),bi=1e3/((typeof qe=="object"&&"cps"in qe&&qe.cps!==void 0?qe.cps:Si)*vi);await Di(bi)}}gt&&(ot.forEach(he=>he()),G.resolve())},0),{getToken:()=>G,interact:()=>{let ce=!1;Ze.forEach(le=>le(()=>ce=!0)),!ce&&F()},update:()=>{X&&X.abort()},forceSkip:()=>{F(!0)},timeline:de,onComplete:ce=>(ot.add(ce),{cancel:()=>{ot.delete(ce)}})}}let x=n.config.action.sentence;if(!x)return null;let S=s??"bold",b={fontWeight:x.config.bold?S:r,fontSize:x.config.fontSize??i,color:po(x.config.color??o),fontFamily:x.config.fontFamily??a,fontStyle:x.config.italic?"italic":void 0},w=G=>({fontWeight:G.config.bold||x.config.bold?S:r,fontSize:G.config.fontSize??x.config.fontSize??i,color:po(G.config.color??x.config.color??o),fontFamily:G.config.fontFamily??x.config.fontFamily??a,fontStyle:G.config.italic??x.config.italic?"italic":void 0}),D=lo(c),B=(G,de)=>G===`
52
+ `?ze.createElement("br",{key:de}):ze.createElement(Ht.Span,{tag:`say.word.${de}`,key:de,style:{...w(G),...dr(D),...Li(p.config.app.debug,{outline:"1px dashed red"})},className:uo("inline-block",G.config.className)},G.config.ruby?ze.createElement("ruby",{className:"align-bottom inline-block"},ze.createElement("rt",{className:"block text-center"},G.config.ruby),ii(G.text,D,u)):ii(G.text,D,u));return ze.createElement("div",{...d,className:uo("whitespace-pre-wrap",e),style:{...b,...pr(c,l),...t}},m.map(B))}function wl({text:o,sentence:e,words:t,useTypeEffect:n=!0,loop:i=!0,restartDelay:r,cps:s,gameSpeed:a,pauseDuration:c,defaultColor:l,className:u,style:d,fontSize:p,fontWeight:g,fontWeightBold:h,fontFamily:m,writingMode:y,textOrientation:A,tateChuYoko:f,onCompleted:v,...x}){let S=_s(),[,b]=mr(0),w=S?.config??re.DefaultConfig,D=S?.preference.getPreferences()??re.DefaultPreference,B=s??D.cps,G=a??D.gameSpeed,de=c??w.autoForwardDefaultPause,ke=r??w.autoForwardDefaultPause,ht=ze.useMemo(()=>xl(o,e,t),[o,e,t]),Ze=ze.useMemo(()=>Cl(i,r,ke),[i,r,ke]),ot=fa(v),[q,X]=mr(()=>n?[]:fr(ht));Nn(()=>{if(S)return S.preference.onPreferenceChange(()=>{b(F=>F+1)}).cancel},[S]),Nn(()=>{ot.current=v},[v]),Nn(()=>{let F=!1,M=[],ve=Math.max(.01,G),Ue=le=>new Promise(gt=>{let he=setTimeout(gt,Math.max(0,le));M.push(he)}),O=()=>{F||ot.current?.()};return n?ht.length===0?(X([]),()=>{F=!0}):((async()=>{do{let le=hr(ht);for(X([]);!F;){let{done:gt,value:he}=le.next();if(gt)break;if(Be.isPause(he)){let qe=Be.from(he);await Ue((qe.config.duration??de)/ve)}else{if(at.isTextEvent(he))continue;ha(X,he),he===`
53
+ `?await Ue(ma(B,G)):await Ue(ma(he.cps??B,G))}}if(F)return;O(),Ze.enabled&&await Ue(Ze.delay)}while(!F&&Ze.enabled)})(),()=>{F=!0,M.forEach(le=>clearTimeout(le))}):(X(fr(ht)),O(),()=>{F=!0})},[ht,n,Ze,B,G,de]);let H=e?.config,te=h??"bold",Pe={fontWeight:H?.bold?te:g,fontSize:H?.fontSize??p,color:po(H?.color??l),fontFamily:H?.fontFamily??m,fontStyle:H?.italic?"italic":void 0},Te=F=>({fontWeight:F.config.bold||H?.bold?te:g,fontSize:F.config.fontSize??H?.fontSize??p,color:po(F.config.color??H?.color??l),fontFamily:F.config.fontFamily??H?.fontFamily??m,fontStyle:F.config.italic??H?.italic?"italic":void 0}),ae=lo(y),fe=(F,M)=>F===`
54
+ `?ze.createElement("br",{key:M}):ze.createElement("span",{key:M,style:{...Te(F),...dr(ae)},className:uo("inline-block",F.config.className)},F.config.ruby?ze.createElement("ruby",{className:"align-bottom inline-block"},ze.createElement("rt",{className:"block text-center"},F.config.ruby),ii(F.text,ae,f)):ii(F.text,ae,f));return ze.createElement("div",{...x,className:uo("whitespace-pre-wrap",u),style:{...Pe,...pr(y,A),...d}},q.map(fe))}function ga(o){return ze.createElement(gr,{...o,key:o.dialog?.config.action.id})}function kl({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=ao({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return ze.createElement(gr,{...r,dialog:s,key:s.config.action.id})}function Pl(o){let e=xt();return ze.createElement(gr,{...o,dialog:e,key:e.config.action.id})}function ln(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?ze.createElement(kl,{...o}):ze.createElement(Pl,{...o})}var El=ln;import fo,{useEffect as Dl,useLayoutEffect as Ll,useMemo as va,useRef as Il,useState as Rl}from"react";import mo from"react";var yr=mo.createContext(null);function vr(){let o=mo.useContext(yr);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Sr=mo.createContext(null);function ya(){let o=mo.useContext(Sr);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function ho({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let c=Il(null),{register:l,unregister:u,getIndex:d}=ya(),[p,g]=Rl(-1),{choose:h,evaluated:m,gameState:y}=vr(),A=p===-1?null:m[p],f=va(()=>Ce.getCtx({gameState:y}),[y]),{hidden:v,disabled:x}=va(()=>{if(!A)return{hidden:!1,disabled:!1};let w=A.config.hidden?.evaluate(f)?.value??!1,D=!w&&(A.config.disabled?.evaluate(f)?.value??!1);return{hidden:w,disabled:D}},[A,f]);Ll(()=>{if(!c.current)return;let w=c;l(w);let D=d(w);return g(D),c.current.dataset.index=D.toString(),()=>u(w)},[l,u,d]),Dl(()=>{if(!t)return;let w=D=>{D.key.toLowerCase()===t.toLowerCase()&&!D.ctrlKey&&!D.metaKey&&(D.preventDefault(),D.stopPropagation(),S())};return window.addEventListener("keydown",w,!0),()=>{window.removeEventListener("keydown",w,!0)}},[t]);function S(){if(p===-1||!m[p]||v||x)return;let w=m[p];h({...w,evaluated:Z.getText(w.words||[])})}let b=A&&!v;return fo.createElement(fo.Fragment,null,fo.createElement("button",{className:o,style:{...e,display:b?e?.display??void 0:"none"},onClick:S,ref:c,disabled:x},b&&fo.createElement(ga,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Me({useTypeEffect:!1,action:{sentence:A.prompt,words:A.words,character:null},gameState:y,evaluatedWords:A.words})})))}import go from"react";import{AnimatePresence as Ml}from"motion/react";function yo({children:o,...e}){let t=Ml;return go.createElement(go.Fragment,null,go.createElement("div",{...e},go.createElement(t,null,o)))}import Sa from"react";function qt({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=Sa.useContext(gn),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return Sa.createElement("div",{...s,style:{color:l?An(l):void 0,...r}},u)}import Vl from"clsx";import Hl from"react";import Tr,{createContext as Nl,useContext as Gl,useState as Ta}from"react";var vn=class vn{constructor(){this.preloaded=[];this.events=new Q}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(vn.EventTypes["event:preloaded.add"],e),this.events.emit(vn.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(i=>this.getSrc(i));return this.preloaded=this.preloaded.filter(i=>!n.includes(this.getSrc(i))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(vn.EventTypes["event:preloaded.remove"],e),this.events.emit(vn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Le.getSrc(e)}};vn.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.complete":"event:preloaded.complete","event:preloaded.unmount":"event:preloaded.unmount"};var $e=vn;var vo=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.decoded=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear(),this.decoded.clear()})}static getImage(e,t,n){return bs(e,{...n,signal:t})}static async decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return null;let t=new window.Image;if(t.src=e,typeof t.decode!="function")return null;try{await t.decode()}catch{return null}return t}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this.decoded.delete(e),this}get(e){return this.src.get(e)}isDecoded(e){return this.decoded.has(e)}clear(){return this.src.clear(),this.decoded.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t,n){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let i=t,r={};this.game.hooks.rawTrigger("preloadImage",()=>[i,(p,g)=>{i=p,r={...r,...g}}]);let s=new AbortController,a=s.signal,c=[],u={promise:o.getImage(i,a,r).then(async p=>{if(this.preloadTasks.delete(t),p){this.add(t,p);let g=await o.decodeImage(p);g&&n?.retainDecoded&&this.src.get(t)===p&&this.decoded.set(t,g)}}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),c.forEach(g=>g(p))}),controller:s};this.preloadTasks.set(t,u);let d={abort:()=>{s.abort(),this.preloadTasks.delete(t)},onFinished:p=>(u.promise.then(p),d),onErrored:p=>(c.push(p),d)};return d}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){let t=new Set(e);for(let n of this.src.keys())t.has(n)||(this.src.delete(n),this.decoded.delete(n));for(let n of this.decoded.keys())t.has(n)||this.decoded.delete(n);return this}};var br=Nl(null);function ba({children:o}){let e=I(),[t]=Ta(()=>new $e),[n]=Ta(()=>new vo(e));return Tr.createElement(Tr.Fragment,null,Tr.createElement(br,{value:{preloaded:t,cacheManager:n}},o))}function Ft(){if(!br)throw new Error("usePreloaded must be used within a PreloadedProvider");return Gl(br)}function Aa(){let o=xt(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return Ol(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?L.getSrcURL(s):null,c=s&&L.isTagSrc(s)?[...s.state.currentSrc]:null,l=Ks({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=Ul(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Fl({className:o,style:e,alt:t,...n}){let i=Aa(),{cacheManager:r}=Ft();if(!i.visible||!i.src)return null;let s=r.get(i.src)||i.src;return Hl.createElement("img",{...n,"data-element-type":"dialog-avatar",className:Vl("dialog-avatar",o),src:s,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function Ul(o){return o?k.srcToURL(o):null}function Ol(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var Ar=Fl;import{useEffect as Bl}from"react";function Kl(){let o=xt(),[e]=se(o.deps),t=Z.getText(o.config.evaluatedWords);return Bl(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as So,useEffect as xr,useMemo as Wl,useRef as zl,useState as xa}from"react";function $l(){let o=xt(),[e]=se(o.deps),[t,n]=xa(!0),[i,r]=xa(!0),s=zl(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;xr(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]);let u=Wl(()=>{if(!c)return null;try{return nt.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);xr(()=>{s.current=null,r(!0)},[c]),xr(()=>{let m=!1,y=null,A=null,f=null;if(!u){n(!0);return}n(!1);let v=()=>{m||n(!0)};y=a.audioManager.getToken(u),y&&(y.isPlaying()||n(!0),A=()=>v(),f=()=>v(),y.once("ended",A),y.once("stop",f));let x=a.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{v()});return()=>{m=!0,x.cancel(),y&&A&&y.off("ended",A),y&&f&&y.off("stop",f)}},[a,u]);let d=So(async m=>{let y=m??u;if(!y)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let A=y instanceof URL?Ae.voice(y.toString()):typeof y=="string"?Ae.voice(y):y,f=await a.getLiveGame().playSound(A);s.current=f;let v=()=>{r(!0)};return f.once("ended",v),f.once("stop",v),f},[a,u]),p=So(()=>u,[u]),g=So(()=>l,[l]),h=So(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:g,getVoiceSrc:h}}import Cr,{createContext as iu,useContext as ou,useEffect as ka,useRef as ru}from"react";import{useState as jl}from"react";function To(o){let[e]=jl(o);return e}import{AnimatePresence as ql}from"motion/react";var bo=ql;import ai,{createContext as Zl,useContext as _l,useEffect as eu,useRef as tu}from"react";import{useEffect as oi,useLayoutEffect as Ql}from"react";function Xl(){let o=Gt(),[e]=se();return oi(()=>o.onChange(e).cancel,[]),o.getPathname()}function Yl(){let{router:o,path:e}=si(),[t]=se();return oi(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function Jl(){let o=Gt(),[e]=se();return oi(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Ao(o,e){let t=Gt();Ql(()=>t.onUpdate(()=>o(t)).cancel,e),oi(()=>{o(t)},[])}function ri(){let o=Gt(),[e]=se();return oi(()=>o.onChange(e).cancel,[]),e}var Ca=Zl(null);function ci({children:o,path:e,consumedBy:t}){let i={router:Gt(),path:e,consumedBy:t};return ai.createElement(Ca,{value:i},o)}function si(){let o=_l(Ca);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new P(`Invalid useLayout call: Trying to access layout without a parent.
55
+ This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function nu({children:o,name:e,propagate:t}){let n=I(),[i]=se(),{path:r,router:s,consumedBy:a}=si(),c=s.joinPath(r,e),l=To(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),d=tu(!1),p=h=>{d.current=h,i()},g=s.matchPath(u,c);if(ri(),Ao(h=>{let m=h.matchPath(h.getCurrentPath(),c);if(d.current&&!m){if(!o){p(!1);return}h.registerUnmountingPath(l)}m&&h.isPathsUnmounting()&&h.unregisterUnmountingPath(l),m&&!d.current&&!h.isTransitioning()&&p(!0)},[g,o]),eu(()=>{if(!g)return;let h=s.mount(c);return()=>{h.cancel()}},[c,s,g]),a)throw new P("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return ai.createElement(ci,{path:c},ai.createElement(bo,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),p(!1)}},g&&d.current&&o))}function wa({children:o}){return ri(),ai.createElement(ci,{path:an.rootPath},ai.createElement(no,{"data-layout-path":an.rootPath,key:an.rootPath},o))}var wr=iu(null);function su(){return ou(wr)}function au({children:o,name:e}){let[t]=se(),{path:n,router:i,consumedBy:r}=si(),s=su(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=To(()=>i.createToken(l+"@page")),d=i.getCurrentPath(),p=!a,g=ru(!1),h=f=>{g.current=f,t()},m=p&&i.exactMatch(d,n)||i.exactMatch(d,l);if(r&&r!==c)throw new P("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");ri(),Ao(f=>{let v=p&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(g.current&&!v){if(!o){h(!1);return}f.registerUnmountingPath(u)}v&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(u),v&&!g.current&&!f.isTransitioning()&&h(!0)},[m,o]),ka(()=>{if(!m)return;let f=p?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{f.cancel()}},[l,m]),ka(()=>()=>{i.unregisterUnmountingPath(u),h(!1)},[]);let y=Cr.createElement(ci,{path:n,consumedBy:c},Cr.createElement(bo,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),h(!1)}},m&&g.current&&o));return(f=>s?Cr.createElement(wr,{value:{name:null}},f):f)(y)}import kr,{useCallback as cu,useEffect as Pr,useImperativeHandle as lu,useMemo as Pa,useRef as Er,useState as uu}from"react";var pu=50,du={position:"relative",width:"100%",height:"100%",overflow:"hidden"},Ea={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function mu(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function Da(o,e){return e==null?o:Math.max(o,e)}function fu(o,e,t){return o<=0||e<=0||t<=0?{width:o,height:e}:o/e>t?{width:e*t,height:e}:{width:o,height:o/t}}var La=kr.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:d},p){let g=Er(null),[h,m]=uu({...Ea,width:"0px",height:"0px"}),y=Er(u),A=Er(null);Pr(()=>{y.current=u},[u]);let f=cu(()=>{let S=g.current;if(!S)return;let b=S.clientWidth,w=S.clientHeight;if(b<=0||w<=0||e<=0)return;let D=fu(b,w,e),B=Da(D.width,n),G=Da(D.height,i),de=A.current;(!de||de.width!==B||de.height!==G)&&(A.current={width:B,height:G},m({...Ea,width:`${B}px`,height:`${G}px`}));let ke=t>0?B/t:1;y.current?.({width:B,height:G,scale:ke,containerWidth:b,containerHeight:w})},[e,t,n,i]),v=Pa(()=>Ss(f,typeof r=="number"?r:pu),[f,r]);Pr(()=>{f()},[f]),Pr(()=>{let S=new ResizeObserver(()=>{v()});g.current&&S.observe(g.current);let b=()=>{v()};return window.addEventListener("resize",b),()=>{S.disconnect(),window.removeEventListener("resize",b)}},[v]),lu(p,()=>({requestUpdate:f}),[f]);let x=Pa(()=>mu(l),[l]);return kr.createElement("div",{id:c,ref:g,style:du,...x},kr.createElement("div",{className:s,style:{...h,...a}},d))}),Ia=La;function hu(){return I().getLiveGame()}import Ir from"react";import gu,{createContext as yu,useContext as vu,useEffect as Su,useState as Ra}from"react";var Tu={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Ma=yu({state:Tu,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function Ut(){return vu(Ma)}function Dr(){let{dialogs:o}=Ut();return o}function bu(){let{isActive:o}=Ut();return o}function Au(){let{isVisible:o}=Ut();return o}function Lr({children:o}){let t=I().getLiveGame().getGameState(),[n,i]=Ra(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Ra(null);Su(()=>{let c=h=>({...h,dialogs:[...h.dialogs]}),l=t.events.on(E.EventTypes["event:state.nvl.enter"],(h,m)=>{i(c(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(E.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),d=t.events.on(E.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),p=t.events.on(E.EventTypes["event:state.nvl.visibilityChange"],(h,m)=>{i(c(t.getNvlState())),s(m||null)}),g=t.events.on(E.EventTypes["event:state.nvl.change"],h=>{i(c(h))});return()=>{l.cancel(),u.cancel(),d.cancel(),p.cancel(),g.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return gu.createElement(Ma.Provider,{value:a},o)}import{AnimatePresence as xu,motion as Cu}from"motion/react";import wu from"clsx";function Rr({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=Ut(),{ratio:r}=be(),s=I(),a=i?.duration?i.duration/1e3:.3;return Ir.createElement(xu,null,n&&Ir.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},Ir.createElement(Cu.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:wu("w-full h-full overflow-auto",e),style:{transform:s.config.useAspectScale?`scale(${r.state.scale})`:void 0,transformOrigin:"top left",width:s.config.useAspectScale?s.config.width:"100%",height:s.config.useAspectScale?s.config.height:"100%",...t}},o)))}import Sn from"react";function Mr({renderDialogItem:o,dialogs:e}){return Sn.createElement(Rr,{className:"bg-black/80 text-white p-16 inset-8"},Sn.createElement("div",{"data-element-type":"nvl-dialog-list",className:"flex flex-col space-y-4 p-4"},(e??[]).map((n,i)=>{let r=n.entry.character?Sn.createElement(qt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=Sn.createElement(ln,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return Sn.createElement("div",{key:`${n.entry.id}:${n.isActive?"active":"idle"}`,"data-element-type":"nvl-dialog-item","data-dialog-index":i,className:"nvl-dialog-item"},o?o({entry:n.entry,index:i,isActive:n.isActive,nametag:r,texts:s}):Sn.createElement(Sn.Fragment,null,r,s))})))}import ft,{useMemo as ku}from"react";import Na from"clsx";function Pu({children:o,className:e,style:t,renderDialogItem:n}){let i=Dr(),{state:r}=Ut();return ft.createElement("div",{"data-element-type":"nvl-dialog-list",className:Na("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>ft.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},ft.createElement(Eu,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?ft.createElement(qt,{className:"nvl-character-name font-bold mr-2"}):null,texts:ft.createElement(ln,{className:"nvl-dialog-text"})}):o?ft.Children.map(o,c=>ft.isValidElement(c)?ft.cloneElement(c,{entry:s,index:a}):c):ft.createElement(Ga,{entry:s,index:a})))))}function Ga({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??ft.createElement(ln,{className:"nvl-dialog-text"});return ft.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Na("nvl-dialog-item",t),style:n},r&&ft.createElement(qt,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function Eu({entry:o,children:e}){let n=I().getLiveGame().getGameState(),i=ku(()=>o.sentence.evaluate(Ce.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=ao({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return ft.createElement(gn,{value:c},e)}function Ha({state:o}){let e=I(),t=Gt(),n=Nr(null),i=Nr(null),r=Nr(!1),[s]=cn(re.Preferences.skipDelay),[a]=cn(re.Preferences.skipInterval),[c]=yn("skipAction");return Lu(()=>{if(!e.getLiveGame().gameState.playerCurrent){o.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){o.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let u=()=>{i.current&&(clearTimeout(i.current),i.current=null),n.current&&(clearInterval(n.current),n.current=null),r.current=!1},d=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(re.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let h=()=>{n.current=setInterval(()=>{o.events.emit(E.EventTypes["event:state.player.skip"],!1)},a)};u(),o.events.emit(E.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?h():i.current=setTimeout(h,s)}},p=g=>{e.keyMap.match("skipAction",g.key)&&u()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",d).cancel,h=e.getLiveGame().onWindowEvent("keyup",p).cancel;return()=>{u(),g(),h()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",d).cancel,h=e.getLiveGame().onPlayerEvent("keyup",p).cancel;return()=>{u(),g(),h()}}},[t,s,a,c]),Va.createElement(Va.Fragment,null)}import Fa,{useEffect as Iu}from"react";function Ru(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var Ua=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],Mu=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]'];function Nu(o,e){return!o||e&&Ua.some(t=>!!o.closest(t))?!1:[...Mu,...Ua].some(t=>!!o.closest(t))}function Oa(o,e){if(!e)return!1;let t=e.getBoundingClientRect();return o.clientX>=t.left&&o.clientX<=t.right&&o.clientY>=t.top&&o.clientY<=t.bottom}function Ba({state:o}){let e=I();return Iu(()=>{let t=e.getLiveGame().gameState?.playerCurrent;if(!t){o.logger.warn("StageClickAnnouncer","Failed to listen to playerElement events");return}let n=i=>{let r=i.target;if(!r||!t.contains(r)||!Oa(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!Oa(i,s))||Ru(r)||Nu(r,o.isNvlMode())||(o.events.emit(E.EventTypes["event:state.player.stageClick"]),o.recordStageClick())};if(e.config.useWindowListener){let i=e.getLiveGame().onWindowEvent("click",n);return()=>{i.cancel()}}else{let i=e.getLiveGame().onPlayerEvent("click",n);return()=>{i.cancel()}}},[e,o]),Fa.createElement(Fa.Fragment,null)}import{useEffect as Ka}from"react";function Gr({gameState:o}){let e=o.audioManager,[t,n]=cn("globalVolume");return Ka(()=>{n(e.getGlobalVolume())},[]),Ka(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as xo,useRef as Gu}from"react";function Wa(o){let e=Le.catSrc(o.srcManager?.src||[]),t=Le.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=new Set;for(let s of e.image){let a=Le.getSrc(s);!a||r.has(a)||(r.add(a),n.push(a))}for(let s of t.image){let a=Le.getSrc(s);!a||r.has(a)||(r.add(a),i.push(a))}return{critical:n,lookAhead:i,all:[...n,...i],criticalAudio:e.audio}}function za({state:o}){let{preloaded:e,cacheManager:t}=Ft(),n=I(),i=Gu(new Set),[r]=se(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit($e.EventTypes["event:preloaded.unmount"])}return xo(()=>o.events.on(E.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),xo(()=>{if(typeof fetch>"u")return e.events.emit($e.EventTypes["event:preloaded.complete"]),e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),u;if(!n.config.preloadAllImages)return e.events.emit($e.EventTypes["event:preloaded.complete"]),e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),u;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!l||!a)return l?o.logger.debug(s,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(s,"Story not found, skipping preload"),u;let d=performance.now(),p=Wa(a),g=new bn(n.config.preloadConcurrency,0),h=new bn(n.config.preloadConcurrency,n.config.preloadDelay),m=o.logger.group(s,!0),y=!1;o.logger.debug(s,"preloading:",p,a);let A=(f,v,x,S)=>{v.forEach((b,w)=>{if(t.has(b)||t.isPreloading(b)){o.logger.debug(s,`Image already loaded (${x} ${w+1}/${v.length})`,b);return}f.addTask(()=>new Promise(D=>{t.preload(o,b,{retainDecoded:S}).onFinished(()=>{o.logger.debug(s,`Image loaded (${x} ${w+1}/${v.length})`,b),D()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${x} ${w+1}/${v.length})`,b),D()})}))})};A(g,p.critical,"first scene",!0),A(h,p.lookAhead,"look-ahead",!1);for(let f of p.criticalAudio)o.audioManager.preload(f);return m.end(),g.start().then(async()=>{o.logger.info(s,"Image preload (first scene)",`loaded ${t.size()} images in ${performance.now()-d}ms`),e.events.emit($e.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit($e.EventTypes["event:preloaded.ready"]),!y&&(await h.start(),!y&&(o.logger.info(s,"Image preload (look-ahead)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(p.all)))}),n.config.waitForPreload||e.events.emit($e.EventTypes["event:preloaded.ready"]),e.events.emit($e.EventTypes["event:preloaded.mount"]),()=>{y=!0,u()}},[a,l]),xo(()=>{i.current.clear()},[a]),xo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let d=performance.now(),p=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>Le.getPreloadableSrc(l,f)).filter(function(f){return f!==null});p.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{i.current.has(f)||i.current.add(f)});let h=Le.catSrc([...i.current,...p]),m=new bn(n.config.preloadConcurrency,n.config.preloadDelay),y=[],A=o.logger.group(s);o.logger.debug(s,"preloading:",h);for(let f of h.image){let v=Le.getSrc(f);if(v){if(y.push(v),t.has(v)||t.isPreloading(v)){o.logger.debug(s,`Image already loaded (${h.image.indexOf(f)+1}/${h.image.length})`,v);continue}m.addTask(()=>new Promise(x=>{t.preload(o,v).onFinished(()=>{o.logger.debug(s,`Image loaded (${h.image.indexOf(f)+1}/${h.image.length})`,v),x()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${h.image.indexOf(f)+1}/${h.image.length})`,v),x()})}))}}A.end(),m.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(y)})},[c,l]),null}import li from"react";import Co from"react";import Vr,{useEffect as Hr,useLayoutEffect as Fr,useRef as Ur,useState as Or}from"react";function Ot({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,u]=Or(null),[d,p]=Or(null),g=Vr.useRef(null),[h]=Or(()=>new Ci("displayable.refGroup")),m=Ur(h.next()),y=Ur(Ze()),f=I().getLiveGame().getGameState(),v=typeof a=="function"?a(l):a,[x]=se([d,l,y]);Hr(()=>f.events.depends([f.events.on(E.EventTypes["event:state.player.skip"],ht)]).cancel,[d,l,y]),Fr(()=>{if(w(),!l)return;if(y.current.some(([Te])=>!Te.current))throw new P("Displayable: Trying to access transition groups before they are mounted");let{controller:q,task:X}=l,H=Te=>{y.current.forEach(([ae],fe)=>{let F=X.resolve[fe],M=typeof F=="function"?F:F.resolver;if(!M)throw new P(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${fe}])`);let ve=M(...Te),Ue=z(v[fe]||v[v.length-1]||{},ve);B(ae,c?c(Ue):Ue)})},te=q.onUpdate(H);H(X.animations.map(Te=>Te.start));let Pe=!1;return Promise.all(y.current.map(([Te])=>{let ae=Te.current;return ae?.waitForLoad?ae.waitForLoad():Promise.resolve()})).then(()=>{Pe||q.start()}),()=>{Pe=!0,te.cancel()}},[l]),Hr(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Fr(()=>{let q=e.toStyle(f,i);Object.assign(g.current.style,q),f.logger.debug("Displayable","Initial style applied",g.current,q)},[]);let S=Ur(()=>{});S.current=()=>{d||l||!g.current||(Object.assign(g.current.style,e.toStyle(f,i)),w())},Fr(()=>{S.current()});let{ratio:b}=be();Hr(()=>b.onUpdate(()=>{S.current(),requestAnimationFrame(()=>S.current())}),[b]);function w(){let q=typeof a=="function"?a(l):a;if(!y.current||!y.current.length)throw new P("Displayable: Transition group refs are not initialized correctly");y.current.some(([X])=>!X.current)||y.current.forEach(([X],H)=>{B(X,q[H]||q[q.length-1]||{})})}function D(q){f.logger.debug("Displayable","Transform applied",e.toStyle(f,i),g.current),x(),r?.(q)}function B(q,X){if(!q.current)throw new P("Displayable: Trying to assign properties to unmounted element");let H=q.current,te={},Pe={};Object.keys(X).forEach(ae=>{let fe=ae;fe==="style"&&X.style?Object.assign(te,X.style):X[fe]!==void 0&&fe!=="key"&&(Pe[fe]=X[fe])}),Object.keys(te).length>0&&Object.assign(H.style,te);let Te=c?c(Pe):Pe;for(let[ae,fe]of Object.entries(Te))H.getAttribute(ae)!==fe&&H.setAttribute(ae,fe)}function G(q,X){d&&(d.abort(),p(null));let H=q.animate(e,{gameState:f,ref:g,overwrites:i}),te=new Ne(H);return f.timelines.attachTimeline(te),H.onSkipControllerRegister(Pe=>{Pe.onAbort(()=>{te.abort(),p(null)})}),p(H),H.then(()=>{p(null),D(q),X()}),te}function de(q,X){l&&l.controller.complete();let H=q.createTask(f),te=q.requestAnimations(H.animations),Pe=new T().registerSkipController(new V(te.cancel)),Te=new Ne(Pe);Pe.skipController.onAbort(()=>{te.cancel()}),te.onCanceled(()=>{Te.abort(),u(null),f.logger.debug("Displayable","Transition cancelled",q)}),te.onComplete(()=>{ot(),u(null),s?.(q),X(),Pe.resolve()}),f.timelines.attachTimeline(Te),u({task:H,controller:te,transition:q,resolve:X});let ae;if(y.current=H.resolve.map(fe=>{let F=Vr.createRef(),M=typeof fe=="function"?void 0:fe.key;if(!M)return[F,h.next()];if(M==="target")return ae=h.next(),[F,ae];if(M==="current")return[F,m.current];throw new P("Displayable: Invalid key type")}),!ae)throw new P("Displayable: No target key found");return m.current=ae,Te}function ke(q){return f.logger.debug("initDisplayable",o),G(_.immediate(e.get()),q)}function ht(){t&&d&&(d.abort(),p(null),f.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),f.logger.debug("transition skipped"))}function Ze(){return[[Vr.createRef(),m.current]]}function ot(){y.current.forEach(([q])=>{q.current=null}),y.current=Ze()}return{transformRef:g,transitionRefs:y.current,transitionTask:l,initDisplayable:ke,applyTransform:G,applyTransition:de,updateStyleSync:w,flush:x,deps:[d,l,y]}}import{useEffect as Vu}from"react";function vt(o,e,t=[]){let i=I().getLiveGame().getGameState();return Vu(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Br({state:o,text:e}){let{ratio:t}=be(),[n]=se(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:u}=Ot({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:d=>({width:"fit-content",transform:_.propToCSSTransform(o,d,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return vt(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...u]),Co.createElement(Ht.Div,{"data-element-type":"text"},Co.createElement(Ht.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([d,p])=>Co.createElement("span",{key:p,ref:d,className:e.config.className},Co.createElement("span",null,e.state.text)))))}import wt,{forwardRef as Fu,useCallback as ja,useImperativeHandle as Uu,useRef as Po,useState as qa}from"react";import wo,{useEffect as Kr,useRef as Gn,forwardRef as Hu}from"react";var $a=Hu(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=Gn(null),{ratio:a}=be(),[c,l]=wo.useState(0),[u,d]=wo.useState(0),p=Gn(null),g=Gn(null),h=I(),m=Gn(!1),y=Gn(null),A=Gn(null);wo.useImperativeHandle(r,()=>s.current,[]),Kr(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let S=()=>{let b=s.current;return!b||typeof b.decode!="function"?Promise.resolve():b.decode().catch(()=>{})};return m.current?S():(y.current||(y.current=new Promise(b=>{A.current=b})),y.current.then(S))},configurable:!0}})},[]),Kr(()=>(f(),a.onUpdate(f)),[o]),Kr(()=>{let S=new MutationObserver(b=>{b.forEach(w=>{w.type==="attributes"&&w.attributeName==="src"&&s.current&&f()})});return s.current&&S.observe(s.current,{attributes:!0}),()=>{S.disconnect()}},[o]);function f(){if(s.current&&s.current.naturalWidth){let S,b,w;if(s.current.naturalWidth*s.current.naturalHeight===1)S=a.state.width,b=a.state.height,w=`${S} / ${b}`;else{let de=t?h.config.width/s.current.naturalWidth:1;S=s.current.naturalWidth*a.state.scale*de,b=s.current.naturalHeight*a.state.scale*de,w="auto"}let D=p.current,B=!D||D.w!==S||D.h!==b||D.ar!==w,G=!!o&&g.current!==o;if(!B&&!G)return;B&&(p.current={w:S,h:b,ar:w},l(S),d(b),s.current.style.aspectRatio=w),o&&(g.current=o,o(S,b))}}function v(){f(),m.current=!0,A.current&&(A.current(),A.current=null,y.current=null),e&&e()}function x(){m.current=!0,A.current&&(A.current(),A.current=null,y.current=null)}return wo.createElement("img",{ref:s,onLoad:v,onError:x,width:c,height:u,alt:"",src:n,style:i})});$a.displayName="AspectScaleImage";var ko=$a;import Qa from"clsx";import{motion as Ou}from"motion/react";var Bu={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Xa=Fu(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=Po(null),a=Po([]),c=o.findIndex(l=>l!==null);return Uu(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(l=>!l?.isLoaded||l.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(l=>l?.waitForLoad?l.waitForLoad():Promise.resolve())).then(()=>{})}),[]),wt.createElement("div",{ref:s},o.map((l,u)=>l===null?null:wt.createElement(ko,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(l),style:Bu,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});Xa.displayName="LayerStack";function Ku(o){return{willChange:"filter, opacity",position:"absolute",top:0,left:0,right:0,bottom:0,transform:"none",translate:"none",opacity:1,clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat",filter:`brightness(${1-o})`}}function Wu(o){return L.isStaticSrc(o)?o.state.currentSrc:L.getSrcURL(o)??void 0}var zu={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function $u({image:o,state:e}){let[t]=qa(()=>new Q),[n,i]=qa([]),{cacheManager:r}=Ft(),s=Po([]),a=Po(null),c=L.isLayeredSrc(o)?L.getSrcURLs(o):null;function l(S){return!k.isDataURI(S)&&!r.has(S)&&!r.isPreloading(S)&&!s.current.includes(S)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${S}".
54
56
  This may be caused by complicated image action behavior that cannot be predicted.
55
- To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(b)),r.get(b)||b}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:g,applyTransition:y,applyTransform:f,updateStyleSync:h,flush:A,deps:m}=Vt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:b=>{if(c)return(b?b.task.resolve:[null]).map(E=>E&&typeof E=="function"?{style:Iu}:{style:Du(o.state.darkness)});let S=b?b.transition._getCurrentSrc():Lu(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:k.isColor(S)?k.colorToString(S):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:k.isImageSrc(S)?k.srcToURL(S):R.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:b=>b.src?{...b,src:l(b.src)}:b});ft(o,{createWearable:b=>{i(S=>[...S,b])},disposeWearable:b=>{i(S=>S.filter(C=>C.getId()!==b.getId()))},initDisplayable:g,applyTransform:f,applyTransition:y,events:t,updateStyleSync:h,flush:A},[...m]);let v=Va((b,S)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${b}px`,height:`${S}px`}))},[t]),x=Va(()=>{t.emit("event:image.onLoad")},[t]);return bt.createElement(Pu.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},bt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([b,S],C)=>{let E=p?p.task.resolve[C]:null;if(E&&typeof E=="function")return bt.createElement(To,{key:S,ref:b,autoFit:o.config.autoFit});let O=E?E.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return bt.createElement(Ua,{key:S,ref:b,src:O||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:C===0?v:void 0,onLoad:C===0?x:void 0})}):d.map(([b,S],C)=>bt.createElement(To,{key:S,ref:b,autoFit:o.config.autoFit,onSizeChanged:C===0?v:void 0,onLoad:C===0?x:void 0})),bt.createElement("div",{className:Ha("w-full h-full top-0 left-0 absolute")},n.map(b=>bt.createElement("div",{className:Ha("w-full h-full relative"),key:"wearable-"+b.getId()},bt.createElement(Oa,{image:b,state:e}))))))}var Oa=bt.memo(Ru),Ka=Oa;import xo,{useEffect as Wa,useMemo as Fu,useRef as Mr}from"react";var Mu=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,Nu=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function Ba(o,e){if(typeof e!="string"||!e.length)return o;if(Mu.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=Gu(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+Vu(r+e.replace(/\\/g,"/"))}function Gu(o){let e=Nu.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function Vu(o){let e=o.split("/"),t=[];for(let n=0;n<e.length;n++){let i=e[n];if(!(i==="."||i===""&&n!==e.length-1)){if(i===".."){t.pop();continue}t.push(i)}}return t.join("/")}var Ao=class{constructor(){this.backends=new Map;this.reportedMissing=new Set}register(e){if(!e||typeof e.name!="string"||!e.name.length)throw new Error("A puppet backend must have a non-empty name.");if(typeof e.mount!="function")throw new Error(`Puppet backend "${e.name}" must implement mount().`);return this.backends.set(e.name,e),this.reportedMissing.delete(e.name),this}get(e){return this.backends.get(e)||null}has(e){return this.backends.has(e)}list(){return Array.from(this.backends.keys())}unregister(e){return this.backends.delete(e)}reportMissing(e,t){return this.reportedMissing.has(e)?!1:(this.reportedMissing.add(e),t(`No puppet backend is registered under "${e}". The element keeps its place on the stage, its transform and its saved state, but draws nothing. Register one with game.registerPuppetBackend({name, mount}) before the game mounts.`),!0)}};function Nr({state:o,puppet:e}){let[t]=re(),{cacheManager:n}=Nt(),i=Mr(null),r=Fu(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=Mr(r);s.current=r;let{transformRef:a,transitionRefs:c,initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,deps:g}=Vt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipImageTransform,skipTransition:o.game.config.allowSkipImageTransition,transitionsProps:[{style:{position:"relative",width:`${r.width}px`,height:`${r.height}px`}}]});ft(e,{initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,flush:t},[...g]),Wa(()=>{let h=i.current;if(!h)return;let A=o.game,m=e.config.backend,v=A.getPuppetBackend(m);if(!v)return e._setStatus("missing-backend"),A.getPuppetBackendRegistry().reportMissing(m,S=>{o.logger.warn("Puppet",S)}),()=>{e._setStatus("unmounted")};let x;try{x=v.mount(h,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:f,resolveSibling:S=>f(Ba(e.config.src,S)),warn:(S,C)=>{o.logger.warn("Puppet",S,C)}})}catch(S){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${m}" threw while mounting "${e.config.src}"`,S),()=>{e._setStatus("unmounted")}}let b=!1;return e._attachInstance(x),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!b&&typeof x.ready=="function"?x.ready():void 0).then(()=>{b||e._setStatus("ready")}).catch(S=>{b||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${m}" failed to load "${e.config.src}"`,S))}),()=>{b=!0,e._attachInstance(null),e._setStatus("unmounted");try{x.dispose()}catch(S){o.logger.error("Puppet",`Backend "${m}" threw while disposing`,S)}}},[]);let y=Mr(r);Wa(()=>{let h=y.current;if(h.width===r.width&&h.height===r.height)return;y.current=r;let A=e._getInstance();if(!(!A||typeof A.resize!="function"))try{A.resize(r)}catch(m){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,m)}},[r]);function f(h){return k.isDataURI(h)?h:n.get(h)||h}return xo.createElement(Mt.Div,{"data-element-type":"puppet"},xo.createElement(Mt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([h,A])=>xo.createElement("div",{key:A,ref:h,className:e.config.className},xo.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function Gr({state:o,displayable:e}){return ri.createElement(ri.Fragment,null,e.map(t=>{if(t instanceof ln)return ri.createElement(Ir,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof R)return ri.createElement(Ka,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof vt)return ri.createElement(Nr,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Co,{useEffect as Hu}from"react";import{motion as Uu}from"motion/react";function za({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=Vt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return ft(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Hu(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Co.createElement(Co.Fragment,null,Co.createElement(Uu.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([u,d])=>Co.createElement("div",{className:"relative w-full h-full",ref:u,key:d},t))))}async function $a(o,e,t,n){let i=e.state.backgroundMusic,r=i&&o.audioManager.isManaged(i)?o.audioManager.stop(i,n):null;if(r&&t===i&&await r,t)try{await o.audioManager.playSoundToken(t,{end:t.state.volume,duration:n}),e.state.backgroundMusic=t}catch{e.state.backgroundMusic=null}else e.state.backgroundMusic=null;r&&await r}import Ou from"clsx";import{useEffect as ja}from"react";import Vr from"react";function Fr({state:o,className:e,elements:t}){let{scene:n,layers:i}=t;return ja(()=>n.events.depends([n.events.on(ut.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),ja(()=>(n.events.emit(ut.EventTypes["event:scene.mount"]),o.events.emit(I.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(ut.EventTypes["event:scene.unmount"]),o.events.emit(I.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),ft(n,{setBackgroundMusic(r,s){return $a(o,n,r,s)}}),Vr.createElement("div",{className:Ou(e,"w-full h-full absolute")},[...i.entries()].sort(([r],[s])=>r.state.zIndex-s.state.zIndex).map(([r,s])=>Vr.createElement(za,{state:o,layer:r,key:r.getId()},Vr.createElement(Gr,{state:o,displayable:s}))))}import{AnimatePresence as zu}from"motion/react";import{useEffect as $u,useReducer as ju,useRef as si}from"react";import Ku from"clsx";import Ft,{useCallback as Hr,useMemo as Bu,useRef as Wu}from"react";function Ur({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=M(),a=Wu([]),c=Hr(y=>(a.current.push(y),a.current.indexOf(y)),[]),l=Hr(y=>{let f=a.current.indexOf(y);f!==-1&&a.current.splice(f,1)},[]),u=Hr(y=>a.current.indexOf(y),[]),d=s.config.menu,p=Bu(()=>e.map(y=>({...y,words:y.prompt.evaluate(Ce.getCtx({gameState:n}))})),[]);function g(y){t(y)}return Ft.createElement(Ft.Fragment,null,Ft.createElement(ar,{value:{evaluated:p,choose:g,gameState:n}},Ft.createElement(lr,{value:{register:c,unregister:l,getIndex:u}},Ft.createElement(Rt,{className:"absolute"},r&&o&&Ft.createElement(_n,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),Ft.createElement(Mt.Div,{color:"green",border:"dashed",className:Ku("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},Ft.createElement(d,{items:p.map((y,f)=>f)})))))}function qa({items:o}){return Ft.createElement(Zi,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>Ft.createElement(co,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import qu from"clsx";import ai from"react";var Qu=120;function Or({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=si(!1),a=si({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),c=si([]),l=si(null),u=si(null),[,d]=ju(f=>f+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},g=()=>{let f=l.current;if(!f)return;let h=a.current;f.forEach(({slot:A,presenceKey:m})=>{h.slotKeys.get(A)===m&&h.slotKeys.delete(A),h.exitingKeys.add(m)}),l.current=null,u.current=null,c.current=[],d()};$u(()=>()=>{p()},[]);let y=(()=>{let f=a.current,h=i.length>0?i.map(({action:v,onClick:x},b)=>({action:v,slot:b,useTypeEffect:!s.current,onFinished:S=>{S!==void 0&&(s.current=S),x(),o.events.emit(I.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((v,x)=>{if(!v.action.prompt||!v.action.words)return[];let b=f.menuPromptIds.get(v);return b||(b=`menu-prompt-${n.getId()}-${f.nextKey++}`,f.menuPromptIds.set(v,b)),[{action:{sentence:v.action.prompt,words:v.action.words,character:null,id:b},slot:x,useTypeEffect:!1}]});if(h.length===0)return!l.current&&c.current.length>0&&(l.current=c.current.map(v=>({...v,active:!1}))),l.current&&!u.current&&(u.current=setTimeout(g,Qu)),l.current??[];p(),l.current=null;let A=new Set(h.map(({slot:v})=>v));for(let[v,x]of Array.from(f.slotKeys))A.has(v)||(f.exitingKeys.add(x),f.slotKeys.delete(v));let m=h.map(({slot:v,...x})=>{let b=f.slotKeys.get(v);return(!b||f.exitingKeys.has(b))&&(b=`say-${n.getId()}-${f.nextKey++}`,f.slotKeys.set(v,b)),{...x,presenceKey:b,slot:v,active:!0}});return c.current=m,m})();return ai.createElement("div",{className:qu(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs"},ai.createElement(zu,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},y.map(({action:f,onFinished:h,presenceKey:A,active:m,useTypeEffect:v})=>ai.createElement(_n,{gameState:o,key:A,action:f,active:m,onFinished:h,useTypeEffect:v}))),r.map(({action:f,onClick:h},A)=>ai.createElement("div",{key:"menu-"+A,"data-element-type":"menu"},ai.createElement(Ur,{state:o,prompt:f.prompt,choices:f.choices,renderPrompt:!f.prompt,afterChoose:m=>{s.current=!1,h(m),o.stage.next()},words:f.words}))))}import Qa,{useEffect as Xu}from"react";import{motion as Ju}from"motion/react";function Xa({state:o,camera:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=Vt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return ft(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Xu(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),Qa.createElement(Ju.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"camera"},i.map(([u,d])=>Qa.createElement("div",{className:"relative w-full h-full",ref:u,key:d},t)))}import Yu from"react";import{useEffect as Kr,useRef as Zu}from"react";import{useCallback as Ja}from"react";function Ya(o){let e=Ja(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=Ja(()=>{if(!o.current)return;let n=o.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[o]);return{show:e,hide:t}}function Br({gameState:o,video:e}){let t=Zu(null),{show:n,hide:i}=Ya(t);Kr(()=>o.events.depends([o.events.on(I.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),Kr(()=>{i(),e.state.display&&n()},[]),Kr(()=>{if(!t.current)return;let s=t.current,a=!1,c=new Set,l=()=>new L(`Failed to add event listener, ref is not available
56
- at Video.tsx: useEffect`),u=g=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw l();n()},hide:()=>{if(!t.current)throw l();i()},play:()=>{if(!t.current)throw l();let y=t.current;return g||y.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(y.currentTime=0,new Promise(f=>{let h=!1,A=null,m=[],v=()=>{h||(h=!0,c.delete(v),A&&A(),m.forEach(x=>x()),f())};c.add(v),A=o.schedule(({retry:x})=>{if(h)return;if(y.readyState<3){let E=()=>{y.removeEventListener("loadeddata",E),x()};y.addEventListener("loadeddata",E),m.push(()=>y.removeEventListener("loadeddata",E));return}let b=()=>v(),S=()=>v(),C=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),v()};y.addEventListener("ended",b),y.addEventListener("stopped",S),y.addEventListener("error",C),m.push(()=>{y.removeEventListener("ended",b),y.removeEventListener("stopped",S),y.removeEventListener("error",C)}),y.play().catch(E=>{o.logger.error("Failed to play video: "+E),v()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(y=>{o.logger.error("Failed to resume video: "+y)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:y=>{if(!t.current)throw l();t.current.currentTime=y}}))},d=()=>u(!1),p=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(s.error?` (media error code ${s.error.code})`:"")),u(!0)};return s.addEventListener("canplay",d),s.addEventListener("error",p),s.readyState>=3?u(!1):s.error&&p(),()=>{s.removeEventListener("canplay",d),s.removeEventListener("error",p),c.forEach(g=>g()),s.currentTime>0&&s.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function r(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return Yu.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:s=>s.preventDefault()})}import _u,{useEffect as ep,useRef as tp}from"react";var Za={linear:"linear",easeIn:"cubic-bezier(0.42, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.58, 1)",easeInOut:"cubic-bezier(0.42, 0, 0.58, 1)"};function np(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&Za[e]?Za[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function Wr({gameState:o,vfx:e}){let t=tp(null);return ep(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,c=new Set,l=new Set,u=[],d=x=>{n.style.transition="",n.style.opacity=String(x)},p=()=>{n.play().catch(x=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+x)})},g=()=>i||n.error?(o.logger.error("NarraLeaf-React: Vfx","Cannot wait for a vfx whose source failed to load: "+e.config.src),Promise.resolve()):n.readyState>=2?Promise.resolve():new Promise(x=>{let b=!1,S=()=>E(),C=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),E()},E=()=>{b||(b=!0,l.delete(E),n.removeEventListener("loadeddata",S),n.removeEventListener("error",C),x())};l.add(E),n.addEventListener("loadeddata",S),n.addEventListener("error",C),(n.readyState>=2||n.error)&&E()}),y=(x,b,S)=>{let C=b?.duration??0,E=++s;return S.instant||C<=0?(d(x),Promise.resolve()):new Promise(O=>{let _=!1,se=null,ze=()=>{_||(_=!0,l.delete(ze),se!==null&&clearTimeout(se),s===E&&t.current&&d(x),O())};l.add(ze),n.style.transition=`opacity ${C}ms ${np(o,b?.easing)}`,n.offsetWidth,n.style.opacity=String(x),se=setTimeout(ze,C)})},f=x=>{r||(r=!0,i=x,o.mountState(e,{show:async b=>{a=!0;let S={instant:!1};c.add(S);try{if(await g(),!t.current)return;e.state.paused||p(),await y(e.config.opacity,b,S)}finally{c.delete(S)}},hide:async b=>{a=!0;let S={instant:!1};c.add(S);try{await y(0,b,S),t.current&&n.pause()}finally{c.delete(S)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:b=>{n.playbackRate=b}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},h=()=>f(!1),A=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(n.error?` (media error code ${n.error.code})`:"")),f(!0)},m=o.events.on(I.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(x=>{x.instant=!0}),[...l].forEach(x=>x()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),v=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&p()};return document.addEventListener("visibilitychange",v),n.style.opacity="0",n.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&p(),n.addEventListener("canplay",h),n.addEventListener("error",A),n.readyState>=3?f(!1):n.error&&A(),()=>{n.removeEventListener("canplay",h),n.removeEventListener("error",A),document.removeEventListener("visibilitychange",v),m.cancel(),u.forEach(x=>x()),[...l].forEach(x=>x()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),_u.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,loop:e.config.loop,playsInline:!0,onContextMenu:n=>n.preventDefault(),style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:e.config.fit,mixBlendMode:e.config.blendMode,pointerEvents:"none"}})}import ip from"clsx";import op,{useCallback as rp,useEffect as wo,useRef as sp}from"react";function zr({children:o,className:e,gameState:t}){let{ratio:n}=Te(),i=M(),[r]=re(),s=sp(null),a=i.config.minWidth,c=i.config.minHeight,l=rp(u=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(u.width,u.height,u.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return wo(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),wo(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),wo(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),wo(()=>t.events.on(I.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),op.createElement(ba,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:ip(e),onUpdate:l},o)}import _a,{useEffect as ap,useRef as cp,useState as ec}from"react";function $r({src:o,width:e,height:t}){let[n,i]=ec({x:0,y:0}),[r,s]=ec(!1),a=cp(null),{ratio:c}=Te();return ap(()=>{let l=u=>{if(a.current){let d=a.current.getBoundingClientRect(),p=u.clientX-d.left,g=u.clientY-d.top;i({x:p,y:g}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),_a.createElement(Rt,{ref:a,className:"overflow-hidden absolute"},_a.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import tc from"react";import zt from"react";function jr({error:o,errorInfo:e}){return M().config.app.debug?zt.createElement("div",{className:"text-left"},zt.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),zt.createElement("p",{className:"text-red-700"},"Message: ",o.message),zt.createElement("pre",null,"Error Stack: ",o?.stack),zt.createElement("pre",null,"Component Stack: ",e?.componentStack),zt.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):zt.createElement("div",{className:"bg-white w-full h-full"},zt.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),zt.createElement("p",null,"Please contact the game developer for further assistance."))}var ko=class extends tc.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?tc.createElement(jr,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import oc from"clsx";import U,{useEffect as Ht,useReducer as rc,useState as Rn}from"react";import{flushSync as sc}from"react-dom";import{useRef as lp}from"react";import{useEffect as up}from"react";function nc({gameState:o}){let e=lp(null);return up(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(I.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import ci,{useEffect as pp}from"react";function qr({gameState:o}){let[e]=re(),{ratio:t}=Te(),n=o.notificationMgr;pp(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return ci.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},ci.createElement(i,{notifications:n.toArray()}))}function ic({notifications:o}){return ci.createElement(uo,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>ci.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},ci.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function ac({story:o=Qn.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:d=!0}){let[p,g]=rc(P=>P+1,0),[y,f]=rc(P=>P+1,0),[h,A]=Rn(0),m=M(),[v]=Rn(()=>new I(m,{update:g,forceUpdate:()=>{v.logger.weakWarn("Player","force update"),sc(()=>{g()})},forceRemount:()=>{v.logger.weakWarn("Player","force remount"),sc(()=>{A(P=>P+1),g()})},next:ve})),x=U.createRef(),b=U.createRef(),[S,C]=Rn(!1),E=U.useRef(!1),O=U.useRef(null),_=U.useRef(null),{preloaded:se}=Nt(),[ze,dt]=Rn(!1),et=U.useRef(!1),[be,K]=Rn(!1),le=U.useRef(!1),oe=U.useRef(null),ue=U.useRef(!1),[F]=Rn(new Map);function me(P){return{game:m,gameState:v,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable(),scene:P}}function ve(){let P=()=>{F.forEach(D=>D.cancel())};if(v.rollLock.isLocked())return;P();let V=!1,fe=0;for(;!V;){if(fe++>m.config.maxStackModelLoop)throw new L("Max stack model loop reached");let D=m.getLiveGame().next();if(!D){if(m.getLiveGame().stackModel&&!m.getLiveGame().stackModel.isEmpty())continue;break}if(T.isAwaitable(D)){if(O.current===D)break;O.current=D,D.onSettled(()=>{D.isFailed()||(O.current===D&&(O.current=null),ve())}),D.onFailed(he=>{O.current===D&&(O.current=null),v.logger.error("Player",he)}),V=!0;break}if(D instanceof gn){if(_.current===D)break;_.current=D,D.nextUnlock().then(()=>{_.current===D&&(_.current=null),ve()}),V=!0;break}if(je.isCalledActionResult(D)&&D.wait&&je.isStackModelsAwaiting(D.wait.type,D.wait.stackModels)){if(O.current===D)break;if(O.current=D,D.wait){let he=je.executeStackModelGroup(D.wait.type,D.wait.stackModels);he.then(()=>{O.current===D&&(O.current=null),ve()}),he.onFailed(Ot=>{O.current===D&&(O.current=null),v.logger.error("Player",Ot)})}V=!0;break}v.handle(D)}v.stage.update()}Ht(()=>{v.audioManager.initialize()},[]),Ht(()=>(m.getLiveGame().setGameState(v),o&&!m.getLiveGame().isPlaying()&&m.getLiveGame().loadStory(o),o?.entryScene&&!v.getPreloadingScene()&&!v.getLastScene()&&v.preloadScene(o.entryScene),v.playerCurrent=x.current,v.mainContentNode=b.current,()=>{m.getLiveGame().setGameState(void 0),v.playerCurrent=null}),[m,o]),Ht(()=>nt(()=>{C(!0);let P=v.getLastScene(),V=[];P?V.push(P.events.once("event:scene.mount",()=>{v.stage.next()}).cancel):v.stage.next();let fe=v.events.on(I.EventTypes["event:state.end"],()=>{c&&c({game:m,gameState:v,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()})});return v.stage.update(),()=>{P&&V.forEach(D=>D()),fe.cancel()}}),[]),Ht(()=>nt(()=>{S&&i&&!E.current&&(E.current=!0,v.stage.forceUpdate(),m.hooks.trigger("init",[]),i({game:m,gameState:v,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()}))}),[S]),Ht(()=>nt(()=>{if(ze&&s&&!et.current){et.current=!0;let P=oe.current||v.getLastScene()||v.getPreloadingScene(),V=me(P);s(V)}}),[ze]),Ht(()=>nt(()=>{if(be&&!le.current){le.current=!0;let P=oe.current||v.getLastScene()||v.getPreloadingScene(),V=me(P);m.markPreloadComplete(V)&&r&&r(V)}}),[be]),Ht(()=>v.events.on(I.EventTypes["event:state.scene.mount"],P=>{oe.current||(oe.current=P,f())}).cancel,[]),Ht(()=>{if(!be||!d||ue.current||m.isFirstSceneReady())return;let P=oe.current||v.getLastScene();if(!P)return;let V=null,fe=null,D=!1;ue.current=!0;let he=()=>{D=!0,ue.current=!1;let Ot=me(P);m.markFirstSceneReady(Ot)&&a&&a(Ot)};return typeof requestAnimationFrame=="function"?V=requestAnimationFrame(()=>{fe=setTimeout(he,0)}):fe=setTimeout(he,0),()=>{D||(ue.current=!1,V!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(V),fe!==null&&clearTimeout(fe))}},[d,y,p,be]),Ht(()=>se.events.depends([se.events.on(Be.EventTypes["event:preloaded.ready"],()=>{dt(!0),v.stage.update(),o&&m.getLiveGame().isPlaying()&&ve()}),se.events.on(Be.EventTypes["event:preloaded.complete"],()=>{K(!0)})]).cancel,[]),Ht(()=>{v.flushDep=p},[p]);let pe=e||m.config.width,Qe=t||m.config.height;return U.createElement(ko,{onError:l},U.createElement("div",{style:{width:typeof pe=="number"?`${pe}px`:pe,height:typeof Qe=="number"?`${Qe}px`:Qe},className:oc(n,"__narraleaf_content-player"),ref:x,tabIndex:0},U.createElement(zr,{className:oc("flex-grow overflow-auto"),gameState:v},U.createElement(wr,{gameState:v}),U.createElement(nc,{gameState:v}),U.createElement(Rt,{className:"absolute",ref:b,style:{cursor:v.game.config.cursor?"none":"auto",overflow:v.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},m.config.cursor&&U.createElement($r,{src:m.config.cursor,width:m.config.cursorWidth,height:m.config.cursorHeight}),U.createElement(dp,{show:ze&&d,key:h},U.createElement(Tr,null,U.createElement(Pa,{state:v}),U.createElement(Ia,{state:v}),U.createElement(mp,{state:v},v.getSceneElements().map(P=>U.createElement(Fr,{key:"scene-"+P.scene.getId(),state:v,elements:P})),v.getVideos().map((P,V)=>U.createElement("div",{className:"w-full h-full absolute",key:"video-"+V,"data-element-type":"video"},U.createElement(Br,{gameState:v,video:P}))),v.getVfx().map(P=>U.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+P.getId(),"data-element-type":"vfx",style:{zIndex:P.config.zIndex}},U.createElement(Wr,{gameState:v,vfx:P})))),v.getSceneElements().map(P=>U.createElement(Or,{key:"scene-dialogs-"+P.scene.getId(),state:v,elements:P})),U.createElement(fp,{NvlComponent:m.config.nvlDialog}))),U.createElement(Na,{state:v}),U.createElement(ha,null,u),U.createElement(qr,{gameState:v})))))}function dp({children:o,show:e}){return U.createElement(U.Fragment,null,e?o:null)}function mp({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?U.createElement(Xa,{state:o,camera:t},e):U.createElement(U.Fragment,null,e)}function fp({NvlComponent:o}){let{dialogs:e,state:t}=Gt(),i=M().getLiveGame().getGameState(),r=U.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Ce.getCtx({gameState:i})),l=t.activeDialogId===s.id,u=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return U.createElement(o,{dialogs:r})}import"client-only";import Mn from"react";function cc({children:o,game:e}){return Mn.createElement(Mn.Fragment,null,Mn.createElement(qs,null,Mn.createElement(Bs,{game:e},Mn.createElement(pa,null,Mn.createElement(js,null,o)))))}var hp=(c=>(c.image="narraleaf:image",c.text="narraleaf:text",c.layer="narraleaf:layer",c.scene="narraleaf:scene",c.video="narraleaf:video",c.vfx="narraleaf:vfx",c.camera="narraleaf:camera",c.puppet="narraleaf:puppet",c))(hp||{});import gp from"clsx";import Ut,{useEffect as lc,useRef as yp}from"react";import{motion as vp,useIsPresent as Sp}from"motion/react";var Tp={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function bp({children:o,initial:e,transition:t,...n}){let i=M(),r=St(),{ratio:s}=Te(),[a]=on(ie.Preferences.showDialog),c=yp(null),[l]=mn("nextAction"),u=Sp();function d(){r.requestComplete()}return lc(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
57
- at Say.tsx: onElementClick`);return}let p=y=>{y.repeat||i.keyMap.match("nextAction",y.key)&&r.requestComplete()};window.addEventListener("keydown",p);let g=r.events.on(Le.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",p),g.cancel()}},[r,l]),lc(()=>{let p=i.preference.onPreferenceChange(ie.Preferences.autoForward,g=>{g&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{p.cancel()}},[r]),Ut.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},Ut.createElement("div",{className:gp("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:d,style:{...wi(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:c},Ut.createElement(vp.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)))}function uc({children:o,...e}){let t=St();return!t.config.action.sentence||!t.config.action.words?null:Ut.createElement(bp,{...e},o)}var gu=uc;function pc(){return Ut.createElement(uc,null,Ut.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},Ut.createElement(dr,null),Ut.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},Ut.createElement(Wt,null),Ut.createElement(rn,{...Tp}))))}var li={say:pc,menu:qa,notification:ic,nvlDialog:xr};var Po=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var ui=class{constructor(e={}){this.keyMap=e;this.events=new q}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],i=r=>Array.isArray(r)?r:[r];Array.isArray(n)?this.setKeyBinding(e,[...n,...i(t)]):this.setKeyBinding(e,[n,...i(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,i)=>{n===e&&t(i)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(i=>i.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var dc=(e=>(e.game="game",e))(dc||{}),qe=class qe{constructor(e){this.hooks=new bi;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new Yn(qe.DefaultPreference);this.audioBuses=new Kn(()=>this.config.audioBuses??[],Ps(this.preference));this.keyMap=new ui({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new q;this.puppetBackends=new Ao;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=z(qe.DefaultConfig,e),this.plugins=new Po(this),this.router=new nn(this)}configure(e){let[t,n]=gs(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=z(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(I.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}registerPuppetBackend(e){return this.puppetBackends.register(e),this}getPuppetBackend(e){return this.puppetBackends.get(e)}listPuppetBackends(){return this.puppetBackends.list()}getPuppetBackendRegistry(){return this.puppetBackends}onPreloadComplete(e){return this.lifecycleEvents.on(qe.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(qe.LifecycleEventTypes["event:game.preloadComplete"],e)}whenPreloadComplete(){return this.preloadCompleteContext?Promise.resolve(this.preloadCompleteContext):new Promise(e=>{this.oncePreloadComplete(e)})}isPreloadComplete(){return this.preloadCompleteContext!==null}onFirstSceneReady(e){return this.lifecycleEvents.on(qe.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(qe.LifecycleEventTypes["event:game.firstSceneReady"],e)}whenFirstSceneReady(){return this.firstSceneReadyContext?Promise.resolve(this.firstSceneReadyContext):new Promise(e=>{this.onceFirstSceneReady(e)})}isFirstSceneReady(){return this.firstSceneReadyContext!==null}markPreloadComplete(e){return this.preloadCompleteContext?!1:(this.preloadCompleteContext=e,this.lifecycleEvents.emit(qe.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(qe.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.audioBuses.dispose(),this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Pt(this)}};qe.defaultSettings={volume:1},qe.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:0,skipInterval:100},qe.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",voiceFadeDuration:"voiceFadeDuration",voiceEndMode:"voiceEndMode",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},qe.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:li.notification,menu:li.menu,dialog:li.say,nvlDialog:li.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100,audioBuses:[]},qe.GameSettingsNamespace=dc,qe.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var ie=qe;var Eo=class Eo extends ${constructor(){super(...arguments);this._jumpTarget=null}setJumpTarget(t){return this._jumpTarget=t,this}getJumpTarget(){return this._jumpTarget}static executeActionsAsync(t,n){let i=t.game.getLiveGame().requestAsyncStackModel([{type:n.type,node:n.contentNode}]);return t.game.getLiveGame().executeAsyncStackModel(i)}checkActionChain(t){if(t.some(n=>!!n.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return t}executeAction(t,n){let i=this.contentNode,[r]=i.getContent();if(this.type===ee.do)return r.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:r[0].contentNode}];if(this.type===ee.doAsync){if(r.length===0)return super.executeAction(t,n);let s=Eo.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===ee.any){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:s}}}else if(this.type===ee.all){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:s}}}else if(this.type===ee.allAsync){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().requestAsyncStackModel([{type:a.type,node:a.contentNode}]));return t.timelines.attachTimeline(T.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===ee.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=je.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ee.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let c=je.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ee.break){if(!n.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return n.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===ee.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=T.delay(s):T.isAwaitable(s)?a=s:a=T.fromPromise(s);let c=new T,l=new Ie(a);return t.timelines.attachTimeline(l),a.then(()=>{c.resolve({type:this.type,node:this.contentNode.getChild()})}),c.onSkipControllerRegister(u=>{u.onAbort(()=>{l.abort()})}),c}else if(this.type===ee.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new T,a=new T,c=new Ie(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(ie.Preferences.autoForward),d=l.getPreference(ie.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,g=!1,y=null,f=null,h=null,A=()=>{f?.cancel(),h?.cancel(),y&&(clearTimeout(y),y=null)},m=()=>{g||(g=!0,A(),a.resolve())};return f=t.events.on(I.EventTypes["event:state.player.stageClick"],m),h=t.events.on(I.EventTypes["event:state.player.skip"],m),p!==null&&(y=setTimeout(m,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(v=>{v.onAbort(()=>{g||(g=!0,A(),c.abort())})}),s}else{if(this.type===ee.label)return super.executeAction(t,n);if(this.type===ee.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Ge(`Jump target label "${l}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),c=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(l,u)},[c]),a.clearMainStack().getStackModelForce().push({type:this.type,node:s.contentNode}),null}}throw new Error("Unknown control action type: "+this.type)}getFutureActions(t,n){if(this.callee.config.allowFutureScene===!1&&n.allowFutureScene===!1)return[...super.getFutureActions(t,n)];if(this.type===ee.break||this.type===ee.waitForClick||this.type===ee.label||this.type===ee.jump)return super.getFutureActions(t,n);let i=this.contentNode.getContent()[0],r=super.getFutureActions(t,n);return[...i??[],...r]}stringify(t,n,i){if(this.type===ee.break)return super.stringifyWithContent("Control","break");if(this.type===ee.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===ee.label||this.type===ee.jump){let[a]=this.contentNode.getContent(),c=this.type===ee.label?"label":"jump";return super.stringifyWithContent("Control",`${c}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};Eo.ActionTypes=ee;var ne=Eo;var Ue=class o extends ae{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static whileLoop(t,n){return new o().whileLoop(t,n)}static breakLoop(){return new o().breakLoop()}static sleep(t){return new o().sleep(t)}static waitForClick(){return new o().waitForClick()}static label(t){return new o().label(t)}static jump(t){return new o().jump(t)}do(t){return this.push(ne.ActionTypes.do,t)}doAsync(t){return this.push(ne.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(ne.ActionTypes.any,t)}all(t){return this.pushUnchained(ne.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(ne.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(ne.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=j.from(t);return this.pushWithLambda(ne.ActionTypes.while,n,i)}breakLoop(){let t=new ne(this.chain(),ne.ActionTypes.break,new w().setContent([]));return this.chain(t)}sleep(t){return this.push(ne.ActionTypes.sleep,[],t)}waitForClick(){let t=new ne(this.chain(),ne.ActionTypes.waitForClick,new w().setContent([]));return this.chain(t)}label(t){let n=new ne(this.chain(),ne.ActionTypes.label,new w().setContent([t]));return this.chain(n)}jump(t){let n=new ne(this.chain(),ne.ActionTypes.jump,new w().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new ne(this.chain(),t,new w().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new ne(this.chain(),t,new w().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new ne(this.chain(),t,new w().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Kt.say(n).getActions():Ve.toActions([n]))}};var W=class W extends rt{static get DefaultUserConfig(){return W._defaultUserConfig??(W._defaultUserConfig=new B({name:"(anonymous)",autoInit:!0,src:W.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...Q.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return k.isStaticImageData(t)?k.srcToURL(t):k.isColor(t)?t:k.isImageSrc(t)?k.srcToURL(t):W.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isLayeredSrc(e){return!!e.config.src?.slots}static isSrcDefinitionObject(e){return typeof e=="object"&&e!==null&&!k.isImageSrc(e)&&!k.isColor(e)}static isLayeredDefinition(e){return this.isSrcDefinitionObject(e)&&"layers"in e}static isTagDefinition(e){return this.isSrcDefinitionObject(e)&&"resolve"in e}static isLayerVariants(e){return typeof e=="object"&&e!==null}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(k.isImageSrc(t)||k.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:W.isLayeredSrc(e)?null:W.isTagSrc(e)&&e.config.src.resolve?W.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):W.isStaticSrc(e)?k.isStaticImageData(e.state.currentSrc)?k.srcToURL(e.state.currentSrc):k.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static getSrcURLs(e,t){let n=e.config.src?.slots;if(!n)return[];let i=new Set(t??e.state.currentSrc);return n.map(r=>W.resolveLayerSlot(r,i))}static resolveLayerSlot(e,t){if(e===null||typeof e=="string")return e;if(typeof e=="function")return e(t);for(let[n,i]of Object.entries(e))if(t.has(n))return i;return null}static getAllLayerSrc(e){let t=e.config.src?.slots;if(!t)return[];let n=[];for(let i of t)if(typeof i=="string")n.push(i);else if(W.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new W({src:e})}constructor(e={}){super();let t=W.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new Ue,n=>{if(k.isImageSrc(e)||k.isColor(e)){if(k.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new ge(n,ge.ActionTypes.setAppearance,new w().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Ue,i=>i.chain(this._setDarkness(i,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new te("Cannot add self as a wearable");this.config.wearables.push(n),Object.assign(n.config,{isWearable:!0})}return this}wear(e){return this.addWearable(e)}bindWearable(e){return e.addWearable([this])}asWearableOf(e){return this.bindWearable(e)}useLayer(e){return this.userConfig.get().layer=e||void 0,Object.assign(this.config,{layer:e||void 0}),this}toData(){return{state:W.StateSerializer.serialize(this.state),transformState:Q.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=W.StateSerializer.deserialize(e.state),this.transformState=Q.deserialize(e.transformState),this}_applyTransition(e,t){return new De(this.chain(),ke.applyTransition,new w().setContent([e,t]))}_init(e,t){return new De(this.chain(),ke.init,new w().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new ge(this.chain(),ge.ActionTypes.initWearable,new w().setContent([e]))}_flush(){return new ge(this.chain(),ge.ActionTypes.flush,new w)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!W.isTagSrc(this))throw new Error(`Tag not defined
58
- Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(c=>{let l=n.get(c);l&&i.set(l,c)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let c=i.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(c)}),r}_setAppearanceSync(e){if(k.isImageSrc(e)||k.isColor(e)){if(k.isColor(e)&&!this.config.isBackground)throw new te("Color src is not allowed for non-background image");this.state.currentSrc=e;return}if(!W.isTagSrc(this))throw this._mixedSrcError();let t=this.state.currentSrc,n=this.resolveTags(t,e);this.state.currentSrc=n}_mixedSrcError(){throw new te(`Trying to mix src and tags
57
+ To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(S)),r.get(S)||S}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:g,applyTransition:h,applyTransform:m,updateStyleSync:y,flush:A,deps:f}=Ot({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:S=>{if(c)return(S?S.task.resolve:[null]).map(D=>D&&typeof D=="function"?{style:zu}:{style:Ku(o.state.darkness)});let b=S?S.transition._getCurrentSrc():Wu(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:k.isColor(b)?k.colorToString(b):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:k.isImageSrc(b)?k.srcToURL(b):L.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:S=>S.src?{...S,src:l(S.src)}:S});vt(o,{createWearable:S=>{i(b=>[...b,S])},disposeWearable:S=>{i(b=>b.filter(w=>w.getId()!==S.getId()))},initDisplayable:g,applyTransform:m,applyTransition:h,events:t,updateStyleSync:y,flush:A},[...f]);let v=ja((S,b)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${S}px`,height:`${b}px`}))},[t]),x=ja(()=>{t.emit("event:image.onLoad")},[t]);return wt.createElement(Ou.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},wt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([S,b],w)=>{let D=p?p.task.resolve[w]:null;if(D&&typeof D=="function")return wt.createElement(ko,{key:b,ref:S,autoFit:o.config.autoFit});let B=D?D.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return wt.createElement(Xa,{key:b,ref:S,src:B||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:w===0?v:void 0,onLoad:w===0?x:void 0})}):d.map(([S,b],w)=>wt.createElement(ko,{key:b,ref:S,autoFit:o.config.autoFit,onSizeChanged:w===0?v:void 0,onLoad:w===0?x:void 0})),wt.createElement("div",{className:Qa("w-full h-full top-0 left-0 absolute")},n.map(S=>wt.createElement("div",{className:Qa("w-full h-full relative"),key:"wearable-"+S.getId()},wt.createElement(Ya,{image:S,state:e}))))))}var Ya=wt.memo($u),Ja=Ya;import Do,{useEffect as _a,useMemo as Yu,useRef as Wr}from"react";var ju=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,qu=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function Za(o,e){if(typeof e!="string"||!e.length)return o;if(ju.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=Qu(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+Xu(r+e.replace(/\\/g,"/"))}function Qu(o){let e=qu.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function Xu(o){let e=o.split("/"),t=[];for(let n=0;n<e.length;n++){let i=e[n];if(!(i==="."||i===""&&n!==e.length-1)){if(i===".."){t.pop();continue}t.push(i)}}return t.join("/")}var Eo=class{constructor(){this.backends=new Map;this.reportedMissing=new Set}register(e){if(!e||typeof e.name!="string"||!e.name.length)throw new Error("A puppet backend must have a non-empty name.");if(typeof e.mount!="function")throw new Error(`Puppet backend "${e.name}" must implement mount().`);return this.backends.set(e.name,e),this.reportedMissing.delete(e.name),this}get(e){return this.backends.get(e)||null}has(e){return this.backends.has(e)}list(){return Array.from(this.backends.keys())}unregister(e){return this.backends.delete(e)}reportMissing(e,t){return this.reportedMissing.has(e)?!1:(this.reportedMissing.add(e),t(`No puppet backend is registered under "${e}". The element keeps its place on the stage, its transform and its saved state, but draws nothing. Register one with game.registerPuppetBackend({name, mount}) before the game mounts.`),!0)}};function zr({state:o,puppet:e}){let[t]=se(),{cacheManager:n}=Ft(),i=Wr(null),r=Yu(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=Wr(r);s.current=r;let{transformRef:a,transitionRefs:c,initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,deps:g}=Ot({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipImageTransform,skipTransition:o.game.config.allowSkipImageTransition,transitionsProps:[{style:{position:"relative",width:`${r.width}px`,height:`${r.height}px`}}]});vt(e,{initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,flush:t},[...g]),_a(()=>{let y=i.current;if(!y)return;let A=o.game,f=e.config.backend,v=A.getPuppetBackend(f);if(!v)return e._setStatus("missing-backend"),A.getPuppetBackendRegistry().reportMissing(f,b=>{o.logger.warn("Puppet",b)}),()=>{e._setStatus("unmounted")};let x;try{x=v.mount(y,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:m,resolveSibling:b=>m(Za(e.config.src,b)),warn:(b,w)=>{o.logger.warn("Puppet",b,w)}})}catch(b){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${f}" threw while mounting "${e.config.src}"`,b),()=>{e._setStatus("unmounted")}}let S=!1;return e._attachInstance(x),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!S&&typeof x.ready=="function"?x.ready():void 0).then(()=>{S||e._setStatus("ready")}).catch(b=>{S||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${f}" failed to load "${e.config.src}"`,b))}),()=>{S=!0,e._attachInstance(null),e._setStatus("unmounted");try{x.dispose()}catch(b){o.logger.error("Puppet",`Backend "${f}" threw while disposing`,b)}}},[]);let h=Wr(r);_a(()=>{let y=h.current;if(y.width===r.width&&y.height===r.height)return;h.current=r;let A=e._getInstance();if(!(!A||typeof A.resize!="function"))try{A.resize(r)}catch(f){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,f)}},[r]);function m(y){return k.isDataURI(y)?y:n.get(y)||y}return Do.createElement(Ht.Div,{"data-element-type":"puppet"},Do.createElement(Ht.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([y,A])=>Do.createElement("div",{key:A,ref:y,className:e.config.className},Do.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function $r({state:o,displayable:e}){return li.createElement(li.Fragment,null,e.map(t=>{if(t instanceof mn)return li.createElement(Br,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof L)return li.createElement(Ja,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof At)return li.createElement(zr,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Lo,{useEffect as Ju}from"react";import{motion as Zu}from"motion/react";function ec({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=Ot({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return vt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Ju(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Lo.createElement(Lo.Fragment,null,Lo.createElement(Zu.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([u,d])=>Lo.createElement("div",{className:"relative w-full h-full",ref:u,key:d},t))))}async function tc(o,e,t,n){let i=e.state.backgroundMusic,r=i&&o.audioManager.isManaged(i)?o.audioManager.stop(i,n):null;if(r&&t===i&&await r,t)try{await o.audioManager.playSoundToken(t,{end:t.state.volume,duration:n}),e.state.backgroundMusic=t}catch{e.state.backgroundMusic=null}else e.state.backgroundMusic=null;r&&await r}import _u from"clsx";import{useEffect as nc}from"react";import jr from"react";function qr({state:o,className:e,elements:t}){let{scene:n,layers:i}=t;return nc(()=>n.events.depends([n.events.on(mt.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),nc(()=>(n.events.emit(mt.EventTypes["event:scene.mount"]),o.events.emit(E.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(mt.EventTypes["event:scene.unmount"]),o.events.emit(E.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),vt(n,{setBackgroundMusic(r,s){return tc(o,n,r,s)}}),jr.createElement("div",{className:_u(e,"w-full h-full absolute")},[...i.entries()].sort(([r],[s])=>r.state.zIndex-s.state.zIndex).map(([r,s])=>jr.createElement(ec,{state:o,layer:r,key:r.getId()},jr.createElement($r,{state:o,displayable:s}))))}import{AnimatePresence as ip}from"motion/react";import{useEffect as op,useReducer as rp,useRef as ui}from"react";import ep from"clsx";import Bt,{useCallback as Qr,useMemo as tp,useRef as np}from"react";function Xr({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=I(),a=np([]),c=Qr(h=>(a.current.push(h),a.current.indexOf(h)),[]),l=Qr(h=>{let m=a.current.indexOf(h);m!==-1&&a.current.splice(m,1)},[]),u=Qr(h=>a.current.indexOf(h),[]),d=s.config.menu,p=tp(()=>e.map(h=>({...h,words:h.prompt.evaluate(Ce.getCtx({gameState:n}))})),[]);function g(h){t(h)}return Bt.createElement(Bt.Fragment,null,Bt.createElement(yr,{value:{evaluated:p,choose:g,gameState:n}},Bt.createElement(Sr,{value:{register:c,unregister:l,getIndex:u}},Bt.createElement(Vt,{className:"absolute"},r&&o&&Bt.createElement(ni,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),Bt.createElement(Ht.Div,{color:"green",border:"dashed",className:ep("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},Bt.createElement(d,{items:p.map((h,m)=>m)})))))}function ic({items:o}){return Bt.createElement(io,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>Bt.createElement(ho,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import sp from"clsx";import pi from"react";var ap=120;function Yr({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=ui(!1),a=ui({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),c=ui([]),l=ui(null),u=ui(null),[,d]=rp(m=>m+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},g=()=>{let m=l.current;if(!m)return;let y=a.current;m.forEach(({slot:A,presenceKey:f})=>{y.slotKeys.get(A)===f&&y.slotKeys.delete(A),y.exitingKeys.add(f)}),l.current=null,u.current=null,c.current=[],d()};op(()=>()=>{p()},[]);let h=(()=>{let m=a.current,y=i.length>0?i.map(({action:v,onClick:x},S)=>({action:v,slot:S,useTypeEffect:!s.current,onFinished:b=>{b!==void 0&&(s.current=b),x(),o.events.emit(E.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((v,x)=>{if(!v.action.prompt||!v.action.words)return[];let S=m.menuPromptIds.get(v);return S||(S=`menu-prompt-${n.getId()}-${m.nextKey++}`,m.menuPromptIds.set(v,S)),[{action:{sentence:v.action.prompt,words:v.action.words,character:null,id:S},slot:x,useTypeEffect:!1}]});if(y.length===0)return!l.current&&c.current.length>0&&(l.current=c.current.map(v=>({...v,active:!1}))),l.current&&!u.current&&(u.current=setTimeout(g,ap)),l.current??[];p(),l.current=null;let A=new Set(y.map(({slot:v})=>v));for(let[v,x]of Array.from(m.slotKeys))A.has(v)||(m.exitingKeys.add(x),m.slotKeys.delete(v));let f=y.map(({slot:v,...x})=>{let S=m.slotKeys.get(v);return(!S||m.exitingKeys.has(S))&&(S=`say-${n.getId()}-${m.nextKey++}`,m.slotKeys.set(v,S)),{...x,presenceKey:S,slot:v,active:!0}});return c.current=f,f})();return pi.createElement("div",{className:sp(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs"},pi.createElement(ip,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},h.map(({action:m,onFinished:y,presenceKey:A,active:f,useTypeEffect:v})=>pi.createElement(ni,{gameState:o,key:A,action:m,active:f,onFinished:y,useTypeEffect:v}))),r.map(({action:m,onClick:y},A)=>pi.createElement("div",{key:"menu-"+A,"data-element-type":"menu"},pi.createElement(Xr,{state:o,prompt:m.prompt,choices:m.choices,renderPrompt:!m.prompt,afterChoose:f=>{s.current=!1,y(f),o.stage.next()},words:m.words}))))}import oc,{useEffect as cp}from"react";import{motion as lp}from"motion/react";function rc({state:o,camera:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=Ot({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return vt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),cp(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),oc.createElement(lp.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"camera"},i.map(([u,d])=>oc.createElement("div",{className:"relative w-full h-full",ref:u,key:d},t)))}import up from"react";import{useEffect as Jr,useRef as pp}from"react";import{useCallback as sc}from"react";function ac(o){let e=sc(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=sc(()=>{if(!o.current)return;let n=o.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[o]);return{show:e,hide:t}}function Zr({gameState:o,video:e}){let t=pp(null),{show:n,hide:i}=ac(t);Jr(()=>o.events.depends([o.events.on(E.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),Jr(()=>{i(),e.state.display&&n()},[]),Jr(()=>{if(!t.current)return;let s=t.current,a=!1,c=new Set,l=()=>new P(`Failed to add event listener, ref is not available
58
+ at Video.tsx: useEffect`),u=g=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw l();n()},hide:()=>{if(!t.current)throw l();i()},play:()=>{if(!t.current)throw l();let h=t.current;return g||h.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(h.currentTime=0,new Promise(m=>{let y=!1,A=null,f=[],v=()=>{y||(y=!0,c.delete(v),A&&A(),f.forEach(x=>x()),m())};c.add(v),A=o.schedule(({retry:x})=>{if(y)return;if(h.readyState<3){let D=()=>{h.removeEventListener("loadeddata",D),x()};h.addEventListener("loadeddata",D),f.push(()=>h.removeEventListener("loadeddata",D));return}let S=()=>v(),b=()=>v(),w=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),v()};h.addEventListener("ended",S),h.addEventListener("stopped",b),h.addEventListener("error",w),f.push(()=>{h.removeEventListener("ended",S),h.removeEventListener("stopped",b),h.removeEventListener("error",w)}),h.play().catch(D=>{o.logger.error("Failed to play video: "+D),v()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(h=>{o.logger.error("Failed to resume video: "+h)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:h=>{if(!t.current)throw l();t.current.currentTime=h}}))},d=()=>u(!1),p=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(s.error?` (media error code ${s.error.code})`:"")),u(!0)};return s.addEventListener("canplay",d),s.addEventListener("error",p),s.readyState>=3?u(!1):s.error&&p(),()=>{s.removeEventListener("canplay",d),s.removeEventListener("error",p),c.forEach(g=>g()),s.currentTime>0&&s.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function r(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return up.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:s=>s.preventDefault()})}import dp,{useEffect as mp,useRef as fp}from"react";var cc={linear:"linear",easeIn:"cubic-bezier(0.42, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.58, 1)",easeInOut:"cubic-bezier(0.42, 0, 0.58, 1)"};function hp(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&cc[e]?cc[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function _r({gameState:o,vfx:e}){let t=fp(null);return mp(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,c=new Set,l=new Set,u=[],d=x=>{n.style.transition="",n.style.opacity=String(x)},p=()=>{n.play().catch(x=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+x)})},g=()=>i||n.error?(o.logger.error("NarraLeaf-React: Vfx","Cannot wait for a vfx whose source failed to load: "+e.config.src),Promise.resolve()):n.readyState>=2?Promise.resolve():new Promise(x=>{let S=!1,b=()=>D(),w=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),D()},D=()=>{S||(S=!0,l.delete(D),n.removeEventListener("loadeddata",b),n.removeEventListener("error",w),x())};l.add(D),n.addEventListener("loadeddata",b),n.addEventListener("error",w),(n.readyState>=2||n.error)&&D()}),h=(x,S,b)=>{let w=S?.duration??0,D=++s;return b.instant||w<=0?(d(x),Promise.resolve()):new Promise(B=>{let G=!1,de=null,ke=()=>{G||(G=!0,l.delete(ke),de!==null&&clearTimeout(de),s===D&&t.current&&d(x),B())};l.add(ke),n.style.transition=`opacity ${w}ms ${hp(o,S?.easing)}`,n.offsetWidth,n.style.opacity=String(x),de=setTimeout(ke,w)})},m=x=>{r||(r=!0,i=x,o.mountState(e,{show:async S=>{a=!0;let b={instant:!1};c.add(b);try{if(await g(),!t.current)return;e.state.paused||p(),await h(e.config.opacity,S,b)}finally{c.delete(b)}},hide:async S=>{a=!0;let b={instant:!1};c.add(b);try{await h(0,S,b),t.current&&n.pause()}finally{c.delete(b)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:S=>{n.playbackRate=S}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},y=()=>m(!1),A=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(n.error?` (media error code ${n.error.code})`:"")),m(!0)},f=o.events.on(E.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(x=>{x.instant=!0}),[...l].forEach(x=>x()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),v=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&p()};return document.addEventListener("visibilitychange",v),n.style.opacity="0",n.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&p(),n.addEventListener("canplay",y),n.addEventListener("error",A),n.readyState>=3?m(!1):n.error&&A(),()=>{n.removeEventListener("canplay",y),n.removeEventListener("error",A),document.removeEventListener("visibilitychange",v),f.cancel(),u.forEach(x=>x()),[...l].forEach(x=>x()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),dp.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,loop:e.config.loop,playsInline:!0,onContextMenu:n=>n.preventDefault(),style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:e.config.fit,mixBlendMode:e.config.blendMode,pointerEvents:"none"}})}import gp from"clsx";import yp,{useCallback as vp,useEffect as Io,useRef as Sp}from"react";function es({children:o,className:e,gameState:t}){let{ratio:n}=be(),i=I(),[r]=se(),s=Sp(null),a=i.config.minWidth,c=i.config.minHeight,l=vp(u=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(u.width,u.height,u.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return Io(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Io(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Io(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Io(()=>t.events.on(E.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),yp.createElement(Ia,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:gp(e),onUpdate:l},o)}import lc,{useEffect as Tp,useRef as bp,useState as uc}from"react";function ts({src:o,width:e,height:t}){let[n,i]=uc({x:0,y:0}),[r,s]=uc(!1),a=bp(null),{ratio:c}=be();return Tp(()=>{let l=u=>{if(a.current){let d=a.current.getBoundingClientRect(),p=u.clientX-d.left,g=u.clientY-d.top;i({x:p,y:g}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),lc.createElement(Vt,{ref:a,className:"overflow-hidden absolute"},lc.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import pc from"react";import Qt from"react";function ns({error:o,errorInfo:e}){return I().config.app.debug?Qt.createElement("div",{className:"text-left"},Qt.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),Qt.createElement("p",{className:"text-red-700"},"Message: ",o.message),Qt.createElement("pre",null,"Error Stack: ",o?.stack),Qt.createElement("pre",null,"Component Stack: ",e?.componentStack),Qt.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):Qt.createElement("div",{className:"bg-white w-full h-full"},Qt.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),Qt.createElement("p",null,"Please contact the game developer for further assistance."))}var Ro=class extends pc.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?pc.createElement(ns,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import fc from"clsx";import U,{useEffect as Kt,useReducer as hc,useState as Vn}from"react";import{flushSync as gc}from"react-dom";import{useRef as Ap}from"react";import{useEffect as xp}from"react";function dc({gameState:o}){let e=Ap(null);return xp(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(E.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import di,{useEffect as Cp}from"react";function is({gameState:o}){let[e]=se(),{ratio:t}=be(),n=o.notificationMgr;Cp(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return di.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},di.createElement(i,{notifications:n.toArray()}))}function mc({notifications:o}){return di.createElement(yo,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>di.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},di.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function yc({story:o=Jn.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:d=!0}){let[p,g]=hc(M=>M+1,0),[h,m]=hc(M=>M+1,0),[y,A]=Vn(0),f=I(),[v]=Vn(()=>new E(f,{update:g,forceUpdate:()=>{v.logger.weakWarn("Player","force update"),gc(()=>{g()})},forceRemount:()=>{v.logger.weakWarn("Player","force remount"),gc(()=>{A(M=>M+1),g()})},next:ae})),x=U.createRef(),S=U.createRef(),[b,w]=Vn(!1),D=U.useRef(!1),B=U.useRef(null),G=U.useRef(null),{preloaded:de}=Ft(),[ke,ht]=Vn(!1),Ze=U.useRef(!1),[ot,q]=Vn(!1),X=U.useRef(!1),H=U.useRef(null),te=U.useRef(!1),[Pe]=Vn(new Map);function Te(M){return{game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable(),scene:M}}function ae(){let M=()=>{Pe.forEach(O=>O.cancel())};if(v.rollLock.isLocked())return;M();let ve=!1,Ue=0;for(;!ve;){if(Ue++>f.config.maxStackModelLoop)throw new P("Max stack model loop reached");let O=f.getLiveGame().next();if(!O){if(f.getLiveGame().stackModel&&!f.getLiveGame().stackModel.isEmpty())continue;break}if(T.isAwaitable(O)){if(B.current===O)break;B.current=O,O.onSettled(()=>{O.isFailed()||(B.current===O&&(B.current=null),ae())}),O.onFailed(ce=>{B.current===O&&(B.current=null),v.logger.error("Player",ce)}),ve=!0;break}if(O instanceof Tn){if(G.current===O)break;G.current=O,O.nextUnlock().then(()=>{G.current===O&&(G.current=null),ae()}),ve=!0;break}if(Ye.isCalledActionResult(O)&&O.wait&&Ye.isStackModelsAwaiting(O.wait.type,O.wait.stackModels)){if(B.current===O)break;if(B.current=O,O.wait){let ce=Ye.executeStackModelGroup(O.wait.type,O.wait.stackModels);ce.then(()=>{B.current===O&&(B.current=null),ae()}),ce.onFailed(le=>{B.current===O&&(B.current=null),v.logger.error("Player",le)})}ve=!0;break}v.handle(O)}v.stage.update()}Kt(()=>{v.audioManager.initialize()},[]),Kt(()=>(f.getLiveGame().setGameState(v),o&&!f.getLiveGame().isPlaying()&&f.getLiveGame().loadStory(o),o?.entryScene&&!v.getPreloadingScene()&&!v.getLastScene()&&v.preloadScene(o.entryScene),v.playerCurrent=x.current,v.mainContentNode=S.current,()=>{f.getLiveGame().setGameState(void 0),v.playerCurrent=null}),[f,o]),Kt(()=>rt(()=>{w(!0);let M=v.getLastScene(),ve=[];M?ve.push(M.events.once("event:scene.mount",()=>{v.stage.next()}).cancel):v.stage.next();let Ue=v.events.on(E.EventTypes["event:state.end"],()=>{c&&c({game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()})});return v.stage.update(),()=>{M&&ve.forEach(O=>O()),Ue.cancel()}}),[]),Kt(()=>rt(()=>{b&&i&&!D.current&&(D.current=!0,v.stage.forceUpdate(),f.hooks.trigger("init",[]),i({game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()}))}),[b]),Kt(()=>rt(()=>{if(ke&&s&&!Ze.current){Ze.current=!0;let M=H.current||v.getLastScene()||v.getPreloadingScene(),ve=Te(M);s(ve)}}),[ke]),Kt(()=>rt(()=>{if(ot&&!X.current){X.current=!0;let M=H.current||v.getLastScene()||v.getPreloadingScene(),ve=Te(M);f.markPreloadComplete(ve)&&r&&r(ve)}}),[ot]),Kt(()=>v.events.on(E.EventTypes["event:state.scene.mount"],M=>{H.current||(H.current=M,m())}).cancel,[]),Kt(()=>{if(!ot||!d||te.current||f.isFirstSceneReady())return;let M=H.current||v.getLastScene();if(!M)return;let ve=null,Ue=null,O=!1;te.current=!0;let ce=()=>{O=!0,te.current=!1;let le=Te(M);f.markFirstSceneReady(le)&&a&&a(le)};return typeof requestAnimationFrame=="function"?ve=requestAnimationFrame(()=>{Ue=setTimeout(ce,0)}):Ue=setTimeout(ce,0),()=>{O||(te.current=!1,ve!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(ve),Ue!==null&&clearTimeout(Ue))}},[d,h,p,ot]),Kt(()=>de.events.depends([de.events.on($e.EventTypes["event:preloaded.ready"],()=>{ht(!0),v.stage.update(),o&&f.getLiveGame().isPlaying()&&ae()}),de.events.on($e.EventTypes["event:preloaded.complete"],()=>{q(!0)})]).cancel,[]),Kt(()=>{v.flushDep=p},[p]);let fe=e||f.config.width,F=t||f.config.height;return U.createElement(Ro,{onError:l},U.createElement("div",{style:{width:typeof fe=="number"?`${fe}px`:fe,height:typeof F=="number"?`${F}px`:F},className:fc(n,"__narraleaf_content-player"),ref:x,tabIndex:0},U.createElement(es,{className:fc("flex-grow overflow-auto"),gameState:v},U.createElement(Gr,{gameState:v}),U.createElement(dc,{gameState:v}),U.createElement(Vt,{className:"absolute",ref:S,style:{cursor:v.game.config.cursor?"none":"auto",overflow:v.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},f.config.cursor&&U.createElement(ts,{src:f.config.cursor,width:f.config.cursorWidth,height:f.config.cursorHeight}),U.createElement(wp,{show:ke&&d,key:y},U.createElement(Lr,null,U.createElement(Ha,{state:v}),U.createElement(Ba,{state:v}),U.createElement(kp,{state:v},v.getSceneElements().map(M=>U.createElement(qr,{key:"scene-"+M.scene.getId(),state:v,elements:M})),v.getVideos().map((M,ve)=>U.createElement("div",{className:"w-full h-full absolute",key:"video-"+ve,"data-element-type":"video"},U.createElement(Zr,{gameState:v,video:M}))),v.getVfx().map(M=>U.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+M.getId(),"data-element-type":"vfx",style:{zIndex:M.config.zIndex}},U.createElement(_r,{gameState:v,vfx:M})))),v.getSceneElements().map(M=>U.createElement(Yr,{key:"scene-dialogs-"+M.scene.getId(),state:v,elements:M})),U.createElement(Pp,{NvlComponent:f.config.nvlDialog}))),U.createElement(za,{state:v}),U.createElement(wa,null,u),U.createElement(is,{gameState:v})))))}function wp({children:o,show:e}){return U.createElement(U.Fragment,null,e?o:null)}function kp({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?U.createElement(rc,{state:o,camera:t},e):U.createElement(U.Fragment,null,e)}function Pp({NvlComponent:o}){let{dialogs:e,state:t}=Ut(),i=I().getLiveGame().getGameState(),r=U.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Ce.getCtx({gameState:i})),l=t.activeDialogId===s.id,u=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return U.createElement(o,{dialogs:r})}import"client-only";import Hn from"react";function vc({children:o,game:e}){return Hn.createElement(Hn.Fragment,null,Hn.createElement(ia,null,Hn.createElement(Zs,{game:e},Hn.createElement(ba,null,Hn.createElement(na,null,o)))))}var Ep=(c=>(c.image="narraleaf:image",c.text="narraleaf:text",c.layer="narraleaf:layer",c.scene="narraleaf:scene",c.video="narraleaf:video",c.vfx="narraleaf:vfx",c.camera="narraleaf:camera",c.puppet="narraleaf:puppet",c))(Ep||{});import Dp from"clsx";import Wt,{useEffect as Sc,useRef as Lp}from"react";import{motion as Ip,useIsPresent as Rp}from"motion/react";var Mp={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Np({children:o,initial:e,transition:t,...n}){let i=I(),r=xt(),{ratio:s}=be(),[a]=cn(re.Preferences.showDialog),c=Lp(null),[l]=yn("nextAction"),u=Rp();function d(){r.requestComplete()}return Sc(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
59
+ at Say.tsx: onElementClick`);return}let p=h=>{h.repeat||i.keyMap.match("nextAction",h.key)&&r.requestComplete()};window.addEventListener("keydown",p);let g=r.events.on(Me.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",p),g.cancel()}},[r,l]),Sc(()=>{let p=i.preference.onPreferenceChange(re.Preferences.autoForward,g=>{g&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{p.cancel()}},[r]),Wt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},Wt.createElement("div",{className:Dp("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:d,style:{...Li(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:c},Wt.createElement(Ip.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)))}function Tc({children:o,...e}){let t=xt();return!t.config.action.sentence||!t.config.action.words?null:Wt.createElement(Np,{...e},o)}var Du=Tc;function bc(){return Wt.createElement(Tc,null,Wt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},Wt.createElement(Ar,null),Wt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},Wt.createElement(qt,null),Wt.createElement(ln,{...Mp}))))}var mi={say:bc,menu:ic,notification:mc,nvlDialog:Mr};var Mo=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var fi=class{constructor(e={}){this.keyMap=e;this.events=new Q}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],i=r=>Array.isArray(r)?r:[r];Array.isArray(n)?this.setKeyBinding(e,[...n,...i(t)]):this.setKeyBinding(e,[n,...i(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,i)=>{n===e&&t(i)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(i=>i.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var Ac=(e=>(e.game="game",e))(Ac||{}),Je=class Je{constructor(e){this.hooks=new ki;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new ei(Je.DefaultPreference);this.audioBuses=new $n(()=>this.config.audioBuses??[],Hs(this.preference));this.keyMap=new fi({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new Q;this.puppetBackends=new Eo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=z(Je.DefaultConfig,e),this.plugins=new Mo(this),this.router=new an(this)}configure(e){let[t,n]=ks(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=z(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(E.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}registerPuppetBackend(e){return this.puppetBackends.register(e),this}getPuppetBackend(e){return this.puppetBackends.get(e)}listPuppetBackends(){return this.puppetBackends.list()}getPuppetBackendRegistry(){return this.puppetBackends}onPreloadComplete(e){return this.lifecycleEvents.on(Je.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Je.LifecycleEventTypes["event:game.preloadComplete"],e)}whenPreloadComplete(){return this.preloadCompleteContext?Promise.resolve(this.preloadCompleteContext):new Promise(e=>{this.oncePreloadComplete(e)})}isPreloadComplete(){return this.preloadCompleteContext!==null}onFirstSceneReady(e){return this.lifecycleEvents.on(Je.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Je.LifecycleEventTypes["event:game.firstSceneReady"],e)}whenFirstSceneReady(){return this.firstSceneReadyContext?Promise.resolve(this.firstSceneReadyContext):new Promise(e=>{this.onceFirstSceneReady(e)})}isFirstSceneReady(){return this.firstSceneReadyContext!==null}markPreloadComplete(e){return this.preloadCompleteContext?!1:(this.preloadCompleteContext=e,this.lifecycleEvents.emit(Je.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Je.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.audioBuses.dispose(),this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new It(this)}};Je.defaultSettings={volume:1},Je.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:0,skipInterval:100},Je.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",voiceFadeDuration:"voiceFadeDuration",voiceEndMode:"voiceEndMode",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},Je.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:mi.notification,menu:mi.menu,dialog:mi.say,nvlDialog:mi.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100,audioBuses:[]},Je.GameSettingsNamespace=Ac,Je.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var re=Je;var No=class No extends ${constructor(){super(...arguments);this._jumpTarget=null}setJumpTarget(t){return this._jumpTarget=t,this}getJumpTarget(){return this._jumpTarget}static executeActionsAsync(t,n){let i=t.game.getLiveGame().requestAsyncStackModel([{type:n.type,node:n.contentNode}]);return t.game.getLiveGame().executeAsyncStackModel(i)}checkActionChain(t){if(t.some(n=>!!n.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return t}executeAction(t,n){let i=this.contentNode,[r]=i.getContent();if(this.type===ne.do)return r.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:r[0].contentNode}];if(this.type===ne.doAsync){if(r.length===0)return super.executeAction(t,n);let s=No.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===ne.any){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:s}}}else if(this.type===ne.all){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:s}}}else if(this.type===ne.allAsync){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().requestAsyncStackModel([{type:a.type,node:a.contentNode}]));return t.timelines.attachTimeline(T.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===ne.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=Ye.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ne.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let c=Ye.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ne.break){if(!n.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return n.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===ne.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=T.delay(s):T.isAwaitable(s)?a=s:a=T.fromPromise(s);let c=new T,l=new Ne(a);return t.timelines.attachTimeline(l),a.then(()=>{c.resolve({type:this.type,node:this.contentNode.getChild()})}),c.onSkipControllerRegister(u=>{u.onAbort(()=>{l.abort()})}),c}else if(this.type===ne.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new T,a=new T,c=new Ne(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(re.Preferences.autoForward),d=l.getPreference(re.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,g=!1,h=null,m=null,y=null,A=()=>{m?.cancel(),y?.cancel(),h&&(clearTimeout(h),h=null)},f=()=>{g||(g=!0,A(),a.resolve())};return m=t.events.on(E.EventTypes["event:state.player.stageClick"],f),y=t.events.on(E.EventTypes["event:state.player.skip"],f),p!==null&&(h=setTimeout(f,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(v=>{v.onAbort(()=>{g||(g=!0,A(),c.abort())})}),s}else{if(this.type===ne.label)return super.executeAction(t,n);if(this.type===ne.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Fe(`Jump target label "${l}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),c=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(l,u)},[c]),a.clearMainStack().getStackModelForce().push({type:this.type,node:s.contentNode}),null}}throw new Error("Unknown control action type: "+this.type)}getFutureActions(t,n){if(this.callee.config.allowFutureScene===!1&&n.allowFutureScene===!1)return[...super.getFutureActions(t,n)];if(this.type===ne.break||this.type===ne.waitForClick||this.type===ne.label||this.type===ne.jump)return super.getFutureActions(t,n);let i=this.contentNode.getContent()[0],r=super.getFutureActions(t,n);return[...i??[],...r]}stringify(t,n,i){if(this.type===ne.break)return super.stringifyWithContent("Control","break");if(this.type===ne.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===ne.label||this.type===ne.jump){let[a]=this.contentNode.getContent(),c=this.type===ne.label?"label":"jump";return super.stringifyWithContent("Control",`${c}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};No.ActionTypes=ne;var oe=No;var We=class o extends ue{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static whileLoop(t,n){return new o().whileLoop(t,n)}static breakLoop(){return new o().breakLoop()}static sleep(t){return new o().sleep(t)}static waitForClick(){return new o().waitForClick()}static label(t){return new o().label(t)}static jump(t){return new o().jump(t)}do(t){return this.push(oe.ActionTypes.do,t)}doAsync(t){return this.push(oe.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(oe.ActionTypes.any,t)}all(t){return this.pushUnchained(oe.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(oe.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(oe.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=j.from(t);return this.pushWithLambda(oe.ActionTypes.while,n,i)}breakLoop(){let t=new oe(this.chain(),oe.ActionTypes.break,new C().setContent([]));return this.chain(t)}sleep(t){return this.push(oe.ActionTypes.sleep,[],t)}waitForClick(){let t=new oe(this.chain(),oe.ActionTypes.waitForClick,new C().setContent([]));return this.chain(t)}label(t){let n=new oe(this.chain(),oe.ActionTypes.label,new C().setContent([t]));return this.chain(n)}jump(t){let n=new oe(this.chain(),oe.ActionTypes.jump,new C().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new C().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new C().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new C().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?$t.say(n).getActions():Oe.toActions([n]))}};var W=class W extends ct{static get DefaultUserConfig(){return W._defaultUserConfig??(W._defaultUserConfig=new K({name:"(anonymous)",autoInit:!0,src:W.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...Y.DefaultTransformState.getDefaultConfig()},{position:e=>R.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return k.isStaticImageData(t)?k.srcToURL(t):k.isColor(t)?t:k.isImageSrc(t)?k.srcToURL(t):W.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isLayeredSrc(e){return!!e.config.src?.slots}static isSrcDefinitionObject(e){return typeof e=="object"&&e!==null&&!k.isImageSrc(e)&&!k.isColor(e)}static isLayeredDefinition(e){return this.isSrcDefinitionObject(e)&&"layers"in e}static isTagDefinition(e){return this.isSrcDefinitionObject(e)&&"resolve"in e}static isLayerVariants(e){return typeof e=="object"&&e!==null}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(k.isImageSrc(t)||k.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:W.isLayeredSrc(e)?null:W.isTagSrc(e)&&e.config.src.resolve?W.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):W.isStaticSrc(e)?k.isStaticImageData(e.state.currentSrc)?k.srcToURL(e.state.currentSrc):k.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static getSrcURLs(e,t){let n=e.config.src?.slots;if(!n)return[];let i=new Set(t??e.state.currentSrc);return n.map(r=>W.resolveLayerSlot(r,i))}static resolveLayerSlot(e,t){if(e===null||typeof e=="string")return e;if(typeof e=="function")return e(t);for(let[n,i]of Object.entries(e))if(t.has(n))return i;return null}static getAllLayerSrc(e){let t=e.config.src?.slots;if(!t)return[];let n=[];for(let i of t)if(typeof i=="string")n.push(i);else if(W.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new W({src:e})}constructor(e={}){super();let t=W.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new We,n=>{if(k.isImageSrc(e)||k.isColor(e)){if(k.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new ge(n,ge.ActionTypes.setAppearance,new C().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new We,i=>i.chain(this._setDarkness(i,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new ie("Cannot add self as a wearable");this.config.wearables.push(n),Object.assign(n.config,{isWearable:!0})}return this}wear(e){return this.addWearable(e)}bindWearable(e){return e.addWearable([this])}asWearableOf(e){return this.bindWearable(e)}useLayer(e){return this.userConfig.get().layer=e||void 0,Object.assign(this.config,{layer:e||void 0}),this}toData(){return{state:W.StateSerializer.serialize(this.state),transformState:Y.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=W.StateSerializer.deserialize(e.state),this.transformState=Y.deserialize(e.transformState),this}_applyTransition(e,t){return new Ie(this.chain(),Ee.applyTransition,new C().setContent([e,t]))}_init(e,t){return new Ie(this.chain(),Ee.init,new C().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new ge(this.chain(),ge.ActionTypes.initWearable,new C().setContent([e]))}_flush(){return new ge(this.chain(),ge.ActionTypes.flush,new C)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!W.isTagSrc(this))throw new Error(`Tag not defined
60
+ Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(c=>{let l=n.get(c);l&&i.set(l,c)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let c=i.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(c)}),r}_setAppearanceSync(e){if(k.isImageSrc(e)||k.isColor(e)){if(k.isColor(e)&&!this.config.isBackground)throw new ie("Color src is not allowed for non-background image");this.state.currentSrc=e;return}if(!W.isTagSrc(this))throw this._mixedSrcError();let t=this.state.currentSrc,n=this.resolveTags(t,e);this.state.currentSrc=n}_mixedSrcError(){throw new ie(`Trying to mix src and tags
59
61
  To better understand the behavior of the image, you cannot mix static src and tags in the same image. `)}_invalidSrcHandlerError(){throw new Error("Invalid src handler, If you are using tags, config.src must be a function that resolves the src from the tags. If you are using src, config.src must be a string or StaticImageData")}_invalidWearableError(e){throw new Error(`Invalid wearable
60
62
  Wearable must be an Image with isWearable set to true
61
63
  It seems like you are trying to add a non-wearable image to wearables
62
64
  Image below violates the rule:
63
65
  `+e)}_invalidTagGroupDefinitionError(e,t=!1){throw new Error("Invalid tag group definition. Tags in groups must be unique and not conflicting with each other."+(e?`
64
66
  Tag "${e}" belongs to more than one group.`:"")+(t?`
65
- Layers offering the same tag set share one group, so a shared tag means two layers offer different sets. Repeat the whole set on every layer that follows the group, using null where that layer draws nothing.`:""))}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(ge.resolveCurrentSrc(this))._setTargetSrc(t))),new ge(e,ge.ActionTypes.setSrc,new w().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){let e=this.config.src;return e?.slots?W.getAllLayerSrc(this).forEach(t=>this.srcManager.registerRawSrc(t)):e?.resolve?this.srcManager.registerRawSrc(W.getSrcFromTags(e.defaults,e.resolve)):k.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(k.srcToURL(this.state.currentSrc)),this}static collectLayerGroups(e){let t=[],n=new Set;for(let i of e){if(!W.isLayerVariants(i))continue;let r=Object.keys(i),s=[...r].sort().join("\0");n.has(s)||(n.add(s),t.push(r))}return t}static normalizeSrcDefinition(e){return W.isLayeredDefinition(e)?{groups:W.collectLayerGroups(e.layers),defaults:[...e.defaults],resolve:null,slots:e.layers}:W.isTagDefinition(e)?{groups:e.groups,defaults:[...e.defaults],resolve:e.resolve,slots:null}:null}createImageConfig(e){let t=e.get();return W.DefaultImageConfig.create({...t,src:W.normalizeSrcDefinition(t.src)})}getInitialState(){return W.DefaultImageState.create().assign({currentSrc:W.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(Q.DefaultTransformState.keys());return new Q(Q.DefaultTransformState.create(t.get()).get())}checkConfig(){for(let e of this.config.wearables)if(!e.config.isWearable)throw this._invalidWearableError(JSON.stringify(e.config));if(W.isTagSrc(this)){let e=this.config.src,t=new Set;for(let r of e.groups)for(let s of r){if(t.has(s))throw this._invalidTagGroupDefinitionError(s,!!e.slots);t.add(s)}let n=this.constructTagMap(e.groups),i=new Set;for(let r of e.defaults){if(i.has(r))throw new Error(`Tag conflict
67
+ Layers offering the same tag set share one group, so a shared tag means two layers offer different sets. Repeat the whole set on every layer that follows the group, using null where that layer draws nothing.`:""))}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(ge.resolveCurrentSrc(this))._setTargetSrc(t))),new ge(e,ge.ActionTypes.setSrc,new C().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){let e=this.config.src;return e?.slots?W.getAllLayerSrc(this).forEach(t=>this.srcManager.registerRawSrc(t)):e?.resolve?this.srcManager.registerRawSrc(W.getSrcFromTags(e.defaults,e.resolve)):k.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(k.srcToURL(this.state.currentSrc)),this}static collectLayerGroups(e){let t=[],n=new Set;for(let i of e){if(!W.isLayerVariants(i))continue;let r=Object.keys(i),s=[...r].sort().join("\0");n.has(s)||(n.add(s),t.push(r))}return t}static normalizeSrcDefinition(e){return W.isLayeredDefinition(e)?{groups:W.collectLayerGroups(e.layers),defaults:[...e.defaults],resolve:null,slots:e.layers}:W.isTagDefinition(e)?{groups:e.groups,defaults:[...e.defaults],resolve:e.resolve,slots:null}:null}createImageConfig(e){let t=e.get();return W.DefaultImageConfig.create({...t,src:W.normalizeSrcDefinition(t.src)})}getInitialState(){return W.DefaultImageState.create().assign({currentSrc:W.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(Y.DefaultTransformState.keys());return new Y(Y.DefaultTransformState.create(t.get()).get())}checkConfig(){for(let e of this.config.wearables)if(!e.config.isWearable)throw this._invalidWearableError(JSON.stringify(e.config));if(W.isTagSrc(this)){let e=this.config.src,t=new Set;for(let r of e.groups)for(let s of r){if(t.has(s))throw this._invalidTagGroupDefinitionError(s,!!e.slots);t.add(s)}let n=this.constructTagMap(e.groups),i=new Set;for(let r of e.defaults){if(i.has(r))throw new Error(`Tag conflict
66
68
  Tag "${r}" is conflicting with another tag
67
69
  Error found in config.tag.defaults`);if(!n.has(r))throw new Error(`Tag not found
68
70
  Tag "${r}" is not defined in tagDefinitions
69
- Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}if(e.slots){let r=new Set(e.defaults);for(let s of e.groups)if(!s.some(a=>r.has(a)))throw new te(`Layer has no default
70
- The group with tags "${s.join(", ")}" needs exactly one of them listed in src.defaults`)}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new ge(e,ge.ActionTypes.setDarkness,new w().setContent([t,n,i]))}};W.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",W.StateSerializer=new tt,W._defaultUserConfig=null,W.DefaultImageConfig=new B({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),W.DefaultImageState=new B({currentSrc:W.DefaultImagePlaceholder,darkness:0});var R=W;var We=class extends Et{_setPrevLayers(e){return this._prevLayers=e,this}_setTargetLayers(e){return this._targetLayers=e,this}_getPrevLayers(){return this._prevLayers}_getTargetLayers(){return this._targetLayers}_isLayered(){return!!this._prevLayers||!!this._targetLayers}_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>z(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>z(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(this._isLayered())return{};if(k.isColor(e))return{src:R.DefaultImagePlaceholder,style:{backgroundColor:k.isRGBAColor(e)?k.RGBAColorToHex(e):e}};if(k.isImageSrc(e))return{src:k.srcToURL(e)};throw new te("Image transition src cannot be identified, using: "+e)}};var pi=class o extends We{constructor(e){super(),this.from=e.from,this.to=e.to,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.from,end:this.to,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{filter:`brightness(${1-e})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o({from:this.from,to:this.to,duration:this.duration,easing:this.easing})}};var di=class di extends ${static resolveTagSrc(e,t){if(!R.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return R.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(R.isLayeredSrc(e))throw e._mixedSrcError();if(R.isStaticSrc(e))return k.isImageSrc(e.state.currentSrc)?k.srcToURL(e.state.currentSrc):e.state.currentSrc;if(R.isTagSrc(e)&&e.config.src.resolve)return R.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===at.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new T(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===at.setSrc){let n=this.contentNode.getContent()[0];if(k.isColor(n)&&!this.callee.config.isBackground)throw new te("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else{if(this.type===at.flush)return super.executeAction(e,t);if(this.type===at.setAppearance){let[n,i]=this.contentNode.getContent();if(!R.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=()=>{this.callee.state.currentSrc=a};if(R.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let d=new T(f=>f).registerSkipController(new H(()=>super.executeAction(e,t)));i._setPrevLayers(R.getSrcURLs(this.callee))._setTargetLayers(R.getSrcURLs(this.callee,s));let g=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),y=e.timelines.attachTimeline(d).attachChild(g);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:y},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.flush(),super.executeAction(e,t)}let l=this.callee.config.src.resolve;if(!l)throw this.callee._invalidSrcHandlerError();let u=R.getSrcFromTags(s,l);if(e.logger.debug("Image - Set Appearance",s,u),i){let d=new T(f=>f).registerSkipController(new H(()=>super.executeAction(e,t)));i._setPrevSrc(di.resolveCurrentSrc(this.callee))._setTargetSrc(u);let g=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),y=e.timelines.attachTimeline(d).attachChild(g);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:y},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else if(this.type===at.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},c=e.getExposedStateForce(this.callee);if(i){let l=new T(g=>g),u=new pi({from:s,to:n,duration:i,easing:r});if(R.isLayeredSrc(this.callee)){let g=R.getSrcURLs(this.callee);u._setPrevLayers(g)._setTargetLayers(g)}else{let g=di.resolveCurrentSrc(this.callee);u._setPrevSrc(g)._setTargetSrc(g)}let d=c.applyTransition(u,()=>{this.callee.state.darkness=n,l.resolve(super.executeAction(e,t))}),p=e.timelines.attachTimeline(l).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:p},()=>{l.isSettled()||l.abort(),d.abort(),a()}),l}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};di.ActionTypes=at;var ge=di;var $t=class $t extends ${static handleSceneInit(e,t,n,i){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,async r=>{await $t.initBackgroundMusic(e,r),i.resolve(t),n.logger.debug("Scene Action","Scene init")}),i)}static async initBackgroundMusic(e,t){e.state.backgroundMusic&&await t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new te("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,i=t.findElementByScene(n);i&&t.removeElement(i);let r=t.fromElementSnapshot(e.element);t.addElement(r),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyTransition(e,t,n){let i=new T().registerSkipController(new H(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{i.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(i),i}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}applyNvlVisibility(e,t,n,i){e.setNvlVisibility(t,n);let r=Math.max(0,n?.duration||0);if(r===0)return super.executeAction(e,i);let s=super.executeAction(e,i),a=new T(l=>l),c=null;return a.registerSkipController(new H(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===X.action)return super.executeAction(e,t);if(this.is($t,"scene:init")){let n=new T(s=>s),i=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{this.exit(e)},[]);let r={type:this.type,node:this.contentNode.getChild()};return $t.handleSceneInit(this.callee,r,e,T.forward(n,r))}else if(this.type===X.exit){let n=$t.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new T(s=>s);e.timelines.attachTimeline(r),$t.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),$t.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===X.jumpTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[r]);let s=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:s}),null}else if(this.type===X.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.setBackgroundMusic(c,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===X.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===X.transitionToScene){let[n,i,r]=this.contentNode.getContent();return n._setPrevSrc(ge.resolveCurrentSrc(this.callee.background)),i?n._setTargetSrc(ge.resolveCurrentSrc(i.background)):r&&n._setTargetSrc(r),this.applyTransition(e,n,t)}else if(this.type===X.nvlBlock){let[n,i]=this.contentNode.getContent(),r=e.createNvlSnapshot();return e.enterNvlMode(i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{e.restoreNvlSnapshot(s)},[r]),n.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]}else if(this.type===X.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=T.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===X.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=T.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===X.nvlEnd){let[n]=this.contentNode.getContent(),i=e.createNvlSnapshot();return e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{e.restoreNvlSnapshot(r)},[i]),e.exitNvlMode(n||null),{type:this.type,node:null}}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===X.jumpTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=e.getScene(i,!0).getSceneRoot()?.contentNode;return s?.action?[s.action]:[]}if(this.type===X.nvlBlock){let[i]=this.contentNode.getContent(),r=super.getFutureActions(e,t);return[...i??[],...r]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new te(`Scene with name ${e} not found
71
+ Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}if(e.slots){let r=new Set(e.defaults);for(let s of e.groups)if(!s.some(a=>r.has(a)))throw new ie(`Layer has no default
72
+ The group with tags "${s.join(", ")}" needs exactly one of them listed in src.defaults`)}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new ge(e,ge.ActionTypes.setDarkness,new C().setContent([t,n,i]))}};W.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",W.StateSerializer=new Xe,W._defaultUserConfig=null,W.DefaultImageConfig=new K({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),W.DefaultImageState=new K({currentSrc:W.DefaultImagePlaceholder,darkness:0});var L=W;var je=class extends Rt{_setPrevLayers(e){return this._prevLayers=e,this}_setTargetLayers(e){return this._targetLayers=e,this}_getPrevLayers(){return this._prevLayers}_getTargetLayers(){return this._targetLayers}_isLayered(){return!!this._prevLayers||!!this._targetLayers}_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>z(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>z(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(this._isLayered())return{};if(k.isColor(e))return{src:L.DefaultImagePlaceholder,style:{backgroundColor:k.isRGBAColor(e)?k.RGBAColorToHex(e):e}};if(k.isImageSrc(e))return{src:k.srcToURL(e)};throw new ie("Image transition src cannot be identified, using: "+e)}};var hi=class o extends je{constructor(e){super(),this.from=e.from,this.to=e.to,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.from,end:this.to,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{filter:`brightness(${1-e})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o({from:this.from,to:this.to,duration:this.duration,easing:this.easing})}};var gi=class gi extends ${static resolveTagSrc(e,t){if(!L.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return L.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(L.isLayeredSrc(e))throw e._mixedSrcError();if(L.isStaticSrc(e))return k.isImageSrc(e.state.currentSrc)?k.srcToURL(e.state.currentSrc):e.state.currentSrc;if(L.isTagSrc(e)&&e.config.src.resolve)return L.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===ut.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new T(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===ut.setSrc){let n=this.contentNode.getContent()[0];if(k.isColor(n)&&!this.callee.config.isBackground)throw new ie("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else{if(this.type===ut.flush)return super.executeAction(e,t);if(this.type===ut.setAppearance){let[n,i]=this.contentNode.getContent();if(!L.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=()=>{this.callee.state.currentSrc=a};if(L.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let d=new T(m=>m).registerSkipController(new V(()=>super.executeAction(e,t)));i._setPrevLayers(L.getSrcURLs(this.callee))._setTargetLayers(L.getSrcURLs(this.callee,s));let g=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(d).attachChild(g);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.flush(),super.executeAction(e,t)}let l=this.callee.config.src.resolve;if(!l)throw this.callee._invalidSrcHandlerError();let u=L.getSrcFromTags(s,l);if(e.logger.debug("Image - Set Appearance",s,u),i){let d=new T(m=>m).registerSkipController(new V(()=>super.executeAction(e,t)));i._setPrevSrc(gi.resolveCurrentSrc(this.callee))._setTargetSrc(u);let g=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(d).attachChild(g);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else if(this.type===ut.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},c=e.getExposedStateForce(this.callee);if(i){let l=new T(g=>g),u=new hi({from:s,to:n,duration:i,easing:r});if(L.isLayeredSrc(this.callee)){let g=L.getSrcURLs(this.callee);u._setPrevLayers(g)._setTargetLayers(g)}else{let g=gi.resolveCurrentSrc(this.callee);u._setPrevSrc(g)._setTargetSrc(g)}let d=c.applyTransition(u,()=>{this.callee.state.darkness=n,l.resolve(super.executeAction(e,t))}),p=e.timelines.attachTimeline(l).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:p},()=>{l.isSettled()||l.abort(),d.abort(),a()}),l}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};gi.ActionTypes=ut;var ge=gi;var Xt=class Xt extends ${static handleSceneInit(e,t,n,i){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,async r=>{await Xt.initBackgroundMusic(e,r),i.resolve(t),n.logger.debug("Scene Action","Scene init")}),i)}static async initBackgroundMusic(e,t){e.state.backgroundMusic&&await t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new ie("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,i=t.findElementByScene(n);i&&t.removeElement(i);let r=t.fromElementSnapshot(e.element);t.addElement(r),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyTransition(e,t,n){let i=new T().registerSkipController(new V(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{i.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(i),i}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}applyNvlVisibility(e,t,n,i){e.setNvlVisibility(t,n);let r=Math.max(0,n?.duration||0);if(r===0)return super.executeAction(e,i);let s=super.executeAction(e,i),a=new T(l=>l),c=null;return a.registerSkipController(new V(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===J.action)return super.executeAction(e,t);if(this.is(Xt,"scene:init")){let n=new T(s=>s),i=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{this.exit(e)},[]);let r={type:this.type,node:this.contentNode.getChild()};return Xt.handleSceneInit(this.callee,r,e,T.forward(n,r))}else if(this.type===J.exit){let n=Xt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new T(s=>s);e.timelines.attachTimeline(r),Xt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Xt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===J.jumpTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[r]);let s=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:s}),null}else if(this.type===J.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.setBackgroundMusic(c,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===J.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===J.transitionToScene){let[n,i,r]=this.contentNode.getContent();return n._setPrevSrc(ge.resolveCurrentSrc(this.callee.background)),i?n._setTargetSrc(ge.resolveCurrentSrc(i.background)):r&&n._setTargetSrc(r),this.applyTransition(e,n,t)}else if(this.type===J.nvlBlock){let[n,i]=this.contentNode.getContent(),r=e.createNvlSnapshot();return e.enterNvlMode(i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{e.restoreNvlSnapshot(s)},[r]),n.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]}else if(this.type===J.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=T.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===J.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=T.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===J.nvlEnd){let[n]=this.contentNode.getContent(),i=e.createNvlSnapshot();return e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{e.restoreNvlSnapshot(r)},[i]),e.exitNvlMode(n||null),{type:this.type,node:null}}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===J.jumpTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=e.getScene(i,!0).getSceneRoot()?.contentNode;return s?.action?[s.action]:[]}if(this.type===J.nvlBlock){let[i]=this.contentNode.getContent(),r=super.getFutureActions(e,t);return[...i??[],...r]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new ie(`Scene with name ${e} not found
71
73
  Make sure you have registered the scene using story.register
72
74
  Action: (id: ${this.getId()}) ${this.type}
73
- At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===X.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};$t.ActionTypes=X;var ce=$t;var Qr=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},At=class At{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||At.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return At.isHexString(e)||At.isNamedColor(e)||At.isRGBAColor(e)}static isNamedColor(e){return ms(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(At.isHexString(e))return e;if(At.isNamedColor(e))return e;if(At.isRGBAColor(e))return At.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,c=this.calc(i,s),l=this.calc(r,a),u=n.invertX?{right:c}:{left:c},d=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...d}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};At.RGBColor=Qr;var k=At,Xr=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},Me=class o extends Xr{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},$i=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let c=a.contentNode.getChild();c&&c.action&&i.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof ge)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof ce){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
75
+ At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===J.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};Xt.ActionTypes=J;var pe=Xt;var os=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},kt=class kt{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||kt.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return kt.isHexString(e)||kt.isNamedColor(e)||kt.isRGBAColor(e)}static isNamedColor(e){return xs(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(kt.isHexString(e))return e;if(kt.isNamedColor(e))return e;if(kt.isRGBAColor(e))return kt.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,c=this.calc(i,s),l=this.calc(r,a),u=n.invertX?{right:c}:{left:c},d=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...d}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};kt.RGBColor=os;var k=kt,rs=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},Ve=class o extends rs{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},Yi=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let c=a.contentNode.getChild();c&&c.action&&i.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof ge)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof pe){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
74
76
  Scene: ${s.config.name}
75
77
 
76
- At: ${t.__stack}`;throw new Me(a)}}else i.set(s.config.name,s);if(t.type===X.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(r.has(c))return;r.add(c)}}}checkImage(e,t){if(t.type===at.setSrc){let i=t.contentNode.getContent()[0];k.isImageURL(i)&&k.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},te=class o extends Error{static toMessage(e,t){let n=[];return n.push(...Array.isArray(e)?e:[e]),t&&n.push(...Array.isArray(t)?t.map(o.getActionTrace):[o.getActionTrace(t)]),n.join("")}static getActionTrace(e){return`
78
+ At: ${t.__stack}`;throw new Ve(a)}}else i.set(s.config.name,s);if(t.type===J.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(r.has(c))return;r.add(c)}}}checkImage(e,t){if(t.type===ut.setSrc){let i=t.contentNode.getContent()[0];k.isImageURL(i)&&k.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},ie=class o extends Error{static toMessage(e,t){let n=[];return n.push(...Array.isArray(e)?e:[e]),t&&n.push(...Array.isArray(t)?t.map(o.getActionTrace):[o.getActionTrace(t)]),n.join("")}static getActionTrace(e){return`
77
79
  Using action (id: ${e.getId()})
78
- at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},L=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Ge=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function Ap(o,e){return J.color(o,e)}function xp(o){return J.bold(o)}function Cp(o){return J.italic(o)}var Jr=class o extends We{constructor(e){super(),this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(e=>({style:{opacity:1-e}})),this.asTarget(e=>({style:{opacity:e}}))]}}copy(){return new o({duration:this.duration,easing:this.easing})}};var Yr=class o extends We{constructor(e){super(),this.duration=e.duration,this.offset=e.offset??[0,0],this.easing=e.easing}createTask(e){let{invertX:t,invertY:n}=e.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.offset[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.offset[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((i,r,s)=>({style:{opacity:i,translate:`${t?-r:r}px ${n?-s:s}px`}}))]}}copy(){return new o({duration:this.duration,offset:this.offset,easing:this.easing})}};function Z(o){return o<0?0:o>1?1:o}function mc(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function Zr(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function fc(o){switch(o){case"left":return"to left";case"top":return"to top";case"bottom":return"to bottom";case"right":default:return"to right"}}function hc(o){return o==="vertical"?"to right":"to bottom"}var _r=class o extends We{constructor(e){super(),this.duration=e.duration,this.blur=e.blur??16,this.easing=e.easing}createTask(){let e=Math.max(0,this.blur);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-Z(t),filter:`blur(${e*Z(t)}px)`}})),this.asTarget(t=>({style:{opacity:Z(t),filter:`blur(${e*(1-Z(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var es=class o extends We{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*Z(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-Z(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};function G(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function Do(o,e,t){return o<e?e:o>t?t:o}var jt=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${G(t)}deg`:fc(t);return{mask:(r,s)=>{let a=-n+(s?1-Z(r):Z(r))*(100+n);return s?`linear-gradient(${i}, transparent ${G(a)}%, #000 ${G(a+n)}%)`:`linear-gradient(${i}, #000 ${G(a)}%, transparent ${G(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${G(t)}deg`,`${G(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let c=-n+Z(s)*(50+n);if(!a){let l=u=>`linear-gradient(${u}, #000 ${G(c)}%, transparent ${G(c+n)}%)`;return`${l(i)}, ${l(r)}`}if(c<0){let l=Z((c+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${G(50-c-n)}%, rgba(0,0,0,${G(l)}) 50%, transparent ${G(50+c+n)}%)`}return`linear-gradient(${i}, transparent ${G(50-c-n)}%, #000 ${G(50-c)}%, #000 ${G(50+c)}%, transparent ${G(50+c+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let c=(1-Z(r))*150;return`radial-gradient(${i} at ${t}, transparent ${G(c-n)}%, #000 ${G(c)}%)`}let a=Z(r)*150;return`radial-gradient(${i} at ${t}, #000 ${G(a-n)}%, transparent ${G(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let c=r==="counterclockwise"!=!!a,l=-i+Z(s)*(360+i);if(c){let d=Math.max(0,360-l-i),p=Math.max(d,360-l);return`conic-gradient(from ${G(n)}deg at ${t}, transparent ${G(d)}deg, #000 ${G(p)}deg)`}let u=Math.max(0,l);return`conic-gradient(from ${G(n)}deg at ${t}, #000 ${G(u)}deg, transparent ${G(Math.max(u,l+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,c)=>{let l=-r+(c?1-Z(a):Z(a))*(s+r),u=Do(l,0,s),d=Do(l+r,0,s),p=`repeating-conic-gradient(from ${G(i)}deg at ${n}`;return c?`${p}, transparent 0deg, transparent ${G(u)}deg, #000 ${G(d)}deg, #000 ${G(s)}deg)`:`${p}, #000 0deg, #000 ${G(u)}deg, transparent ${G(d)}deg, transparent ${G(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,e.slats??8),i=Math.max(0,e.feather??0),r=typeof t=="number"?`${G(t)}deg`:hc(t),s=100/n;return{mask:(a,c)=>{let l=-i+(c?1-Z(a):Z(a))*(s+i),u=Do(l,0,s),d=Do(l+i,0,s);return c?`repeating-linear-gradient(${r}, transparent 0, transparent ${G(u)}%, #000 ${G(d)}%, #000 ${G(s)}%)`:`repeating-linear-gradient(${r}, #000 0, #000 ${G(u)}%, transparent ${G(d)}%, transparent ${G(s)}%)`}}}static dots(e={}){let t=Math.max(1,e.rows??6),n=Math.max(1,e.cols??10),i=Math.max(0,e.feather??20),s=Z(e.stagger??0)*.5,a=(c,l,u)=>{let d=-i+Z(l)*(100+i);return u?`radial-gradient(circle farthest-corner at ${c}, transparent ${G(d)}%, #000 ${G(d+i)}%)`:`radial-gradient(circle farthest-corner at ${c}, #000 ${G(d)}%, transparent ${G(d+i)}%)`};return{size:`${G(100/n)}% ${G(100/t)}%`,repeat:"repeat",mask:(c,l)=>{let u=l?1-Z(c):Z(c);if(s<=0)return a("50% 50%",u,l);let d=Z(u/(1-s)),p=Z((u-s)/(1-s));return l?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return mc(e.mask(t,n),e.size,e.repeat)}};var ts=class o extends We{constructor(e){super(),this.duration=e.duration,this.color=e.color??"#000000",this.hold=e.hold??.3,this.pattern=e.pattern??null,this.inverted=e.inverted??!1,this.uncover=e.uncover??"retreat",this.easing=e.easing}coverStyle(e,t){if(!this.pattern)return{...Zr(this.color),opacity:Z(e)};let n={...Zr(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...jt.toStyle(this.pattern,e,!this.inverted)}:{...n,...jt.toStyle(this.uncover,e)}:{...n,...jt.toStyle(this.pattern,e,this.inverted)}}createTask(){let t=(1-Z(this.hold))/2,n=1-t,i=.5,r=s=>s<=t?t<=0?1:s/t:s>=n?n>=1?1:(1-s)/(1-n):1;return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(s=>({style:{opacity:s<i?1:0}})),this.asTarget(s=>({style:{opacity:s<i?0:1}})),s=>({src:R.DefaultImagePlaceholder,style:this.coverStyle(r(s),s>=n)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var ns=class o extends We{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:jt.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var is=class extends Xn{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new j(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var Lo=class{static getActionId(e){return e.getId()}static setActionId(e,t){return e.setId(t),e}static getStaticId(e){return e.getStaticId()}static setStaticId(e,t){return e.setStaticId(t),e}static chainToActions(e){return e.getActions()}static wrapAction(e){let t=Ve.isChained(e)?e.getActions():e;return Ue.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return R.getSrcURLs(e,t)}static registerDisplayable(e,t,n=null,i=null){e.findElementByDisplayable(t)||(e.createDisplayable(t,n,i),e.flush())}static setElementId(e,t){e.setId(t)}static setElementStaticId(e,t){e.setStaticId(t)}static getDisplayableTransformProps(e){return{...e.transformState.get()}}static setDisplayableTransformProps(e,t,n,i={}){let r=t.transformState;i.merge===!1?r.forceOverwrite(n):r.assign(Symbol("DevTools.setDisplayableTransformProps"),n),e.getExposedState(t)?.updateStyleSync?.(),e.flush()}static getPuppetStatus(e){return e._getStatus()}static onPuppetStatusChange(e,t){return e._onStatusChange(t)}static async describePuppet(e,t){try{return await t._describe()}catch(n){return e.logger.error("DevTools","Puppet backend threw while describing itself",n),null}}static getPuppetState(e){return vt.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?vt.normalizeState(n):vt.mergeState(t.state,n),t._applyState().catch(r=>{e.logger.error("DevTools","Puppet backend threw while applying state",r)}),e.flush()}static async runPuppetCommand(e,t,n,i){try{await t._runCommand(n,i)||e.logger.weakWarn("DevTools",`Puppet command "${n}" was dropped: the puppet is not mounted.`)}catch(r){e.logger.error("DevTools",`Puppet backend threw while running "${n}"`,r)}}static listPuppetBackends(e){return e.listPuppetBackends()}static getCurrentDialog(e){if(e.isNvlMode()){let n=e.getNvlState();if(!n.activeDialogId||n.phase==="idle")return null;let i=e.getNvlDialog(n.activeDialogId);return i?{actionId:i.actionId||null,ended:n.phase==="awaitAdvance",mode:"nvl"}:null}let t=e.getAdvDialogState();return t?{actionId:t.actionId,ended:t.ended,mode:"adv"}:null}static onDialogStateChange(e,t){let n=[e.events.on(I.EventTypes["event:state.dialog.change"],t),e.events.on(I.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};Lo.DynamicPersistent=Cn;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
80
+ at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},P=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Fe=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function Gp(o,e){return Z.color(o,e)}function Vp(o){return Z.bold(o)}function Hp(o){return Z.italic(o)}var ss=class o extends je{constructor(e){super(),this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(e=>({style:{opacity:1-e}})),this.asTarget(e=>({style:{opacity:e}}))]}}copy(){return new o({duration:this.duration,easing:this.easing})}};var as=class o extends je{constructor(e){super(),this.duration=e.duration,this.offset=e.offset??[0,0],this.easing=e.easing}createTask(e){let{invertX:t,invertY:n}=e.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.offset[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.offset[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((i,r,s)=>({style:{opacity:i,translate:`${t?-r:r}px ${n?-s:s}px`}}))]}}copy(){return new o({duration:this.duration,offset:this.offset,easing:this.easing})}};function ee(o){return o<0?0:o>1?1:o}function xc(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function cs(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function Cc(o){switch(o){case"left":return"to left";case"top":return"to top";case"bottom":return"to bottom";case"right":default:return"to right"}}function wc(o){return o==="vertical"?"to right":"to bottom"}var ls=class o extends je{constructor(e){super(),this.duration=e.duration,this.blur=e.blur??16,this.easing=e.easing}createTask(){let e=Math.max(0,this.blur);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-ee(t),filter:`blur(${e*ee(t)}px)`}})),this.asTarget(t=>({style:{opacity:ee(t),filter:`blur(${e*(1-ee(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var us=class o extends je{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*ee(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-ee(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};function N(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function Go(o,e,t){return o<e?e:o>t?t:o}var Yt=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${N(t)}deg`:Cc(t);return{mask:(r,s)=>{let a=-n+(s?1-ee(r):ee(r))*(100+n);return s?`linear-gradient(${i}, transparent ${N(a)}%, #000 ${N(a+n)}%)`:`linear-gradient(${i}, #000 ${N(a)}%, transparent ${N(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${N(t)}deg`,`${N(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let c=-n+ee(s)*(50+n);if(!a){let l=u=>`linear-gradient(${u}, #000 ${N(c)}%, transparent ${N(c+n)}%)`;return`${l(i)}, ${l(r)}`}if(c<0){let l=ee((c+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${N(50-c-n)}%, rgba(0,0,0,${N(l)}) 50%, transparent ${N(50+c+n)}%)`}return`linear-gradient(${i}, transparent ${N(50-c-n)}%, #000 ${N(50-c)}%, #000 ${N(50+c)}%, transparent ${N(50+c+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let c=(1-ee(r))*150;return`radial-gradient(${i} at ${t}, transparent ${N(c-n)}%, #000 ${N(c)}%)`}let a=ee(r)*150;return`radial-gradient(${i} at ${t}, #000 ${N(a-n)}%, transparent ${N(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let c=r==="counterclockwise"!=!!a,l=-i+ee(s)*(360+i);if(c){let d=Math.max(0,360-l-i),p=Math.max(d,360-l);return`conic-gradient(from ${N(n)}deg at ${t}, transparent ${N(d)}deg, #000 ${N(p)}deg)`}let u=Math.max(0,l);return`conic-gradient(from ${N(n)}deg at ${t}, #000 ${N(u)}deg, transparent ${N(Math.max(u,l+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,c)=>{let l=-r+(c?1-ee(a):ee(a))*(s+r),u=Go(l,0,s),d=Go(l+r,0,s),p=`repeating-conic-gradient(from ${N(i)}deg at ${n}`;return c?`${p}, transparent 0deg, transparent ${N(u)}deg, #000 ${N(d)}deg, #000 ${N(s)}deg)`:`${p}, #000 0deg, #000 ${N(u)}deg, transparent ${N(d)}deg, transparent ${N(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,e.slats??8),i=Math.max(0,e.feather??0),r=typeof t=="number"?`${N(t)}deg`:wc(t),s=100/n;return{mask:(a,c)=>{let l=-i+(c?1-ee(a):ee(a))*(s+i),u=Go(l,0,s),d=Go(l+i,0,s);return c?`repeating-linear-gradient(${r}, transparent 0, transparent ${N(u)}%, #000 ${N(d)}%, #000 ${N(s)}%)`:`repeating-linear-gradient(${r}, #000 0, #000 ${N(u)}%, transparent ${N(d)}%, transparent ${N(s)}%)`}}}static dots(e={}){let t=Math.max(1,e.rows??6),n=Math.max(1,e.cols??10),i=Math.max(0,e.feather??20),s=ee(e.stagger??0)*.5,a=(c,l,u)=>{let d=-i+ee(l)*(100+i);return u?`radial-gradient(circle farthest-corner at ${c}, transparent ${N(d)}%, #000 ${N(d+i)}%)`:`radial-gradient(circle farthest-corner at ${c}, #000 ${N(d)}%, transparent ${N(d+i)}%)`};return{size:`${N(100/n)}% ${N(100/t)}%`,repeat:"repeat",mask:(c,l)=>{let u=l?1-ee(c):ee(c);if(s<=0)return a("50% 50%",u,l);let d=ee(u/(1-s)),p=ee((u-s)/(1-s));return l?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return xc(e.mask(t,n),e.size,e.repeat)}};var ps=class o extends je{constructor(e){super(),this.duration=e.duration,this.color=e.color??"#000000",this.hold=e.hold??.3,this.pattern=e.pattern??null,this.inverted=e.inverted??!1,this.uncover=e.uncover??"retreat",this.easing=e.easing}coverStyle(e,t){if(!this.pattern)return{...cs(this.color),opacity:ee(e)};let n={...cs(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...Yt.toStyle(this.pattern,e,!this.inverted)}:{...n,...Yt.toStyle(this.uncover,e)}:{...n,...Yt.toStyle(this.pattern,e,this.inverted)}}createTask(){let t=(1-ee(this.hold))/2,n=1-t,i=.5,r=s=>s<=t?t<=0?1:s/t:s>=n?n>=1?1:(1-s)/(1-n):1;return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(s=>({style:{opacity:s<i?1:0}})),this.asTarget(s=>({style:{opacity:s<i?0:1}})),s=>({src:L.DefaultImagePlaceholder,style:this.coverStyle(r(s),s>=n)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var ds=class o extends je{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:Yt.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var ms=class extends Zn{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new j(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var Vo=class{static getActionId(e){return e.getId()}static setActionId(e,t){return e.setId(t),e}static getStaticId(e){return e.getStaticId()}static setStaticId(e,t){return e.setStaticId(t),e}static chainToActions(e){return e.getActions()}static wrapAction(e){let t=Oe.isChained(e)?e.getActions():e;return We.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return L.getSrcURLs(e,t)}static registerDisplayable(e,t,n=null,i=null){e.findElementByDisplayable(t)||(e.createDisplayable(t,n,i),e.flush())}static setElementId(e,t){e.setId(t)}static setElementStaticId(e,t){e.setStaticId(t)}static getDisplayableTransformProps(e){return{...e.transformState.get()}}static setDisplayableTransformProps(e,t,n,i={}){let r=t.transformState;i.merge===!1?r.forceOverwrite(n):r.assign(Symbol("DevTools.setDisplayableTransformProps"),n),t.markDirty(),e.getExposedState(t)?.updateStyleSync?.(),e.flush()}static getPuppetStatus(e){return e._getStatus()}static onPuppetStatusChange(e,t){return e._onStatusChange(t)}static async describePuppet(e,t){try{return await t._describe()}catch(n){return e.logger.error("DevTools","Puppet backend threw while describing itself",n),null}}static getPuppetState(e){return At.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?At.normalizeState(n):At.mergeState(t.state,n),t._applyState().catch(r=>{e.logger.error("DevTools","Puppet backend threw while applying state",r)}),e.flush()}static async runPuppetCommand(e,t,n,i){try{await t._runCommand(n,i)||e.logger.weakWarn("DevTools",`Puppet command "${n}" was dropped: the puppet is not mounted.`)}catch(r){e.logger.error("DevTools",`Puppet backend threw while running "${n}"`,r)}}static listPuppetBackends(e){return e.listPuppetBackends()}static getCurrentDialog(e){if(e.isNvlMode()){let n=e.getNvlState();if(!n.activeDialogId||n.phase==="idle")return null;let i=e.getNvlDialog(n.activeDialogId);return i?{actionId:i.actionId||null,ended:n.phase==="awaitAdvance",mode:"nvl"}:null}let t=e.getAdvDialogState();return t?{actionId:t.actionId,ended:t.ended,mode:"adv"}:null}static onDialogStateChange(e,t){let n=[e.events.on(E.EventTypes["event:state.dialog.change"],t),e.events.on(E.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};Vo.DynamicPersistent=En;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
79
81
  @layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.isolate{isolation:isolate}.z-20{z-index:20}.container{width:100%}.\\!hidden{display:none!important}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow,.grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.mask-repeat{-webkit-mask-repeat:repeat;mask-repeat:repeat}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.ordinal{--tw-ordinal:ordinal;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-filter{backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}\r
80
- `,document.head.appendChild(o)}export{an as Align,Jt as AudioBusError,Kn as AudioBusMixer,On as AudioBusTree,dr as Avatar,_r as BlurDissolve,qn as Camera,Fi as Character,it as CommonPosition,Sn as CommonPositionType,jo as Condition,Ue as Control,lt as Coord2D,pi as Darkness,Ye as DefaultAudioBusIds,xr as DefaultNvlContainer,wa as DefaultNvlDialogItem,Lo as DevTools,gu as Dialog,Jr as Dissolve,hp as ExposedStateType,Yr as FadeIn,Ta as FixedAspectRatioContainer,is as Gallery,ie as Game,Zi as GameMenu,cc as GameProviders,I as GameState,R as Image,We as ImageTransition,Rt as Isolated,co as Item,Dn as KeyBindingType,ui as KeyMap,j as Lambda,kn as Layer,Wl as Layout,oi as LayoutRouterProvider,Pt as LiveGame,jt as Mask,Ii as MaxAudioBusDepth,qo as Menu,jn as NVLToken,kt as Namespace,Wt as Nametag,Kt as Narrator,uo as Notifications,Ar as NvlContainer,fu as NvlDialogList,Tr as NvlProvider,Ql as Page,hr as PageInjectContext,Fe as Pause,xn as Persistent,ac as Player,Yn as Preference,vt as Puppet,es as Push,ns as Reveal,$s as RootPath,ut as Scene,Ce as Script,ks as SeededBusPreferenceKeys,Se as Sentence,Xn as Service,Ae as Sound,Es as SoundType,qc as Stage,Hn as Storable,Qn as Story,ln as Text,ot as TextEvent,Bn as TextTransition,hl as Texts,dl as TextsPreview,ts as ThroughColor,Y as Transform,Et as Transition,Yo as Vfx,Jo as Video,J as Word,Ri as acceptsAudioBus,xp as b,Ap as c,Wo as getActiveAudioBusTree,Cp as i,da as useAvatar,Dl as useDialog,M as useGame,cu as useIsNvlMode,lu as useIsNvlVisible,mn as useKeyBinding,nu as useLiveGame,Gt as useNvl,Sr as useNvlDialogs,Fl as useParams,Vl as usePathname,on as usePreference,Hl as useQueryParams,It as useRouter,cr as useUIMenuContext,Rl as useVoiceState};
82
+ `,document.head.appendChild(o)}export{pn as Align,_t as AudioBusError,$n as AudioBusMixer,zn as AudioBusTree,Ar as Avatar,ls as BlurDissolve,Yn as Camera,Ki as Character,st as CommonPosition,xn as CommonPositionType,Zo as Condition,We as Control,dt as Coord2D,hi as Darkness,tt as DefaultAudioBusIds,Mr as DefaultNvlContainer,Ga as DefaultNvlDialogItem,Vo as DevTools,Du as Dialog,ss as Dissolve,Ep as ExposedStateType,as as FadeIn,La as FixedAspectRatioContainer,ms as Gallery,re as Game,io as GameMenu,vc as GameProviders,E as GameState,L as Image,je as ImageTransition,Vt as Isolated,ho as Item,Mn as KeyBindingType,fi as KeyMap,j as Lambda,Ln as Layer,nu as Layout,ci as LayoutRouterProvider,It as LiveGame,Yt as Mask,Vi as MaxAudioBusDepth,_o as Menu,Xn as NVLToken,Lt as Namespace,qt as Nametag,$t as Narrator,yo as Notifications,Rr as NvlContainer,Pu as NvlDialogList,Lr as NvlProvider,au as Page,wr as PageInjectContext,Be as Pause,Pn as Persistent,yc as Player,ei as Preference,At as Puppet,us as Push,ds as Reveal,ta as RootPath,mt as Scene,Ce as Script,Vs as SeededBusPreferenceKeys,Se as Sentence,Zn as Service,Ae as Sound,Fs as SoundType,il as Stage,Kn as Storable,Jn as Story,mn as Text,at as TextEvent,jn as TextTransition,El as Texts,wl as TextsPreview,ps as ThroughColor,_ as Transform,Rt as Transition,ir as Vfx,nr as Video,Z as Word,Hi as acceptsAudioBus,Vp as b,Gp as c,Xo as getActiveAudioBusTree,Hp as i,Aa as useAvatar,Kl as useDialog,I as useGame,bu as useIsNvlMode,Au as useIsNvlVisible,yn as useKeyBinding,hu as useLiveGame,Ut as useNvl,Dr as useNvlDialogs,Yl as useParams,Xl as usePathname,cn as usePreference,Jl as useQueryParams,Gt as useRouter,vr as useUIMenuContext,$l as useVoiceState};