narraleaf-react 0.14.0 → 0.16.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.
Files changed (45) hide show
  1. package/dist/game/nlcore/action/actionTypes.d.ts +16 -2
  2. package/dist/game/nlcore/action/actions/controlAction.d.ts +2 -0
  3. package/dist/game/nlcore/action/actions/vfxAction.d.ts +24 -0
  4. package/dist/game/nlcore/action/logicAction.d.ts +16 -13
  5. package/dist/game/nlcore/action/stackModel.d.ts +28 -0
  6. package/dist/game/nlcore/common/elements.d.ts +6 -1
  7. package/dist/game/nlcore/common/game.d.ts +2 -1
  8. package/dist/game/nlcore/common/transition.d.ts +8 -9
  9. package/dist/game/nlcore/elements/camera.d.ts +71 -0
  10. package/dist/game/nlcore/elements/character/sentence.d.ts +2 -1
  11. package/dist/game/nlcore/elements/character/textEvent.d.ts +67 -0
  12. package/dist/game/nlcore/elements/character/word.d.ts +2 -1
  13. package/dist/game/nlcore/elements/control.d.ts +62 -0
  14. package/dist/game/nlcore/elements/displayable/image.d.ts +2 -2
  15. package/dist/game/nlcore/elements/scene.d.ts +2 -2
  16. package/dist/game/nlcore/elements/story.d.ts +21 -1
  17. package/dist/game/nlcore/elements/transition/transitions/image/darkness.d.ts +16 -9
  18. package/dist/game/nlcore/elements/transition/transitions/image/dissolve.d.ts +9 -6
  19. package/dist/game/nlcore/elements/transition/transitions/image/fadeIn.d.ts +9 -8
  20. package/dist/game/nlcore/elements/transition/transitions/image/mask.d.ts +162 -0
  21. package/dist/game/nlcore/elements/transition/transitions/image/reveal.d.ts +33 -0
  22. package/dist/game/nlcore/elements/transition/transitions/image/throughColor.d.ts +34 -36
  23. package/dist/game/nlcore/elements/transition/transitions/image/transitionMaskUtils.d.ts +5 -16
  24. package/dist/game/nlcore/elements/transition/transitions/text/fontSize.d.ts +9 -2
  25. package/dist/game/nlcore/elements/vfx.d.ts +85 -0
  26. package/dist/game/nlcore/elements/video.d.ts +26 -0
  27. package/dist/game/nlcore/game/liveGame.d.ts +44 -5
  28. package/dist/game/player/elements/menu/type.d.ts +3 -2
  29. package/dist/game/player/elements/nvl/type.d.ts +2 -1
  30. package/dist/game/player/elements/nvl/useNvlDialogState.d.ts +2 -1
  31. package/dist/game/player/elements/player/Camera.d.ts +1 -0
  32. package/dist/game/player/elements/say/Sentence.d.ts +3 -2
  33. package/dist/game/player/elements/say/UIDialog.d.ts +2 -1
  34. package/dist/game/player/elements/say/textEventEffect.d.ts +19 -0
  35. package/dist/game/player/elements/say/type.d.ts +4 -3
  36. package/dist/game/player/elements/scene/SceneDialogs.d.ts +1 -0
  37. package/dist/game/player/elements/vfx/Vfx.d.ts +1 -0
  38. package/dist/game/player/gameState.d.ts +8 -0
  39. package/dist/game/player/type.d.ts +20 -1
  40. package/dist/main.js +44 -42
  41. package/package.json +1 -1
  42. package/dist/game/nlcore/elements/transition/transitions/image/blinds.d.ts +0 -28
  43. package/dist/game/nlcore/elements/transition/transitions/image/maskTransition.d.ts +0 -38
  44. package/dist/game/nlcore/elements/transition/transitions/image/softIris.d.ts +0 -28
  45. package/dist/game/nlcore/elements/transition/transitions/image/softWipe.d.ts +0 -28
package/dist/main.js CHANGED
@@ -1,69 +1,71 @@
1
- var Ee={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},en={say:"character:say",action:"character:action",setName:"character:setName"},$={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 Je={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},xr={action:"condition:action"},wr={action:"script:action"},kr={action:"menu:action"},kt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute"},xe={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"},Yn={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},Tn={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},Wt={action:"layer:action",setZIndex:"layer:setZIndex"},tn={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"};var Pr=(d=>(d[d.string=0]="string",d[d.number=1]="number",d[d.boolean=2]="boolean",d[d.object=3]="object",d[d.array=4]="array",d[d.function=5]="function",d[d.symbol=6]="symbol",d[d.undefined=7]="undefined",d[d.null=8]="null",d[d.date=9]="date",d[d.regexp=10]="regexp",d[d.other=11]="other",d))(Pr||{}),ro=(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});ro.DataTypes=Pr;function K(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,c)=>ro(a)===3&&ro(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:K(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]=K({},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 K(i,s,...a)}return i}var He=class He{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=so()}static isAwaitable(e){return e instanceof He}static fromPromise(e){let t=new He;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new He;return t.resolve(e),t}static delay(e){let t=new He;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new He;return e(t),t}static wait(e){let t=new He;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new He;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 U(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new He().registerSkipController(n||new U(()=>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 He;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 U(()=>{e.forEach(n=>n.abort())})),t)}static all(...e){let t=new He;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 U(()=>{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>=He.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>=He.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()}}};He.nothing=e=>e,He.maxListeners=8;var y=He;function Er(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 on(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 Y=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 so(o=1){let e=new Error().stack;return e?e.split(`
1
+ var De={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},an={say:"character:say",action:"character:action",setName:"character:setName"},q={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 _e={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},Mr={action:"condition:action"},Nr={action:"script:action"},Gr={action:"menu:action"},It={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute"},Z={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"},oi={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},kn={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},Qt={action:"layer:action",setZIndex:"layer:setZIndex"},yt={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"},Ft={action:"vfx:action",show:"vfx:show",hide:"vfx:hide",pause:"vfx:pause",resume:"vfx:resume",setRate:"vfx:setRate"};var Hr=(d=>(d[d.string=0]="string",d[d.number=1]="number",d[d.boolean=2]="boolean",d[d.object=3]="object",d[d.array=4]="array",d[d.function=5]="function",d[d.symbol=6]="symbol",d[d.undefined=7]="undefined",d[d.null=8]="null",d[d.date=9]="date",d[d.regexp=10]="regexp",d[d.other=11]="other",d))(Hr||{}),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=Hr;function W(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:W(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]=W({},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 W(i,s,...a)}return i}var Ue=class Ue{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=go()}static isAwaitable(e){return e instanceof Ue}static fromPromise(e){let t=new Ue;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new Ue;return t.resolve(e),t}static delay(e){let t=new Ue;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new Ue;return e(t),t}static wait(e){let t=new Ue;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new Ue;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 F(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new Ue().registerSkipController(n||new F(()=>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 Ue;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 F(()=>{e.forEach(n=>n.abort())})),t)}static all(...e){let t=new Ue;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 F(()=>{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>=Ue.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>=Ue.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()}}};Ue.nothing=e=>e,Ue.maxListeners=8;var S=Ue;function Vr(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 ln(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 te=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 go(o=1){let e=new Error().stack;return e?e.split(`
2
2
  `).slice(o+1).join(`
3
- `).trim():""}function ii(o){return new Promise(e=>setTimeout(e,o))}var ni=class ni{constructor(e){this.abortHandler=e;this.events=new Y;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(ni.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};ni.EventTypes={"event:skipController.abort":"event:skipController.abort"};var U=ni;var bn=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}},nn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new bn;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 oi(o,e,t={}){return o?e:t}function Dr(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var Jn=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 Lr(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 Ir(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 Cn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}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())),await ii(this.delay),await e()};await e()}};function je(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Rr(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var $e=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 Mr(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 Nr(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function ao(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function co(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"&&!co(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Zn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function ri(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 Gr(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var _n=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},ei=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 ti=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 Hr(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 Fr(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,p=s*c+(u>>>0)>>>0;e=l,t=p}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var An=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=so(),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]:[]}};An.ActionTypes={action:"action"};var j=class extends An{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 y(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 lo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},A=class o extends lo{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 si={center:"center",left:"left",right:"right"};import{animate as Ta}from"motion/react";var xn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(xn||{}),Ur={left:"33.33%",center:"50%",right:"66.66%"},Ze=class Ze{static isUnknown(e){return e===Ze.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||Ze.isUnknown(e))return"auto";let i=!(t===void 0||Ze.isUnknown(t));if(typeof n=="number"&&n>0){let s=Ze.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(nt.isCommonPositionType(e))return _e.fromCommonPosition(e);if(_e.isCoord2DPosition(e))return e;if(zt.isAlignPosition(e))return _e.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 Ze.isUnknown(e)||e===void 0?Ze.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return _e.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Ze.isUnknown(t.x)?0:t.x,y:Ze.isUnknown(t.y)?0:t.y,xoffset:Ze.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Ze.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 nt||e instanceof _e||e instanceof zt}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return _e.fromCommonPosition(new nt(e));if(this.isRawAlignPosition(e))return _e.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new _e(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}}};Ze.Unknown=Symbol("Unknown");var M=Ze,ai=class ai{static isCommonPositionType(e){return e instanceof ai}constructor(e){this.position=e}toCSS(){return{x:Ur[this.position],y:"50%",xoffset:0,yoffset:0}}};ai.Positions=xn;var nt=ai,_e=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:Ur[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||M.isUnknown(n)?M.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:M.isUnknown(t.x)?e.x:t.x,y:M.isUnknown(t.y)?e.y:t.y,xoffset:M.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:M.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=M.orUnknown(e.x),this.y=M.orUnknown(e.y),this.xoffset=M.orUnknown(e.xoffset),this.yoffset=M.orUnknown(e.yoffset)):(this.x=M.orUnknown(e),this.y=M.orUnknown(t),this.xoffset=M.Unknown,this.yoffset=M.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}}},zt=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=M.orUnknown(e.xalign),this.yalign=M.orUnknown(e.yalign),this.xoffset=M.orUnknown(e.xoffset),this.yoffset=M.orUnknown(e.yoffset)):(this.xalign=M.orUnknown(e),this.yalign=M.orUnknown(t),this.xoffset=M.Unknown,this.yoffset=M.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:M.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:M.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var J=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new uo(this.mergeWithDefaultConfig(e))}copy(){return new o(K({},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)?K({},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}},uo=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(K({},this.config))}join(e){let t=Rr(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 ba={[si.left]:"25.33%",[si.center]:"50%",[si.right]:"75.66%"},rt=class rt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new rt(rt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?M.toCoord2D(M.tryParsePosition(e||t)):M.mergePosition(M.tryParsePosition(e),M.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=rt.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 ao(Z.constructStyle(e,this.state,t))}toStyle(e,t){return ao(Z.constructStyle(e,this.state,t))}serialize(){return rt.TransformStateSerializer.serialize(this.state)}clone(){return new rt(rt.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=rt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};rt.DefaultTransformState=new J({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new nt("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}),rt.TransformStateSerializer=new $e({position:e=>M.serializePosition(M.tryParsePosition(e))},{position:e=>M.toCoord2D(e)});var Ce=rt,be=class be{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},be.defaultConfig,t||{});else{let[n,i]=[e,t||be.defaultOptions];this.sequences.push({props:n,options:i||be.defaultOptions}),this.config=Object.assign({},be.defaultConfig)}}static isPosition(e){return nt.isCommonPositionType(e)||_e.isCoord2DPosition(e)||zt.isAlignPosition(e)}static immediate(e){return new be(e,{duration:0,ease:"linear"})}static left(e,t){return new be({position:nt.Positions.Left},{duration:e,ease:t})}static right(e,t){return new be({position:nt.Positions.Right},{duration:e,ease:t})}static center(e,t){return new be({position:nt.Positions.Center},{duration:e,ease:t})}static create(e){return new be([],e)}static positionToCSS(e,t,n,i){return e?M.isRawPosition(e)?M.D2PositionToCSS(M.rawPositionToCoord2D(e),n,t,i):M.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?M.toCoord2D(M.tryParsePosition(e||t)):M.mergePosition(M.tryParsePosition(e),M.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...K(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(d,g,h){return typeof d>"u"?typeof h<"u"?g(h):"":g(d)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,d=>`rotate(${d}deg)`,0),c(t.scaleX,d=>`scaleX(${d*a})`,1),c(t.scaleY,d=>`scaleY(${d*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{...be.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?on(t.fontColor):void 0,transform:be.propToCSSTransform(e,t),...be.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=Ta(s,a),p=()=>{e.overwrite(l,r.get()).unlock(l),u.complete(),c=!0},d=new y().registerSkipController(new U(p)),g=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),d.resolve()};return u.then(g,(h=>{t.logger.error("Failed to animate transform. "+(h?.toString?.()||""));try{g()}catch{d.resolve()}})),u.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),d}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...be.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 be(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 me("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 me("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};be.defaultConfig={sync:!0},be.defaultOptions={duration:0,ease:"linear"},be.CommonImagePositionMap=ba;var Z=be;var ci=class{constructor(){this.id=""}setId(e){this.id=e}getId(){return this.id}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 Or=Symbol("_Chained"),Kr;Kr=Or;var po=class po{constructor(e){this[Kr]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Or]}static toActions(e){return e.flat(2).map(t=>po.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()}},De=po,rn=class extends ci{chain(e){let t=De.isChained(this)?this:this.proxy(this,new De(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 ce=class extends rn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var dt=class extends j{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=xr;var mt=class o{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(o.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(o.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=K({},t),this.defaultContent=t}set(e,t){return o.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
4
- at namespace "${this.name}"`),this.content[e]=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(){return this.content=K({},this.defaultContent),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)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)})}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e){let t={any:i=>({type:"any",data:i}),date:i=>({type:"date",data:i.toString()})},n=this.toTypeName(e);return t[n](e)}unwrap(e){return{any:n=>n.data,date:n=>new Date(n.data)}[e.type](e)}},wn=class{constructor(){this.namespaces={}}static createNamespace(e,t,n){return new mt(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,this}getNamespace(e){if(!this.namespaces[e])throw new E(`Namespace ${e} is not initialized, did you forget to register it?
5
- Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return 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)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]||(this.namespaces[t]=new mt(t,{})),this.namespaces[t].deserialize(n)})}clear(){return this.namespaces={},this}};var qe=class extends j{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===kt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.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===kt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.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===kt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=y.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===kt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.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===kt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.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===kt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.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===kt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=y.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")}};qe.ActionTypes=kt;var Nt=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Nt||{}),ve=class ve extends ce{static toSound(e){return e==null?null:typeof e=="string"?new ve({src:e}):e}static isSound(e){return e instanceof ve}static voice(e){let t=typeof e=="string"?{src:e}:e;return new ve({...t,type:"voice"})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new ve({...t,type:"bgm"})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new ve({...t,type:"sound"})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=ve.DefaultUserConfig.create(t),[i]=n.extract(ve.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){if(this.config.type==="bgm")throw new we(`Sound (src: ${this.config.src}) is marked as bgm, but it is being played as a normal sound.
6
- To prevent unintended behavior, the sound marked as bgm cannot be played using \`play()\`.`);return this.pushAction(qe.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(qe.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(qe.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(qe.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(qe.ActionTypes.setRate,[e])}pause(e){return this.pushAction(qe.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(qe.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}getSrc(){return this.config.src}toData(){return{state:ve.StateSerializer.serialize(this.state)}}fromData(e){return this.state=ve.StateSerializer.deserialize(e.state),this}copy(){return new ve(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return ve.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new qe(this.chain(),e,new A().setContent(t)))}};ve.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",ve.DefaultUserConfig=new J({src:ve.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,type:"sound"}),ve.DefaultConfig=new J({src:ve.noSound,loop:!1,streaming:!1,seek:0,type:"sound"}),ve.DefaultState=new J({volume:1,rate:1,paused:!1,muted:!1}),ve.StateSerializer=new $e;var fe=ve;var Vr=2;var lp={};var sn=class extends rn{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 Bt=class Bt{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===Bt.SrcTypes.image?t.add(s):r===Bt.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(ee,$.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(w.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof le){let n=t;if(t.is(le,Je.setSrc)){let i=t.contentNode.getContent()[0];if(w.isImageSrc(i))return{type:"image",src:w.srcToURL(i),activeType:"scene"}}else{if(t.type===Je.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===Je.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 fe){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof R||w.isStaticImageData(e)){if(e instanceof R){if(!w.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(R.getSrcURL(e)))return this}else if(this.isSrcRegistered(w.srcToURL(e.src)))return this;this.src.push({type:"image",src:w.isStaticImageData(e)?w.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 fe?t:new fe({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 fe?e.getSrc():e;return this.src.some(n=>n.type===Bt.SrcTypes.audio?t===n.src.getSrc():n.type===Bt.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)}};Bt.SrcTypes={image:"image",video:"video",audio:"audio"};var Fe=Bt;var Gt=class extends j{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Yn.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===Yn.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")}};Gt.ActionTypes=Yn;var Le=class extends j{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 y().registerSkipController(new U(()=>(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),p=e.timelines.attachTimeline(s).attachChild(u);return u.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:p},d=>{s.isSettled()||s.abort(),u.abort(),t.transformState.forceOverwrite(d.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new y().registerSkipController(new U(()=>(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 y().registerSkipController(new U(()=>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")}};Le.ActionTypes=Ee;var ft=class o extends ce{constructor(){super(...arguments);this.srcManager=new Fe}pos(t,n,i){return this.transform(new Z({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new Z({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new Z({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new Z({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new Z({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 Z({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new Z({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new Z(t,n))}mask(t,n={}){let i=w.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},p=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Ie,d=>d.transform(p).clearClip({duration:0})):this.transform(p)}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},p=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Ie,d=>d.transform(p).clearClip({duration:0})):this.transform(p)}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),p=o.wipeClipPath(n,0),d=o.createClipPathTransform([[i?p:u,{duration:0}],[i?u:p,l]]);return r?this.combineActions(new Ie,g=>g.transform(d).clearClip({duration:0})):this.transform(d)}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 Le(n,Ee.applyTransform,new A().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 Z(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 Z?t.copy():new Z({opacity:1},t),r=new Le(n,Ee.applyTransform,new A().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof Z?t.copy():new Z({opacity:0},t),r=new Le(n,Ee.applyTransform,new A().setContent([i]));return n.chain(r)}};var Qe=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(Qe||{});import{animate as Ca}from"motion/react";var ht=class{requestAnimations(e){let t=e.map(v=>v.start),n=[],i=0,r=!1,s=!1,a=!1,c=[],l=[],u=[],p=()=>{e.forEach((v,f)=>{t[f]=v.end}),i=e.length,c.forEach(v=>v(t)),l.forEach(v=>v())};return{onUpdate:v=>(c.push(v),{cancel:()=>{let f=c.indexOf(v);f!==-1&&c.splice(f,1)}}),onComplete:v=>(l.push(v),{cancel:()=>{let f=l.indexOf(v);f!==-1&&l.splice(f,1)}}),onCanceled:v=>(u.push(v),{cancel:()=>{let f=u.indexOf(v);f!==-1&&u.splice(f,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(v=>v.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){p();return}e.forEach((v,f)=>{n.push(this.requestMotion(v,{onComplete:()=>{t[f]=v.end,c.forEach(T=>T(t)),i++,i===e.length&&l.forEach(T=>T())},onUpdate:T=>{t[f]=T,c.forEach(m=>m(t))}}))})}},cancel:()=>{s=!0,n.forEach(v=>v.cancel()),u.forEach(v=>v())}}}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 Ca(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};ht.AnimationType=Qe;var kn=class extends ht{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new E(`Trying to access text state, but element is not set
7
- This should not happen, please report this issue to the developers`);return this._element.state}};var li=class o extends kn{constructor(t,n,i){super();this.textSize=t;this.duration=n;this.easing=i}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.textSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{fontSize:`${t}px`}}))]}}copy(){return new o(this.textSize,this.duration,this.easing)}};var Xe=class Xe extends ft{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=Xe.DefaultUserConfig.create(n),r=Xe.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 Gt(t,Gt.ActionTypes.setText,new A().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new Z({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Ie,i=>{if(t){let s=new li(e,t,n);i.chain(this._applyTransition(i,s))}let r=new Gt(i,Gt.ActionTypes.setFontSize,new A().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:Xe.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=Xe.StateSerializer.deserialize(e.state),this.transformState=Ce.deserialize(e.transformState),this}_init(e){return new Le(this.chain(),Ee.init,new A().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(Xe.DefaultTextTransformState.keys());return new Ce(Xe.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Le(e,Ee.applyTransition,new A().setContent([t,n=>n._setElement(this)]))}getInitialState(){return Xe.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};Xe.DefaultUserConfig=new J({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:""}),Xe.DefaultTextConfig=new J({alignX:"center",alignY:"center",className:"",layer:void 0}),Xe.DefaultTextState=new J({fontSize:16,display:!1,text:""}),Xe.DefaultTextTransformState=new J({fontColor:"#000000",...Ce.DefaultTransformState.getDefaultConfig()}),Xe.StateSerializer=new $e;var $t=Xe;var Pn=class Pn extends j{executeAction(e,t){let n=this;if(n.is(Pn,"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(Pn,"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")}};Pn.ActionTypes=Tn;var ui=Pn;var Re=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 Me=class Me{static isWord(e){return e instanceof Me}static color(e,t){return Me.isWord(e)?e.copy().assign({color:t}):new Me(e,{color:t})}static bold(e){return Me.isWord(e)?e.copy().assign({bold:!0}):new Me(e,{bold:!0})}static italic(e){return Me.isWord(e)?e.copy().assign({italic:!0}):new Me(e,{italic:!0})}static getText(e){return e.filter(t=>!t.isPause()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=K(Me.defaultConfig,t)}evaluate(e){if(Re.isPause(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Me.isWord(n)?n.inherit(this.config).evaluate(e):new Me(n,this.config)).flat():Me.isWord(t)?t.inherit(this.config).evaluate(e):[new Me(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=K(this.config,e),this}copy(){return new Me(this.text,this.config)}isPause(){return Re.isPause(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Me.defaultConfig={},Me.defaultColor="#000";var q=Me;var Ye=class Ye{static isSentence(e){return e instanceof Ye}static toSentence(e){return Ye.isSentence(e)?e:new Ye(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 q.isWord(e)?e:new q(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[q.isWord(e)?e:new q(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(Ye.isSingleWord):Ye.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||q.isWord(e)||Re.isPause(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=Ye.format(e),this.config=K(Ye.defaultConfig,{...t,voice:typeof t.voice=="string"?fe.voice(t.voice):fe.toSound(t.voice)}),this.state=Er(Ye.defaultState)}toData(){return null}fromData(e){return this.state=K(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(...Ye.formatStaticWord(i))}return t}copy(){return new Ye([...this.text],this.config)}};Ye.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},Ye.defaultState={};var pe=Ye;var Ht=class extends j{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")}};Ht.ActionTypes=wr;var Se=class o extends ce{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 Ht(t,Ht.ActionTypes.action,new A().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new Ht(this.chain(),Ht.ActionTypes.action,new A().setContent(e))]}};var pi=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 ke=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()}),je(()=>{this.preventAttach()})}static proxy(e){let t=new y,n=new y,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 E("Cannot create an 'any' timeline with no awaitables.");let t=new y,n=new y,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 E("Cannot create an 'all' timeline with no awaitables.");let t=new y,n=new y,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 y,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?je(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new U(()=>(i&&i.abort(),t))),i=e(t),i?je(()=>s()):je(()=>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()?je(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 E(`Attaching to this timeline violates the timeline's state.
3
+ `).trim():""}function pi(o){return new Promise(e=>setTimeout(e,o))}var ui=class ui{constructor(e){this.abortHandler=e;this.events=new te;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(ui.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};ui.EventTypes={"event:skipController.abort":"event:skipController.abort"};var F=ui;var En=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}},cn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new En;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 di(o,e,t={}){return o?e:t}function Fr(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var ri=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 Ur(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 Or(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 Pn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}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())),await pi(this.delay),await e()};await e()}};function qe(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Kr(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var je=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 Wr(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 zr(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function yo(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function vo(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"&&!vo(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 mi(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 $r(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var ai=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},ci=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 li=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 Br(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 jr(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,p=s*c+(u>>>0)>>>0;e=l,t=p}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Dn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=go(),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]:[]}};Dn.ActionTypes={action:"action"};var B=class extends Dn{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 S(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 So=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},x=class o extends So{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 fi={center:"center",left:"left",right:"right"};import{animate as Na}from"motion/react";var un=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(un||{}),qr={left:"33.33%",center:"50%",right:"66.66%"},et=class et{static isUnknown(e){return e===et.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||et.isUnknown(e))return"auto";let i=!(t===void 0||et.isUnknown(t));if(typeof n=="number"&&n>0){let s=et.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(Qe.isCommonPositionType(e))return tt.fromCommonPosition(e);if(tt.isCoord2DPosition(e))return e;if(Xt.isAlignPosition(e))return tt.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 et.isUnknown(e)||e===void 0?et.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return tt.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:et.isUnknown(t.x)?0:t.x,y:et.isUnknown(t.y)?0:t.y,xoffset:et.isUnknown(t.xoffset)?0:t.xoffset,yoffset:et.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(un).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 Qe||e instanceof tt||e instanceof Xt}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return tt.fromCommonPosition(new Qe(e));if(this.isRawAlignPosition(e))return tt.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new tt(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}}};et.Unknown=Symbol("Unknown");var N=et,hi=class hi{static isCommonPositionType(e){return e instanceof hi}constructor(e){this.position=e}toCSS(){return{x:qr[this.position],y:"50%",xoffset:0,yoffset:0}}};hi.Positions=un;var Qe=hi,tt=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:qr[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}}},Xt=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 $=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new To(this.mergeWithDefaultConfig(e))}copy(){return new o(W({},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)?W({},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}},To=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(W({},this.config))}join(e){let t=Kr(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 Ga={[fi.left]:"25.33%",[fi.center]:"50%",[fi.right]:"75.66%"},lt=class lt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new lt(lt.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=lt.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 yo(X.constructStyle(e,this.state,t))}toStyle(e,t){return yo(X.constructStyle(e,this.state,t))}serialize(){return lt.TransformStateSerializer.serialize(this.state)}clone(){return new lt(lt.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=lt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};lt.DefaultTransformState=new $({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new Qe("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}),lt.TransformStateSerializer=new je({position:e=>N.serializePosition(N.tryParsePosition(e))},{position:e=>N.toCoord2D(e)});var le=lt,we=class we{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},we.defaultConfig,t||{});else{let[n,i]=[e,t||we.defaultOptions];this.sequences.push({props:n,options:i||we.defaultOptions}),this.config=Object.assign({},we.defaultConfig)}}static isPosition(e){return Qe.isCommonPositionType(e)||tt.isCoord2DPosition(e)||Xt.isAlignPosition(e)}static immediate(e){return new we(e,{duration:0,ease:"linear"})}static left(e,t){return new we({position:Qe.Positions.Left},{duration:e,ease:t})}static right(e,t){return new we({position:Qe.Positions.Right},{duration:e,ease:t})}static center(e,t){return new we({position:Qe.Positions.Center},{duration:e,ease:t})}static create(e){return new we([],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{...W(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(d,g,m){return typeof d>"u"?typeof m<"u"?g(m):"":g(d)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,d=>`rotate(${d}deg)`,0),c(t.scaleX,d=>`scaleX(${d*a})`,1),c(t.scaleY,d=>`scaleY(${d*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{...we.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?ln(t.fontColor):void 0,transform:we.propToCSSTransform(e,t),...we.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=Na(s,a),p=()=>{e.overwrite(l,r.get()).unlock(l),u.complete(),c=!0},d=new S().registerSkipController(new F(p)),g=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),d.resolve()};return u.then(g,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{g()}catch{d.resolve()}})),u.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),d}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...we.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 we(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 ue("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 ue("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};we.defaultConfig={sync:!0},we.defaultOptions={duration:0,ease:"linear"},we.CommonImagePositionMap=Ga;var X=we;var gi=class{constructor(){this.id=""}setId(e){this.id=e}getId(){return this.id}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 Qr=Symbol("_Chained"),Xr;Xr=Qr;var bo=class bo{constructor(e){this[Xr]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Qr]}static toActions(e){return e.flat(2).map(t=>bo.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()}},Le=bo,pn=class extends gi{chain(e){let t=Le.isChained(this)?this:this.proxy(this,new Le(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 oe=class extends pn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var vt=class extends B{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)}}`:""}`)}};vt.ActionTypes=Mr;var St=class o{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(o.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(o.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=W({},t),this.defaultContent=t}set(e,t){return o.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
4
+ at namespace "${this.name}"`),this.content[e]=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(){return this.content=W({},this.defaultContent),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)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)})}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e){let t={any:i=>({type:"any",data:i}),date:i=>({type:"date",data:i.toString()})},n=this.toTypeName(e);return t[n](e)}unwrap(e){return{any:n=>n.data,date:n=>new Date(n.data)}[e.type](e)}},Ln=class{constructor(){this.namespaces={}}static createNamespace(e,t,n){return new St(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,this}getNamespace(e){if(!this.namespaces[e])throw new I(`Namespace ${e} is not initialized, did you forget to register it?
5
+ Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return 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)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]||(this.namespaces[t]=new St(t,{})),this.namespaces[t].deserialize(n)})}clear(){return this.namespaces={},this}};var Xe=class extends B{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===It.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.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===It.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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===It.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.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")}};Xe.ActionTypes=It;var Ut=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Ut||{}),Ce=class Ce extends oe{static toSound(e){return e==null?null:typeof e=="string"?new Ce({src:e}):e}static isSound(e){return e instanceof Ce}static voice(e){let t=typeof e=="string"?{src:e}:e;return new Ce({...t,type:"voice"})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new Ce({...t,type:"bgm"})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new Ce({...t,type:"sound"})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=Ce.DefaultUserConfig.create(t),[i]=n.extract(Ce.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){if(this.config.type==="bgm")throw new xe(`Sound (src: ${this.config.src}) is marked as bgm, but it is being played as a normal sound.
6
+ To prevent unintended behavior, the sound marked as bgm cannot be played using \`play()\`.`);return this.pushAction(Xe.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(Xe.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(Xe.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(Xe.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(Xe.ActionTypes.setRate,[e])}pause(e){return this.pushAction(Xe.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(Xe.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}getSrc(){return this.config.src}toData(){return{state:Ce.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Ce.StateSerializer.deserialize(e.state),this}copy(){return new Ce(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Ce.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new Xe(this.chain(),e,new x().setContent(t)))}};Ce.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Ce.DefaultUserConfig=new $({src:Ce.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,type:"sound"}),Ce.DefaultConfig=new $({src:Ce.noSound,loop:!1,streaming:!1,seek:0,type:"sound"}),Ce.DefaultState=new $({volume:1,rate:1,paused:!1,muted:!1}),Ce.StateSerializer=new je;var Se=Ce;var Jr=2;var Ip={};var dn=class extends pn{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 Jt=class Jt{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===Jt.SrcTypes.image?t.add(s):r===Jt.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 M?M.getSrcURL(e):e.type==="image"?M.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(re,q.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(D.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,_e.setSrc)){let i=t.contentNode.getContent()[0];if(D.isImageSrc(i))return{type:"image",src:D.srcToURL(i),activeType:"scene"}}else{if(t.type===_e.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===_e.setAppearance){let i=t.contentNode.getContent()[0];if(M.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(M.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:M.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 Se){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof M||D.isStaticImageData(e)){if(e instanceof M){if(!D.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(M.getSrcURL(e)))return this}else if(this.isSrcRegistered(D.srcToURL(e.src)))return this;this.src.push({type:"image",src:D.isStaticImageData(e)?D.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 Se?t:new Se({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 Se?e.getSrc():e;return this.src.some(n=>n.type===Jt.SrcTypes.audio?t===n.src.getSrc():n.type===Jt.SrcTypes.image?t===M.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)}};Jt.SrcTypes={image:"image",video:"video",audio:"audio"};var Oe=Jt;var Ot=class extends B{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===oi.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===oi.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")}};Ot.ActionTypes=oi;var Ie=class extends B{executeAction(e,t){if(this.type===De.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===De.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===De.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 S().registerSkipController(new F(()=>(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),p=e.timelines.attachTimeline(s).attachChild(u);return u.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:p},d=>{s.isSettled()||s.abort(),u.abort(),t.transformState.forceOverwrite(d.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new S().registerSkipController(new F(()=>(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 S().registerSkipController(new F(()=>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=De;var rt=class o extends oe{constructor(){super(...arguments);this.srcManager=new Oe}pos(t,n,i){return this.transform(new X({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new X({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new X({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new X({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new X({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 X({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new X({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new X(t,n))}mask(t,n={}){let i=D.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},p=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Re,d=>d.transform(p).clearClip({duration:0})):this.transform(p)}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},p=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Re,d=>d.transform(p).clearClip({duration:0})):this.transform(p)}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),p=o.wipeClipPath(n,0),d=o.createClipPathTransform([[i?p:u,{duration:0}],[i?u:p,l]]);return r?this.combineActions(new Re,g=>g.transform(d).clearClip({duration:0})):this.transform(d)}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,De.applyTransform,new x().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 X(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 X?t.copy():new X({opacity:1},t),r=new Ie(n,De.applyTransform,new x().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof X?t.copy():new X({opacity:0},t),r=new Ie(n,De.applyTransform,new x().setContent([i]));return n.chain(r)}};var ut=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(ut||{});import{animate as Ha}from"motion/react";var Tt=class{requestAnimations(e){let t=e.map(y=>y.start),n=[],i=0,r=!1,s=!1,a=!1,c=[],l=[],u=[],p=()=>{e.forEach((y,v)=>{t[v]=y.end}),i=e.length,c.forEach(y=>y(t)),l.forEach(y=>y())};return{onUpdate:y=>(c.push(y),{cancel:()=>{let v=c.indexOf(y);v!==-1&&c.splice(v,1)}}),onComplete:y=>(l.push(y),{cancel:()=>{let v=l.indexOf(y);v!==-1&&l.splice(v,1)}}),onCanceled:y=>(u.push(y),{cancel:()=>{let v=u.indexOf(y);v!==-1&&u.splice(v,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(y=>y.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){p();return}e.forEach((y,v)=>{n.push(this.requestMotion(y,{onComplete:()=>{t[v]=y.end,c.forEach(C=>C(t)),i++,i===e.length&&l.forEach(C=>C())},onUpdate:C=>{t[v]=C,c.forEach(f=>f(t))}}))})}},cancel:()=>{s=!0,n.forEach(y=>y.cancel()),u.forEach(y=>y())}}}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 Ha(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Tt.AnimationType=ut;var In=class extends Tt{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new I(`Trying to access text state, but element is not set
7
+ This should not happen, please report this issue to the developers`);return this._element.state}};var yi=class o extends In{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 Je=class Je extends rt{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=Je.DefaultUserConfig.create(n),r=Je.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 Ot(t,Ot.ActionTypes.setText,new x().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new X({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Re,i=>{if(t){let s=new yi({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new Ot(i,Ot.ActionTypes.setFontSize,new x().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:Je.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=Je.StateSerializer.deserialize(e.state),this.transformState=le.deserialize(e.transformState),this}_init(e){return new Ie(this.chain(),De.init,new x().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(Je.DefaultTextTransformState.keys());return new le(Je.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Ie(e,De.applyTransition,new x().setContent([t,n=>n._setElement(this)]))}getInitialState(){return Je.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};Je.DefaultUserConfig=new $({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:""}),Je.DefaultTextConfig=new $({alignX:"center",alignY:"center",className:"",layer:void 0}),Je.DefaultTextState=new $({fontSize:16,display:!1,text:""}),Je.DefaultTextTransformState=new $({fontColor:"#000000",...le.DefaultTransformState.getDefaultConfig()}),Je.StateSerializer=new je;var Yt=Je;var Rn=class Rn extends B{executeAction(e,t){let n=this;if(n.is(Rn,"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(Rn,"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")}};Rn.ActionTypes=kn;var vi=Rn;var Me=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 Ye=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 Ne=class Ne{static isWord(e){return e instanceof Ne}static color(e,t){return Ne.isWord(e)?e.copy().assign({color:t}):new Ne(e,{color:t})}static bold(e){return Ne.isWord(e)?e.copy().assign({bold:!0}):new Ne(e,{bold:!0})}static italic(e){return Ne.isWord(e)?e.copy().assign({italic:!0}):new Ne(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=W(Ne.defaultConfig,t)}evaluate(e){if(Me.isPause(this.text))return[this];if(Ye.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Ne.isWord(n)?n.inherit(this.config).evaluate(e):new Ne(n,this.config)).flat():Ne.isWord(t)?t.inherit(this.config).evaluate(e):[new Ne(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=W(this.config,e),this}copy(){return new Ne(this.text,this.config)}isPause(){return Me.isPause(this.text)}isTextEvent(){return Ye.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Ne.defaultConfig={},Ne.defaultColor="#000";var Q=Ne;var Ze=class Ze{static isSentence(e){return e instanceof Ze}static toSentence(e){return Ze.isSentence(e)?e:new Ze(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 Q.isWord(e)?e:new Q(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[Q.isWord(e)?e:new Q(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(Ze.isSingleWord):Ze.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||Q.isWord(e)||Me.isPause(e)||Ye.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=Ze.format(e),this.config=W(Ze.defaultConfig,{...t,voice:typeof t.voice=="string"?Se.voice(t.voice):Se.toSound(t.voice)}),this.state=Vr(Ze.defaultState)}toData(){return null}fromData(e){return this.state=W(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(...Ze.formatStaticWord(i))}return t}copy(){return new Ze([...this.text],this.config)}};Ze.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},Ze.defaultState={};var ve=Ze;var Kt=class extends B{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")}};Kt.ActionTypes=Nr;var Ae=class o extends oe{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 Kt(t,Kt.ActionTypes.action,new x().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new Kt(this.chain(),Kt.ActionTypes.action,new x().setContent(e))]}};var Si=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 Ee=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()}),qe(()=>{this.preventAttach()})}static proxy(e){let t=new S,n=new S,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 I("Cannot create an 'any' timeline with no awaitables.");let t=new S,n=new S,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 I("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,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 S,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?qe(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new F(()=>(i&&i.abort(),t))),i=e(t),i?qe(()=>s()):qe(()=>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()?qe(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 I(`Attaching to this timeline violates the timeline's state.
8
8
  Timeline attaching is only allowed synchronously after the timeline is created.
9
- Current _ableToAttach: `+this._ableToAttach);let t=y.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())}},di=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof ke?e:new ke(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 an=class an extends j{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:fe.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)}executeAction(e,t){if(this.type===en.say){let n=null,i="",r=null,s=new y(f=>f).registerSkipController(new U(()=>{n?.()})),a=new ke(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),p=e.createPresentationSnapshot(),d=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,g=an.getVoice(e,c);if(g){let f=e.audioManager.play(g);a.attachChild(f)}let h=g?e.events.on(P.EventTypes["event:state.player.lineEnd"],()=>{let f=an.endVoiceWithPreference(e,g);f&&e.timelines.attachTimeline(f),h?.cancel()}):null;if(l){let f=this.getId(),m=(e.getActiveNvlDialogForAction(f)||e.getLatestNvlDialogForAction(f))?.id||e.allocateNvlDialogId(f),S=c.evaluate(Se.getCtx({gameState:e}));i=q.getText(S),u.events.emit(gt.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let I=!1,C=()=>{I||(I=!0,e.events.emit(P.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(v),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:b}=e.ensureNvlDialog({id:m,actionId:f,character:this.callee,sentence:c,text:i});r=m;let x=e.consumeNvlTypingSuppression(),N=b&&!x?"typing":"awaitAdvance";e.activateNvlDialog(m,N,!b);let H=e.waitForNvlAdvance(m,()=>{e.settleNvlDialog(m),C()});n=()=>{H.cancel()}}else{let f=e.idManager.generateId(),T=e.createDialog(f,c,()=>{e.settleAdvDialog(f),e.gameHistory.resolvePending(v),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(f,this.getId()),i=T.text,n=()=>{e.settleAdvDialog(f),T.cancel()}}u.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:v}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(h?.cancel(),g&&e.audioManager.isPlaying(g)){let f=an.endVoiceWithPreference(e,g);f&&a.attachChild(f)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(p),d?u.setLastDialog(d.sentence,d.speaker):u.lastDialog=null});return e.gameHistory.push({token:v,action:this,element:{type:"say",text:i,voice:g?g.getSrc():null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),s}else if(this.type===en.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")}};an.ActionTypes=en;var st=an;var En=class En extends ce{constructor(e,t={}){super(),this.config=K(En.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=>pe.isSingleWord(c))){let c=e,l=pe.format([t,...n]),u=new pe(Lr(c,l),{character:this}),p=new st(this.chain(),st.ActionTypes.say,new A().setContent(u));return this.chain(p)}let i=t||{},r=e,s=Array.isArray(r)?new pe(r,{...i,character:this}):(pe.isSentence(r)?r:new pe(r,{...i,character:this})).copy();s.setCharacter(this);let a=new st(this.chain(),st.ActionTypes.say,new A().setContent(s));return this.chain(a)}setName(e){let t=new st(this.chain(),st.ActionTypes.setName,new A().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&&pe.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):pe.isSentence(e)?this.say(e):this.say(e,t)}};En.defaultCharacterColor="#000",En.defaultConfig={portraits:[]};var mi=En,Pt=new mi(null);var V=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()})`}},mo=class o extends ce{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 we(`ELSE condition already set
10
- You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:V.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new we(`ELSE condition already set
11
- 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 A().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 De.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=V.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new dt(i,dt.ActionTypes.action,new A().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Pt.say(n).getActions():De.toActions([n]))}};var fi=class fi extends ce{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new mt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Tn.set,[e,t]))}assign(e){return this.chain(this.createAction(Tn.assign,[e]))}equals(e,t){return new V(n=>{let i=n.storable.getNamespace(this.namespace),r=V.isLambda(t)||V.isLambdaHandler(t)?V.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new V(n=>{let i=n.storable.getNamespace(this.namespace),r=V.isLambda(t)||V.isLambdaHandler(t)?V.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new V(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new V(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new V(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new q(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new q(i=>V.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new V(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=fi.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new ui(this.chain(),e,A.create(t))}};fi.NamespacePrefix="persistent";var cn=fi,hi=class hi extends cn{constructor(e){super(e,{}),this.namespace=this.prefix(e,hi.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new mt(this.namespace,this.defaultContent))}};hi.LocalNamespacePrefix="local";var ln=hi;var un=class extends j{executeAction(e,t){if(this.type===Wt.action)return super.executeAction(e,t);if(this.type===Wt.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")}};un.ActionTypes=Wt;var it=class it extends ft{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 un(this.chain(),Wt.setZIndex,new A().setContent([e])))}toData(){return{state:it.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=it.StateSerializer.deserialize(e.state),this.transformState=Ce.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 un(this.chain(),Wt.action,new A),new Le(this.chain(),Ee.init,new A().setContent([e,null,!1]))]}getInitialState(){return it.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(Ce.DefaultTransformState.keys());return new Ce(Ce.DefaultTransformState.create(e.get()).get())}};it.DefaultUserConfig=new J({zIndex:0,...Ce.DefaultTransformState.getDefaultConfig(),opacity:1}),it.DefaultConfig=new J({name:"(anonymous)",zIndex:0}),it.StateSerializer=new $e,it.DefaultState=new J({zIndex:0});var pn=it;var Dn=class extends ce{constructor(e){super(),this.scene=e}show(e){let t=new ee(this.scene.chain(),$.nvlShow,new A().setContent([e]));return this.chain(t)}hide(e){let t=new ee(this.scene.chain(),$.nvlHide,new A().setContent([e]));return this.chain(t)}end(){let e=new ee(this.scene.chain(),$.nvlEnd,new A().setContent([]));return this.chain(e)}};var Ve=class Ve extends sn{constructor(t,n){super();this.srcManager=new Fe;this.events=new Y;this.actions=[];this._futureActions_=[];let i=Ve.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Ve.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Ve.DefaultUserConfig.create(n),a=Ve.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 ln(t)}static validateVoice(t){if(t.config.type!=="voice"&&t.config.type!=="sound")throw new we(`Voice must be a voice, but got ${t.config.type}.
12
- To prevent unintended behavior and unexpected results, the sound have to be marked as voice. Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Ve}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new $e({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(Ie.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new Ie({allowFutureScene:!1}),i=>{let s=K({},n instanceof ht?{transition:n}:n);return i.chain(new ee(i,"scene:preUnmount",new A().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 ee(this.chain(),$.setBackgroundMusic,new A().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new Dn(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new ee(this.chain(),$.nvlEnd,new A().setContent([l])),p=[...c,u];super.constructNodes(p);let d=new ee(this.chain(),$.nvlBlock,new A().setContent([p,l]));return this.chain(d)}action(t){return this.actions=t,this}preloadImage(t){if(!w.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:Ve.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=Ve.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new ee(this.chain(),"scene:action",new A);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(h=>De.isChained(h)?h.fromChained(h):h).flat(2),s=[],a=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(h=>{De.isChained(h)||(h instanceof R?s.push(h):h instanceof $t&&a.push(h))});let c=[],l=[],u=new Map;s.forEach(h=>{h.config.isWearable?l.push(h):h.config.autoInit&&c.push(h);for(let v of h.config.wearables){if(u.get(v)&&u.get(v)!==h)throw new Error(`Wearable image cannot be used multiple times
9
+ Current _ableToAttach: `+this._ableToAttach);let t=S.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())}},Ti=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof Ee?e:new Ee(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 mn=class mn extends B{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:Se.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)}executeAction(e,t){if(this.type===an.say){let n=null,i="",r=null,s=new S(v=>v).registerSkipController(new F(()=>{n?.()})),a=new Ee(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),p=e.createPresentationSnapshot(),d=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,g=mn.getVoice(e,c);if(g){let v=e.audioManager.play(g);a.attachChild(v)}let m=g?e.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{let v=mn.endVoiceWithPreference(e,g);v&&e.timelines.attachTimeline(v),m?.cancel()}):null;if(l){let v=this.getId(),f=(e.getActiveNvlDialogForAction(v)||e.getLatestNvlDialogForAction(v))?.id||e.allocateNvlDialogId(v),h=c.evaluate(Ae.getCtx({gameState:e}));i=Q.getText(h),u.events.emit(bt.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let w=!1,T=()=>{w||(w=!0,e.events.emit(L.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(y),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:b}=e.ensureNvlDialog({id:f,actionId:v,character:this.callee,sentence:c,text:i});r=f;let A=e.consumeNvlTypingSuppression(),E=b&&!A?"typing":"awaitAdvance";e.activateNvlDialog(f,E,!b);let O=e.waitForNvlAdvance(f,()=>{e.settleNvlDialog(f),T()});n=()=>{O.cancel()}}else{let v=e.idManager.generateId(),C=e.createDialog(v,c,()=>{e.settleAdvDialog(v),e.gameHistory.resolvePending(y),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(v,this.getId()),i=C.text,n=()=>{e.settleAdvDialog(v),C.cancel()}}u.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:y}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(m?.cancel(),g&&e.audioManager.isPlaying(g)){let v=mn.endVoiceWithPreference(e,g);v&&a.attachChild(v)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(p),d?u.setLastDialog(d.sentence,d.speaker):u.lastDialog=null});return e.gameHistory.push({token:y,action:this,element:{type:"say",text:i,voice:g?g.getSrc():null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),s}else if(this.type===an.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")}};mn.ActionTypes=an;var pt=mn;var Mn=class Mn extends oe{constructor(e,t={}){super(),this.config=W(Mn.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=>ve.isSingleWord(c))){let c=e,l=ve.format([t,...n]),u=new ve(Ur(c,l),{character:this}),p=new pt(this.chain(),pt.ActionTypes.say,new x().setContent(u));return this.chain(p)}let i=t||{},r=e,s=Array.isArray(r)?new ve(r,{...i,character:this}):(ve.isSentence(r)?r:new ve(r,{...i,character:this})).copy();s.setCharacter(this);let a=new pt(this.chain(),pt.ActionTypes.say,new x().setContent(s));return this.chain(a)}setName(e){let t=new pt(this.chain(),pt.ActionTypes.setName,new x().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&&ve.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ve.isSentence(e)?this.say(e):this.say(e,t)}};Mn.defaultCharacterColor="#000",Mn.defaultConfig={portraits:[]};var bi=Mn,Rt=new bi(null);var z=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()})`}},Co=class o extends oe{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 xe(`ELSE condition already set
10
+ You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:z.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new xe(`ELSE condition already set
11
+ 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(vt,[this,vt.ActionTypes.action,new x().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 Le.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=z.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new vt(i,vt.ActionTypes.action,new x().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Rt.say(n).getActions():Le.toActions([n]))}};var Ci=class Ci extends oe{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new St(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(kn.set,[e,t]))}assign(e){return this.chain(this.createAction(kn.assign,[e]))}equals(e,t){return new z(n=>{let i=n.storable.getNamespace(this.namespace),r=z.isLambda(t)||z.isLambdaHandler(t)?z.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new z(n=>{let i=n.storable.getNamespace(this.namespace),r=z.isLambda(t)||z.isLambdaHandler(t)?z.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new z(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new z(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new z(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new Q(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new Q(i=>z.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new z(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=Ci.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new vi(this.chain(),e,x.create(t))}};Ci.NamespacePrefix="persistent";var fn=Ci,xi=class xi extends fn{constructor(e){super(e,{}),this.namespace=this.prefix(e,xi.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new St(this.namespace,this.defaultContent))}};xi.LocalNamespacePrefix="local";var hn=xi;var gn=class extends B{executeAction(e,t){if(this.type===Qt.action)return super.executeAction(e,t);if(this.type===Qt.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")}};gn.ActionTypes=Qt;var st=class st extends rt{constructor(e,t={}){super();let n=st.DefaultUserConfig.create(t),i=st.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 gn(this.chain(),Qt.setZIndex,new x().setContent([e])))}toData(){return{state:st.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=st.StateSerializer.deserialize(e.state),this.transformState=le.deserialize(e.transformState),this}copy(){return new st(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new gn(this.chain(),Qt.action,new x),new Ie(this.chain(),De.init,new x().setContent([e,null,!1]))]}getInitialState(){return st.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(le.DefaultTransformState.keys());return new le(le.DefaultTransformState.create(e.get()).get())}};st.DefaultUserConfig=new $({zIndex:0,...le.DefaultTransformState.getDefaultConfig(),opacity:1}),st.DefaultConfig=new $({name:"(anonymous)",zIndex:0}),st.StateSerializer=new je,st.DefaultState=new $({zIndex:0});var yn=st;var Nn=class extends oe{constructor(e){super(),this.scene=e}show(e){let t=new re(this.scene.chain(),q.nvlShow,new x().setContent([e]));return this.chain(t)}hide(e){let t=new re(this.scene.chain(),q.nvlHide,new x().setContent([e]));return this.chain(t)}end(){let e=new re(this.scene.chain(),q.nvlEnd,new x().setContent([]));return this.chain(e)}};var $e=class $e extends dn{constructor(t,n){super();this.srcManager=new Oe;this.events=new te;this.actions=[];this._futureActions_=[];this.labelMap=new Map;let i=$e.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=$e.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=$e.DefaultUserConfig.create(n),a=$e.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 hn(t)}static validateVoice(t){if(t.config.type!=="voice"&&t.config.type!=="sound")throw new xe(`Voice must be a voice, but got ${t.config.type}.
12
+ To prevent unintended behavior and unexpected results, the sound have to be marked as voice. Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof $e}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new je({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(Re.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new Re({allowFutureScene:!1}),i=>{let s=W({},n instanceof Tt?{transition:n}:n);return i.chain(new re(i,"scene:preUnmount",new x().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 re(this.chain(),q.setBackgroundMusic,new x().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new Nn(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new re(this.chain(),q.nvlEnd,new x().setContent([l])),p=[...c,u];super.constructNodes(p);let d=new re(this.chain(),q.nvlBlock,new x().setContent([p,l]));return this.chain(d)}action(t){return this.actions=t,this}preloadImage(t){if(!D.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:$e.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=$e.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new re(this.chain(),"scene:action",new x);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>Le.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{Le.isChained(m)||(m instanceof M?s.push(m):m instanceof Yt&&a.push(m))});let c=[],l=[],u=new Map;s.forEach(m=>{m.config.isWearable?l.push(m):m.config.autoInit&&c.push(m);for(let y of m.config.wearables){if(u.get(y)&&u.get(y)!==m)throw new Error(`Wearable image cannot be used multiple times
13
13
  Maybe you bind the same wearable image to multiple parent images
14
- Parent Conflict (src: `+u.get(v)?.state.currentSrc+`)
15
- Current Parent (src: `+h.state.currentSrc+")");u.set(v,h)}});let p=[...this._initScene(this),...c.map(h=>h._init(this)),...l.map(h=>{if(!u.has(h))throw new Error("Wearable image must have a parent image");return u.get(h)._initWearable(h)}),...a.map(h=>h._init()),...r],d=super.constructNodes(p),g=new A(this.sceneRoot,void 0,d||void 0).setContent(this);return d?.setParent(g),this.sceneRoot?.setContentNode(g),this._futureActions_=p,this}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Pt.say(n).getActions():De.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 ee){let l=c.callee;if(w.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:w.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===$.jumpTo){let u=c,p=Ve.getScene(t,u.contentNode.getContent()[0]);if(!p)throw c._sceneNotFoundError(c.getSceneName(u.contentNode.getContent()[0]));let d=Fe.getPreloadableSrc(t,c);if(d&&this.srcManager.register(d),r.has(u)||n.has(p))continue;r.add(u),a.add(p),n.add(p)}}else if(c instanceof le){let l=Fe.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof qe)this.srcManager.register(c.callee);else if(c instanceof he){let u=c.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else c instanceof Le&&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 we(`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.setId(`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"?fe.voice(r):(Ve.validateVoice(r),r)}let i=n[t];return typeof i=="string"?fe.voice(i):i||null}return null}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&&t.backgroundMusic.config.type!=="bgm")throw new we(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
16
- To prevent unintended behavior and unexpected results, the sound have to be marked as bgm. 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 ee(this.chain(),"scene:jumpTo",new A().setContent([t])))}_exit(){return new ee(this.chain(),"scene:exit",new A().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 ee(this.chain(),"scene:init",new A().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)]}};Ve.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"},Ve.DefaultUserConfig=new J({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Ve.DefaultSceneConfig=new J({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new pn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new pn("[[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=>{fe.isSound(r)&&Ve.validateVoice(r)}),i(t))return t;throw new we(`Invalid voices config: ${t}`)}});var et=Ve;import*as Yr from"howler";var gi=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 Aa={volume:1,limit:1/0},xa=class Br{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={...Aa,...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 Br(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}}},$r=!1;function wa(o){$r=o}function Ft(o,e){$r||(e!==void 0?console.warn(o,e):console.warn(o))}var ka=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){Ft("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){Ft("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){Ft("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()}},zr=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}},Pa=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 ka(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){Ft("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){Ft("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 zr(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new zr(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}},Ea=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}},Da=10*1024*1024,La=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 Ea(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}}},Ia={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},jr=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...Ia,...o},wa(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new La(this.audioContext),this.masterChannel=new xa("__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=>{Ft("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 d=this.audioContext.createBufferSource();d.buffer=u.raw(),l=d}else{u=o,u.addRef?.();let d=this.audioContext.createBufferSource();d.buffer=o.raw(),l=d}let p=new Pa(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 d=!1,g=()=>{d||(d=!0,u.releaseRef?.())};p.once("ended",g),p.once("stop",g)}return p}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<Da?"full":"stream"}catch(t){return Ft("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=>{Ft("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var yi=class{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.channelVolumes=new Map;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1;Object.values(Nt).forEach(t=>{this.channelVolumes.set(t,1)})}initialize(){if(this.isReady||this.isInitializing)return;let e=new jr;this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),Object.values(Nt).forEach(t=>{let n=this.channelVolumes.get(t)??1,i=e.getChannel(t)??e.createChannel(t,{volume:n});i.setVolume(n),this.channels.set(t,i)}),this.isReady=!0,this.isInitializing=!1,this.setupGroupVolume()}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}play(e,t={end:1,duration:0}){let n=new y;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channels.get(e.config.type),r=await this.sound.load(e.config.src),s=await i.play(r,{volume:0,startTime:e.config.seek,loop:e.config.loop,rate:1}),a=e.state.muted??!1;s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:r,originalVolume:t.end}),t.duration>0?await s.fade(0,t.end,t.duration).finished:s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(c=>{s.once("ended",()=>c())}),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={end:1,duration:0}){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channels.get(e.config.type);if(!n)throw new E(`Channel not found for sound type: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=await n.play(i,{volume:0,startTime:e.config.seek,loop:e.config.loop,rate:1}),s=e.state.muted??!1;return r.mute(s),e.state.muted=s,this.state.set(e,{token:r,cachedAudio:i,originalVolume:t.end}),t.duration>0?r.fade(0,t.end,t.duration):r.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,r}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 y;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 y;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 y;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 y;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 y;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}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,y.resolve(void 0)):y.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.channelVolumes.entries()].map(([e,t])=>[e,t])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setGroupVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r)throw new E(`Sound not found (id: "${n}")
17
- NarraLeaf cannot find the element with the id from the saved game`);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.channels.get(e.config.type),i=await this.sound.load(e.config.src),r=await n.play(i,{volume:e.state.volume,startTime:t.position,loop:e.config.loop,rate:1});this.state.set(e,{token:r,cachedAudio:i,originalVolume:e.state.volume});let s=e.state.muted??!1;r.mute(s),e.state.muted=s,e.state.paused?r.pause():t.isPlaying||r.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),Object.values(Nt).forEach(e=>{if(this.channelVolumes.set(e,1),this.isReady){let t=this.channels.get(e);t&&t.setVolume(1)}}),this.setupGroupVolume()}setGroupVolume(e,t){if(this.channelVolumes.set(e,t),this.isReady){let n=this.channels.get(e);n&&n.setVolume(t)}}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}getGroupVolume(e){return this.channelVolumes.get(e)??1}destroy(){this.reset(),this.sound.destroy()}setupGroupVolume(){let{soundVolume:e,bgmVolume:t,voiceVolume:n}=this.gameState.game.preference.getPreferences();this.setGroupVolume("sound",e),this.setGroupVolume("bgm",t),this.setGroupVolume("voice",n)}};import*as Ra from"html-to-image";var vi=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new Y}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 y,n=new ke(t);return t.registerSkipController(new U(()=>{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 Si=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=ri(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 Ti=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:ri(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 jt=class extends j{executeAction(e,t){let n=new y().registerSkipController(new U(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let p=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:[p]}}),a=()=>{p.reset()},e.gameHistory.updateByToken(l,d=>{d&&d.element.type==="menu"&&(d.element.selected=u.evaluated,d.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(",")}]}`)}};jt.ActionTypes=kr;var qt=class qt extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=pe.isSentence(t)?t:t===null?null:new pe(t),this.config=K(qt.defaultConfig,n)}static prompt(t,n={}){return new qt(t!==void 0?t:null,n)}static choose(t,n){return new qt(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return pe.isSentence(t)&&n?i.choices.push({prompt:pe.toSentence(t),action:this.narrativeToActions(n),config:{}}):(q.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:pe.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:pe.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?V.from(t.config.disabled):void 0,hidden:t.config?.hidden?V.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 we("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=V.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new we("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=V.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:V.not(V.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:V.not(V.from(t))}})}fromChained(t){return[new jt(this.chain(),jt.ActionTypes.action,new A().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"?Pt.say(n).getActions():De.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??{}}))}};qt.defaultConfig={},qt.targetAction=jt;var fo=qt;var Et=class Et extends sn{constructor(t,n=Et.defaultConfig){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.name=t,this.config=K(Et.defaultConfig,n)}static empty(){return new Et("empty").entry(new et("empty"))}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new cn(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 we(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return Fr(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 me(`Service ${i} serialize method should not return a promise`);if(!co(r))throw new me(`Service ${i} serialize method should return a pure object.
14
+ Parent Conflict (src: `+u.get(y)?.state.currentSrc+`)
15
+ Current Parent (src: `+m.state.currentSrc+")");u.set(y,m)}});let p=[...this._initScene(this),...c.map(m=>m._init(this)),...l.map(m=>{if(!u.has(m))throw new Error("Wearable image must have a parent image");return u.get(m)._initWearable(m)}),...a.map(m=>m._init()),...r],d=super.constructNodes(p),g=new x(this.sceneRoot,void 0,d||void 0).setContent(this);return d?.setParent(g),this.sceneRoot?.setContentNode(g),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 _&&r.type===Z.label){let[s]=r.contentNode.getContent();if(i.has(s))throw new xe(`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 _&&r.type===Z.jump){let[s]=r.contentNode.getContent(),a=i.get(s);if(!a)throw new xe(`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"?Rt.say(n).getActions():Le.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 re){let l=c.callee;if(D.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:D.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===q.jumpTo){let u=c,p=$e.getScene(t,u.contentNode.getContent()[0]);if(!p)throw c._sceneNotFoundError(c.getSceneName(u.contentNode.getContent()[0]));let d=Oe.getPreloadableSrc(t,c);if(d&&this.srcManager.register(d),r.has(u)||n.has(p))continue;r.add(u),a.add(p),n.add(p)}}else if(c instanceof ge){let l=Oe.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof Xe)this.srcManager.register(c.callee);else if(c instanceof _){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 xe(`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.setId(`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"?Se.voice(r):($e.validateVoice(r),r)}let i=n[t];return typeof i=="string"?Se.voice(i):i||null}return null}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&&t.backgroundMusic.config.type!=="bgm")throw new xe(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
16
+ To prevent unintended behavior and unexpected results, the sound have to be marked as bgm. Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new M({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 re(this.chain(),"scene:jumpTo",new x().setContent([t])))}_exit(){return new re(this.chain(),"scene:exit",new x().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 re(this.chain(),"scene:init",new x().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)]}};$e.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"},$e.DefaultUserConfig=new $({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),$e.DefaultSceneConfig=new $({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new yn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new yn("[[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=>{Se.isSound(r)&&$e.validateVoice(r)}),i(t))return t;throw new xe(`Invalid voices config: ${t}`)}});var nt=$e;import*as rs from"howler";var Ai=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 Va={volume:1,limit:1/0},Fa=class _r{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={...Va,...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 _r(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}}},es=!1;function Ua(o){es=o}function Wt(o,e){es||(e!==void 0?console.warn(o,e):console.warn(o))}var Oa=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){Wt("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){Wt("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){Wt("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()}},Zr=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}},Ka=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 Oa(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){Wt("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){Wt("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 Zr(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new Zr(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}},Wa=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}},za=10*1024*1024,$a=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 Wa(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}}},Ba={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},ts=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...Ba,...o},Ua(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new $a(this.audioContext),this.masterChannel=new Fa("__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=>{Wt("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 d=this.audioContext.createBufferSource();d.buffer=u.raw(),l=d}else{u=o,u.addRef?.();let d=this.audioContext.createBufferSource();d.buffer=o.raw(),l=d}let p=new Ka(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 d=!1,g=()=>{d||(d=!0,u.releaseRef?.())};p.once("ended",g),p.once("stop",g)}return p}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<za?"full":"stream"}catch(t){return Wt("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=>{Wt("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var wi=class{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.channelVolumes=new Map;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1;Object.values(Ut).forEach(t=>{this.channelVolumes.set(t,1)})}initialize(){if(this.isReady||this.isInitializing)return;let e=new ts;this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),Object.values(Ut).forEach(t=>{let n=this.channelVolumes.get(t)??1,i=e.getChannel(t)??e.createChannel(t,{volume:n});i.setVolume(n),this.channels.set(t,i)}),this.isReady=!0,this.isInitializing=!1,this.setupGroupVolume()}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}play(e,t={end:1,duration:0}){let n=new S;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channels.get(e.config.type),r=await this.sound.load(e.config.src),s=await i.play(r,{volume:0,startTime:e.config.seek,loop:e.config.loop,rate:1}),a=e.state.muted??!1;s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:r,originalVolume:t.end}),t.duration>0?await s.fade(0,t.end,t.duration).finished:s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(c=>{s.once("ended",()=>c())}),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={end:1,duration:0}){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channels.get(e.config.type);if(!n)throw new I(`Channel not found for sound type: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=await n.play(i,{volume:0,startTime:e.config.seek,loop:e.config.loop,rate:1}),s=e.state.muted??!1;return r.mute(s),e.state.muted=s,this.state.set(e,{token:r,cachedAudio:i,originalVolume:t.end}),t.duration>0?r.fade(0,t.end,t.duration):r.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,r}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 S;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 S;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 S;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 S;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 S;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}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.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.channelVolumes.entries()].map(([e,t])=>[e,t])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setGroupVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r)throw new I(`Sound not found (id: "${n}")
17
+ NarraLeaf cannot find the element with the id from the saved game`);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.channels.get(e.config.type),i=await this.sound.load(e.config.src),r=await n.play(i,{volume:e.state.volume,startTime:t.position,loop:e.config.loop,rate:1});this.state.set(e,{token:r,cachedAudio:i,originalVolume:e.state.volume});let s=e.state.muted??!1;r.mute(s),e.state.muted=s,e.state.paused?r.pause():t.isPlaying||r.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),Object.values(Ut).forEach(e=>{if(this.channelVolumes.set(e,1),this.isReady){let t=this.channels.get(e);t&&t.setVolume(1)}}),this.setupGroupVolume()}setGroupVolume(e,t){if(this.channelVolumes.set(e,t),this.isReady){let n=this.channels.get(e);n&&n.setVolume(t)}}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}getGroupVolume(e){return this.channelVolumes.get(e)??1}destroy(){this.reset(),this.sound.destroy()}setupGroupVolume(){let{soundVolume:e,bgmVolume:t,voiceVolume:n}=this.gameState.game.preference.getPreferences();this.setGroupVolume("sound",e),this.setGroupVolume("bgm",t),this.setGroupVolume("voice",n)}};import*as ja from"html-to-image";var ki=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new te}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 S,n=new Ee(t);return t.registerSkipController(new F(()=>{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 Ei=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=mi(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 Pi=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:mi(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 Zt=class extends B{executeAction(e,t){let n=new S().registerSkipController(new F(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let p=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:[p]}}),a=()=>{p.reset()},e.gameHistory.updateByToken(l,d=>{d&&d.element.type==="menu"&&(d.element.selected=u.evaluated,d.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(",")}]}`)}};Zt.ActionTypes=Gr;var _t=class _t extends oe{constructor(t,n={}){super();this.choices=[];this.prompt=ve.isSentence(t)?t:t===null?null:new ve(t),this.config=W(_t.defaultConfig,n)}static prompt(t,n={}){return new _t(t!==void 0?t:null,n)}static choose(t,n){return new _t(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return ve.isSentence(t)&&n?i.choices.push({prompt:ve.toSentence(t),action:this.narrativeToActions(n),config:{}}):(Q.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:ve.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:ve.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?z.from(t.config.disabled):void 0,hidden:t.config?.hidden?z.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 xe("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=z.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new xe("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=z.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:z.not(z.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:z.not(z.from(t))}})}fromChained(t){return[new Zt(this.chain(),Zt.ActionTypes.action,new x().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"?Rt.say(n).getActions():Le.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??{}}))}};_t.defaultConfig={},_t.targetAction=Zt;var xo=_t;var en=class en extends rt{constructor(e={}){super();let t=en.DefaultUserConfig.create(e),n=en.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 X({position:new Qe("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=le.deserialize(e.transformState),this}copy(){return new en(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(le.DefaultTransformState.keys());return new le(le.DefaultTransformState.create(e.get()).get())}};en.DefaultUserConfig=new $({...le.DefaultTransformState.getDefaultConfig(),opacity:1}),en.DefaultConfig=new $({name:"(camera)"});var Gn=en;var zt=class zt extends dn{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=W(zt.defaultConfig,r),this._camera=i??new Gn}static empty(){return new zt("empty").entry(new nt("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 fn(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 xe(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return jr(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 ue(`Service ${i} serialize method should not return a promise`);if(!vo(r))throw new ue(`Service ${i} serialize method should return a pure object.
18
18
  A pure object should:
19
19
  1. be an object literal
20
20
  2. not have any prototype
21
21
  3. no circular reference
22
22
  4. sub objects should also be pure objects or serializable data
23
23
  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
24
- 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(et.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||me,[`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>Et.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${Et.MAX_DEPTH})`);let s=i.shift();if(et.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 bi(t).run(this)}};Et.defaultConfig={origin:"bottom left"},Et.MAX_DEPTH=32767;var Ln=Et;var Ci=class extends j{executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(Se.getCtx({gameState:e}),n,i);return y.isAwaitable(r)?y.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var ho=class extends ce{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(Nr(r)){let s=[],a=new y().registerSkipController(new U(()=>{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 Ci(t,"service:action",new A().setContent([n,i]))}},go=class extends ho{},In=class extends go{};var yt=class yt extends j{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(yt,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(yt,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(yt,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(yt,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(yt,"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(yt,"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(yt,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new E(`Video is being used before it is added to the game
25
- Use video.show() to add the video to the game`);let i=this.callee,r=new y,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 U(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")}};yt.ActionTypes=tn;var Ai=yt;var dn=class dn extends ce{constructor(e){super();let t=dn.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new me("Video must have a src")}show(){return this.chain(this.createAction(tn.show,[]))}hide(){return this.chain(this.createAction(tn.hide,[]))}play(){return this.chain(this.createAction(tn.play,[]))}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 dn.DefaultVideoState.create().get()}createAction(e,t){return new Ai(this.chain(),e,A.create(t))}};dn.DefaultVideoConfig=new J({src:"",muted:!1}),dn.DefaultVideoState=new J({display:!1});var yo=dn;function Qr(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function Xr(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return qr(o);let i=vo(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=vo(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=vo(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function vo(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 qr(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}var oe=class oe{constructor(e,t){this.state={sounds:[],videos:[],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 bn;this.htmlToImage=Ra;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 Y,this.logger=new gi(e,"NarraLeaf-React"),this.audioManager=new yi(this),this.guard=new pi(e.config.app.guard).observe(this),this.timelines=new di(this.guard),this.notificationMgr=new vi(this,[]),this.idManager=new _n,this.actionHistory=new Si(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new Ti(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}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=et.isScene(e)?e:e.entryScene;if(!t)throw new E("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(oe.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(Qr);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],p=r.get(u);if(p&&this.isDisplayableVisible(u))return p}}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(Se.getCtx({gameState:this}));this.game.getLiveGame().events.emit(gt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:q.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:q.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(Se.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(gt.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?q.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(oe.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(oe.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(oe.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(oe.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(oe.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(oe.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(oe.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})=>ee.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(oe.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(oe.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(oe.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(oe.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{ee.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(oe.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(oe.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(oe.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(oe.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(oe.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 E(`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.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 Yr.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 E("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]=ke.proxy(y.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof ft&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(Z.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 Ue("State already mounted");if(!e)throw new Ue("Invalid state key");return this.exposedState.set(e,t),this.events.emit(oe.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 E("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(oe.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()]),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 E("Scene not found, id: "+a+`
26
- 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,p=>{ee.initBackgroundMusic(l,p)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,c])=>{let l=t.get(a);if(!l)throw new E("Video not found, id: "+a+`
27
- 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 pe(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(oe.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(oe.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 E('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(oe.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 E("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new E("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 E("Layer not found, id: "+n+`
28
- NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new E("Displayable not found, id: "+s+`
24
+ 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(nt.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||ue,[`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>zt.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${zt.MAX_DEPTH})`);let s=i.shift();if(nt.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 Di(t).run(this)}};zt.defaultConfig={origin:"bottom left"},zt.MAX_DEPTH=32767;var Hn=zt;var Li=class extends B{executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(Ae.getCtx({gameState:e}),n,i);return S.isAwaitable(r)?S.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var Ao=class extends oe{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(zr(r)){let s=[],a=new S().registerSkipController(new F(()=>{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 Li(t,"service:action",new x().setContent([n,i]))}},wo=class extends Ao{},Vn=class extends wo{};var Ct=class Ct extends B{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(Ct,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(Ct,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(Ct,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(Ct,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(Ct,"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(Ct,"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(Ct,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new I(`Video is being used before it is added to the game
25
+ Use video.show() to add the video to the game`);let i=this.callee,r=new S,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 F(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")}};Ct.ActionTypes=yt;var Ii=Ct;var vn=class vn extends oe{constructor(e){super();let t=vn.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ue("Video must have a src")}show(){return this.chain(this.createAction(yt.show,[]))}hide(){return this.chain(this.createAction(yt.hide,[]))}play(){return this.chain(this.createAction(yt.play,[]))}pause(){return this.chain(this.createAction(yt.pause,[]))}resume(){return this.chain(this.createAction(yt.resume,[]))}stop(){return this.chain(this.createAction(yt.stop,[]))}seek(e){return this.chain(this.createAction(yt.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 vn.DefaultVideoState.create().get()}createAction(e,t){return new Ii(this.chain(),e,x.create(t))}};vn.DefaultVideoConfig=new $({src:"",muted:!1}),vn.DefaultVideoState=new $({display:!1});var ko=vn;var $t=class $t extends B{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is($t,"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($t,"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+")"),S.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($t,"vfx:pause"))return this.changeState(e,s=>{i.state.paused=!0,s.pause()},t);if(n.is($t,"vfx:resume"))return this.changeState(e,s=>{i.state.paused=!1,s.resume()},t);if(n.is($t,"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 I(`Vfx is being used before it is added to the game
26
+ Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new S,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 F(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")}};$t.ActionTypes=Ft;var Ri=$t;var Sn=class Sn extends oe{constructor(e){super();let t=Sn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ue("Vfx must have a src")}show(e){return this.chain(this.createAction(Ft.show,[e]))}hide(e){return this.chain(this.createAction(Ft.hide,[e]))}pause(){return this.chain(this.createAction(Ft.pause,[]))}resume(){return this.chain(this.createAction(Ft.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Ft.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 Sn.DefaultVfxState.create().get()}createAction(e,t){return new Ri(this.chain(),e,x.create(t))}};Sn.DefaultVfxConfig=new $({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),Sn.DefaultVfxState=new $({display:!1,paused:!1});var Eo=Sn;function is(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function os(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return ns(o);let i=Po(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=Po(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=Po(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function Po(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 ns(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}var pe=class pe{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 En;this.htmlToImage=ja;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 te,this.logger=new Ai(e,"NarraLeaf-React"),this.audioManager=new wi(this),this.guard=new Si(e.config.app.guard).observe(this),this.timelines=new Ti(this.guard),this.notificationMgr=new ki(this,[]),this.idManager=new ai,this.actionHistory=new Ei(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new Pi(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=nt.isScene(e)?e:e.entryScene;if(!t)throw new I("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(pe.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(is);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],p=r.get(u);if(p&&this.isDisplayableVisible(u))return p}}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(Ae.getCtx({gameState:this}));this.game.getLiveGame().events.emit(bt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:Q.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:Q.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(Ae.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(bt.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?Q.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(pe.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(pe.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(pe.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(pe.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(pe.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(pe.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(pe.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})=>re.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(pe.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(pe.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(pe.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(pe.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{re.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(pe.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(pe.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(pe.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(pe.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(pe.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 I(`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 rs.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 I("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]=Ee.proxy(S.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(X.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 Pe("State already mounted");if(!e)throw new Pe("Invalid state key");return this.exposedState.set(e,t),this.events.emit(pe.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 I("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(pe.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 I("Scene not found, id: "+a+`
27
+ 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,p=>{re.initBackgroundMusic(l,p)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,c])=>{let l=t.get(a);if(!l)throw new I("Video not found, id: "+a+`
28
+ 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 I("Vfx not found, id: "+a+`
29
+ 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 ve(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(pe.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(pe.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 I('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(pe.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 I("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new I("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 I("Layer not found, id: "+n+`
30
+ NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new I("Displayable not found, id: "+s+`
29
31
  NarraLeaf cannot find the element with the id from the saved game
30
- This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};oe.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 P=oe;var Jr=32767,Ma=1e3,Oe=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 ti().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new Ue("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new Ue("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(y.isAwaitable(i)&&!i.isSettled())throw new Ue("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!y.isAwaitable(n))throw new Ue("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)&&!y.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?y.any(...t.map(n=>n.execute())):y.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%Jr===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=Jr&&t<Ma){let i=new E(`[NarraLeaf] Potential infinite loop detected!
32
+ This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};pe.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 L=pe;var ss=32767,qa=1e3,Ke=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 li().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new Pe("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new Pe("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(S.isAwaitable(i)&&!i.isSettled())throw new Pe("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!S.isAwaitable(n))throw new Pe("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)&&!S.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?S.any(...t.map(n=>n.execute())):S.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%ss===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=ss&&t<qa){let i=new I(`[NarraLeaf] Potential infinite loop detected!
31
33
  Loop has executed ${e} iterations in ${t}ms.
32
34
  This is likely a bug in your game script. Check your loop conditions.
33
- 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 E("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(y.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(y.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 y().registerSkipController(new U(()=>{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(y.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&&y.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&&y.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 Ue("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=i=>i?y.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?y.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()):y.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&&V.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 Dt=class Dt{constructor(e){this.events=new Y;this.story=null;this.gameLock=new nn;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.lastDialog=null;this.mapCache=null;this.game=e,this._storable=new wn,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new mt(Dt.GameSpacesKey.game,Dt.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:Vr,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,p]=this.constructMaps();this.initNamespaces(),this._storable.load(i),s.forEach(({id:d,data:g})=>{t.logger.debug("restore element",d);let h=p.get(d);if(!h)throw new Error("Element not found, id: "+d+`
34
- NarraLeaf cannot find the element with the id from the saved game`);h.reset(),h.fromData(g)}),this.currentSavedGame=e,t.loadData(r,p),this.stackModel.deserialize(c,u),l.forEach(d=>{let g=Oe.createStackModel(this,d,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(P.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===en.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(r,i),s===this.stackModel&&this.stackModel.push(Oe.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=y.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 fe({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(P.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=e.maxSteps??t.game.config.maxStackModelLoop,r=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let s=0;for(;s++<i;){if(n==="menu"&&t.hasActiveMenu())return{reason:"menu"};if(this.stackModel.isEmpty())return{reason:"end"};let a=this.stackModel.getWaitingAwaitable();if(a){let c=new Promise(l=>a.onSettled(()=>l()));t.events.emit(P.EventTypes["event:state.player.skip"],!0),await c}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps"}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(r)}}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(Dt.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Dt.EventTypes["event:menu.choose"],e)}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(Oe.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 Oe(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 Oe(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");let i=t.executeAction(e,n);return y.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Ue("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Oe(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Ue("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(ee,$.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(he,xe.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()}return r}clearMainStack(){if(!this.stackModel)throw new Ue("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Ue("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:Gr(),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 E("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 E("Player Element Not Mounted")}};Dt.DefaultNamespaces={game:{}},Dt.GameSpacesKey={game:"game"},Dt.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose"};var gt=Dt;var Rn=class Rn{constructor(e){this.settings=e;this.events=new Y;this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(Rn.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(Rn.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))}};Rn.EventTypes={"event:game.preference.change":"event:game.preference.change"};var Mn=Rn;import"client-only";import Gs,{useEffect as ml,useRef as zo}from"react";import"client-only";import Zr,{useContext as _r,useState as Na}from"react";var So=Zr.createContext(null);function es({children:o,game:e}){"use client";let t=new _({}),[n]=Na(e||t);return Zr.createElement(So,{value:n},o)}function L(){let o=_r(So);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function ts(){return _r(So)}import Ga,{createContext as Ha,useContext as ns}from"react";var is="/",xi=class xi{constructor(e,t=xi.rootPath){this.events=new Y;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 E(`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 E(`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(),je(()=>{t()}))})}else je(()=>{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=is;var Ut=xi,To=Ha(null);function os({children:o}){let e=L();return Ga.createElement(To,{value:{router:e.router}},o)}function vt(){if(!ns(To))throw new Error("useRouter must be used within a RouterProvider");return ns(To).router}import ss from"react";import za from"clsx";import Fa,{createContext as Ua,useContext as Oa,useLayoutEffect as Ka,useReducer as Va,useState as Wa}from"react";var Lt=class Lt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new Y().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(Lt.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(Lt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(Lt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(Lt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(Lt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(Lt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};Lt.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 bo=Lt,Co=Ua(null);function rs({children:o}){"use client";let[e]=Wa(()=>new bo);return Fa.createElement(Co,{value:{ratio:e}},o)}function ge(){let o=Oa(Co),[,e]=Va(n=>n+1,0);if(!Co||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return Ka(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function St({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=ge(),s=r.getStyle();return ss.createElement("div",{className:za("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},ss.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import Ba,{useEffect as $a}from"react";function at(o){let e=L(),[t,n]=Ba.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return $a(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import Ao from"react";import wi from"react";import as from"clsx";function ki({children:o,className:e,style:t,...n}){let{ratio:i}=ge(),r=L();return wi.createElement(St,{className:as("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},wi.createElement("div",{className:"absolute inset-0 w-full h-full"},wi.createElement("div",{className:"inset-0 w-full h-full"},wi.createElement("div",{className:as("pointer-events-auto-rest",e),style:t},o))))}function ja({children:o,className:e,style:t}){return Ao.createElement(Ao.Fragment,null,Ao.createElement(ki,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import cs from"clsx";import ls from"react";function Pi({className:o,children:e,...t}){let{ratio:n}=ge();return ls.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:cs("w-full h-full")},ls.createElement("div",{className:cs("z-20",o),...t},e))}import ot,{useState as us}from"react";import{motion as qa}from"motion/react";function Ei({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=L(),[l,u]=us(!1);if(!c.config.app.inspector)return ot.createElement(r,{...a,ref:s},o);let p={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return ot.createElement(r,{...p,ref:s},n&&l&&ot.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function Qa({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=L(),[a,c]=us(!1);if(!s.config.app.inspector)return ot.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 ot.createElement("div",null,ot.createElement(i,{...l}),t&&a&&ot.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function Xa(o){return ot.createElement(Ei,{...o,as:"div"})}function Ya(o){return ot.createElement(Ei,{...o,as:"span"})}function Ja(o){return ot.createElement(Qa,{...o,as:"img"})}function Za(o){return ot.createElement(Ei,{...o,as:"button"})}function _a(o){return ot.createElement(Ei,{...o,as:qa.div,ref:o.ref,layout:o.layout})}var ec={Div:Xa,Span:Ya,Button:Za,Img:Ja,mDiv:_a},Qt=ec;import Ri from"clsx";import Ne,{useEffect as fn,useRef as hs,useState as xo}from"react";import{useEffect as tc,useState as nc}from"react";function re(o){let[e,t]=nc(0);tc(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import ps from"react";var Xt=ps.createContext(null);function ct(){let o=ps.useContext(Xt);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import Di,{useCallback as ic,useLayoutEffect as Nn,useMemo as ds,useRef as ms}from"react";import{useIsPresent as oc}from"motion/react";var lt=class lt{constructor(e){this.events=new Y;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.config=e,this._state="pending",this.autoForwardScheduler=new Jn,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(lt.Events.complete):this.safeEmit(lt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(lt.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(lt.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(_.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(lt.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.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(lt.Events.onFlush),this}onFlush(e){return this.events.on(lt.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;!this._active||!e.getPreference(_.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(lt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(_.Preferences.gameSpeed))}};lt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Ae=lt;function Gn({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=oc(),s=i&&r,a=ms(!1),c=ms(o),l=c.current!==o,u=ds(()=>o.sentence?.evaluate(Se.getCtx({gameState:n})),[o.sentence,n]),p=ds(()=>new Ae({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:l}),[o,n,t,u]),d=n.game.config.dialog,g=ic(h=>{!s||a.current||(a.current=!0,e?.(h))},[s,e]);return Nn(()=>{a.current=!1},[p]),Nn(()=>{c.current=o},[o]),Nn(()=>(p.setActive(s),()=>{p.setActive(!1)}),[p,s]),Nn(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",p),p.events.on(Ae.Events.complete,h=>{n.logger.log("NarraLeaf-React: Say","Complete",p.isIdle()),s&&(p.isIdle()||h?g(!1):p.setIdle(!0))}).cancel),[p,g,n,s]),Nn(()=>n.events.on(P.EventTypes["event:state.player.skip"],h=>{s&&(h?(p.setIdle(!0),p.forceSkip()):p.isIdle()?g(!0):p.forceSkip())}).cancel,[p,g,n,s]),Di.createElement(Di.Fragment,null,Di.createElement(Xt,{value:p},Di.createElement(d,null)))}import{useEffect as Li,useState as ac}from"react";import{useEffect as rc,useState as sc}from"react";function Yt(o){let e=L(),[t,n]=sc(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return rc(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var mn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(mn||{});function Ii({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=L(),[s]=Yt("nextAction"),[a]=ac(()=>new Ae({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e}));return Li(()=>{if(!n)return;let c=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},l=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(P.EventTypes["event:state.player.stageClick"],c),p=e.events.on(P.EventTypes["event:state.player.skip"],l);return()=>{u.cancel(),p.cancel()}},[a,o.id,e,n]),Li(()=>{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]),Li(()=>{let c=a.events.on(Ae.Events.complete,l=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!l&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),Li(()=>{let c=a.events.on(Ae.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{c.cancel()}},[a,n]),a}function*ko(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(Re.isPause(n.text)){yield Re.from(n.text);continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
35
+ 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 I("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(S.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(S.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 S().registerSkipController(new F(()=>{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(S.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&&S.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&&S.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 Pe("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().frames)),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?S.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?S.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()):S.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&&z.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 at=class at{constructor(e){this.events=new te;this.story=null;this.gameLock=new cn;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 Ln,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new St(at.GameSpacesKey.game,at.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:Jr,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,p]=this.constructMaps();this.initNamespaces(),this._storable.load(i),s.forEach(({id:d,data:g})=>{t.logger.debug("restore element",d);let m=p.get(d);if(!m)throw new Error("Element not found, id: "+d+`
36
+ NarraLeaf cannot find the element with the id from the saved game`);m.reset(),m.fromData(g)}),this.currentSavedGame=e,t.loadData(r,p),this.stackModel.deserialize(c,u),l.forEach(d=>{let g=Ke.createStackModel(this,d,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(L.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===an.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(r,i),s===this.stackModel&&this.stackModel.push(Ke.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=S.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 Se({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(L.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=i!==null?{reachedTarget:!1}:{},c=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let l=0;for(;l++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...a};if(this.stackModel.isEmpty())return{reason:"end",...a};let u=this.stackModel.getWaitingAwaitable();if(u){let p=new Promise(d=>u.onSettled(()=>d()));t.events.emit(L.EventTypes["event:state.player.skip"],!0),await p}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...a}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(c)}}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(at.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(at.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(at.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(Ke.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 Ke(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 Ke(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(at.EventTypes["event:action.current"])&&this.events.emit(at.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type});let i=t.executeAction(e,n);return S.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Pe("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Ke(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Pe("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),[vt].some(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(re,q.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(_,Z.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 Pe("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Pe("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:$r(),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 I("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 I("Player Element Not Mounted")}};at.DefaultNamespaces={game:{}},at.GameSpacesKey={game:"game"},at.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"};var bt=at;var Fn=class Fn{constructor(e){this.settings=e;this.events=new te;this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(Fn.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(Fn.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))}};Fn.EventTypes={"event:game.preference.change":"event:game.preference.change"};var Un=Fn;import"client-only";import $s,{useEffect as Pl,useRef as _o}from"react";import"client-only";import as,{useContext as cs,useState as Qa}from"react";var Do=as.createContext(null);function ls({children:o,game:e}){"use client";let t=new ne({}),[n]=Qa(e||t);return as.createElement(Do,{value:n},o)}function R(){let o=cs(Do);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function us(){return cs(Do)}import Xa,{createContext as Ja,useContext as ps}from"react";var ds="/",Mi=class Mi{constructor(e,t=Mi.rootPath){this.events=new te;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 I(`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 I(`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(),qe(()=>{t()}))})}else qe(()=>{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)}};Mi.rootPath=ds;var Bt=Mi,Lo=Ja(null);function ms({children:o}){let e=R();return Xa.createElement(Lo,{value:{router:e.router}},o)}function xt(){if(!ps(Lo))throw new Error("useRouter must be used within a RouterProvider");return ps(Lo).router}import hs from"react";import ic from"clsx";import Ya,{createContext as Za,useContext as _a,useLayoutEffect as ec,useReducer as tc,useState as nc}from"react";var Mt=class Mt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new te().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(Mt.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(Mt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(Mt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(Mt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(Mt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(Mt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};Mt.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 Io=Mt,Ro=Za(null);function fs({children:o}){"use client";let[e]=nc(()=>new Io);return Ya.createElement(Ro,{value:{ratio:e}},o)}function Te(){let o=_a(Ro),[,e]=tc(n=>n+1,0);if(!Ro||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return ec(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function At({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=Te(),s=r.getStyle();return hs.createElement("div",{className:ic("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},hs.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import oc,{useEffect as rc}from"react";function dt(o){let e=R(),[t,n]=oc.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return rc(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import Mo from"react";import Ni from"react";import gs from"clsx";function Gi({children:o,className:e,style:t,...n}){let{ratio:i}=Te(),r=R();return Ni.createElement(At,{className:gs("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},Ni.createElement("div",{className:"absolute inset-0 w-full h-full"},Ni.createElement("div",{className:"inset-0 w-full h-full"},Ni.createElement("div",{className:gs("pointer-events-auto-rest",e),style:t},o))))}function sc({children:o,className:e,style:t}){return Mo.createElement(Mo.Fragment,null,Mo.createElement(Gi,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import ys from"clsx";import vs from"react";function Hi({className:o,children:e,...t}){let{ratio:n}=Te();return vs.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:ys("w-full h-full")},vs.createElement("div",{className:ys("z-20",o),...t},e))}import ct,{useState as Ss}from"react";import{motion as ac}from"motion/react";function Vi({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=R(),[l,u]=Ss(!1);if(!c.config.app.inspector)return ct.createElement(r,{...a,ref:s},o);let p={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return ct.createElement(r,{...p,ref:s},n&&l&&ct.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function cc({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=R(),[a,c]=Ss(!1);if(!s.config.app.inspector)return ct.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 ct.createElement("div",null,ct.createElement(i,{...l}),t&&a&&ct.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function lc(o){return ct.createElement(Vi,{...o,as:"div"})}function uc(o){return ct.createElement(Vi,{...o,as:"span"})}function pc(o){return ct.createElement(cc,{...o,as:"img"})}function dc(o){return ct.createElement(Vi,{...o,as:"button"})}function mc(o){return ct.createElement(Vi,{...o,as:ac.div,ref:o.ref,layout:o.layout})}var fc={Div:lc,Span:uc,Button:dc,Img:pc,mDiv:mc},tn=fc;import Wi from"clsx";import Ge,{useEffect as bn,useRef as As,useState as No}from"react";import{useEffect as hc,useState as gc}from"react";function de(o){let[e,t]=gc(0);hc(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import Ts from"react";var nn=Ts.createContext(null);function mt(){let o=Ts.useContext(nn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import Fi,{useCallback as yc,useLayoutEffect as On,useMemo as bs,useRef as Cs}from"react";import{useIsPresent as vc}from"motion/react";var ft=class ft{constructor(e){this.events=new te;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.config=e,this._state="pending",this.autoForwardScheduler=new ri,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(ft.Events.complete):this.safeEmit(ft.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(ft.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(ft.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(ne.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(ft.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.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(ft.Events.onFlush),this}onFlush(e){return this.events.on(ft.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;!this._active||!e.getPreference(ne.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(ft.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(ne.Preferences.gameSpeed))}};ft.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var ke=ft;function Kn({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=vc(),s=i&&r,a=Cs(!1),c=Cs(o),l=c.current!==o,u=bs(()=>o.sentence?.evaluate(Ae.getCtx({gameState:n})),[o.sentence,n]),p=bs(()=>new ke({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:l}),[o,n,t,u]),d=n.game.config.dialog,g=yc(m=>{!s||a.current||(a.current=!0,e?.(m))},[s,e]);return On(()=>{a.current=!1},[p]),On(()=>{c.current=o},[o]),On(()=>(p.setActive(s),()=>{p.setActive(!1)}),[p,s]),On(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",p),p.events.on(ke.Events.complete,m=>{n.logger.log("NarraLeaf-React: Say","Complete",p.isIdle()),s&&(p.isIdle()||m?g(!1):p.setIdle(!0))}).cancel),[p,g,n,s]),On(()=>n.events.on(L.EventTypes["event:state.player.skip"],m=>{s&&(m?(p.setIdle(!0),p.forceSkip()):p.isIdle()?g(!0):p.forceSkip())}).cancel,[p,g,n,s]),Fi.createElement(Fi.Fragment,null,Fi.createElement(nn,{value:p},Fi.createElement(d,null)))}import{useEffect as Ui,useState as bc}from"react";import{useEffect as Sc,useState as Tc}from"react";function on(o){let e=R(),[t,n]=Tc(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return Sc(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Tn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Tn||{});function Oi({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=R(),[s]=on("nextAction"),[a]=bc(()=>new ke({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e}));return Ui(()=>{if(!n)return;let c=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},l=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(L.EventTypes["event:state.player.stageClick"],c),p=e.events.on(L.EventTypes["event:state.player.skip"],l);return()=>{u.cancel(),p.cancel()}},[a,o.id,e,n]),Ui(()=>{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]),Ui(()=>{let c=a.events.on(ke.Events.complete,l=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!l&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),Ui(()=>{let c=a.events.on(ke.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{c.cancel()}},[a,n]),a}function Cc(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&&(M.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function Ki(o,e,t){e.has(o)||(e.add(o),Cc(o,t))}function*Ho(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(Me.isPause(n.text)){yield Me.from(n.text);continue}if(Ye.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
35
37
  `?yield`
36
- `:yield{text:r,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function wo(o){let e=ko(o),t=[];for(let n of e)Re.isPause(n)||t.push(n);return t}function gs(o,e){o(t=>{let n=t[t.length-1];return n&&n!==`
38
+ `:yield{text:r,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function Go(o){let e=Ho(o),t=[];for(let n of e)Me.isPause(n)||Ye.isTextEvent(n)||t.push(n);return t}function ws(o,e){o(t=>{let n=t[t.length-1];return n&&n!==`
37
39
  `&&e!==`
38
- `&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function cc(o,e,t){return t||(o!==void 0?pe.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new q(n.text,n.config)):[])}function lc(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 fs(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function Mi(o){return o===void 0?void 0:on(o)}function Po({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,...c}){let l=L(),u=l.getLiveGame().getGameState(),p=hs(null),[d,g]=xo(()=>n&&!n.config.useTypeEffect?wo(n.config.evaluatedWords):[]),[h,v]=re();if(!n)throw new Error("Dialog state is required");fn(()=>{if(!(!n.config.action.sentence||p.current))return u.logger.info("Initializing the sentence",n,p.current),u.schedule(({onCleanup:b})=>{if(!n.config.useTypeEffect){n.dispatchComplete();return}g([]),p.current=f(),h(),p.current.onComplete(()=>{n.dispatchComplete()}),b(()=>{p.current?.timeline?.abort()})},0)},[]),fn(()=>n.events.depends([n.events.on(Ae.Events.requestComplete,()=>{p.current?.interact()}),n.events.on(Ae.Events.forceSkip,()=>{n.isEnded()||p.current?.forceSkip()})]).cancel,[n,v]),fn(()=>l.preference.events.depends([l.preference.onPreferenceChange(_.Preferences.gameSpeed,()=>{p.current?.update()}),l.preference.onPreferenceChange(_.Preferences.autoForward,()=>{p.current?.update()}),l.preference.onPreferenceChange(_.Preferences.cps,()=>{p.current?.update()})]).cancel,[]);function f(){let b=new y,x=new ke(b).setGuard(u.guard),N=new Set,H=new Set,te=new Set,Te=ko(n.config.evaluatedWords),Pe=null,xt=[],ze=[],ye=()=>{xt.forEach(W=>W()),xt.length=0},F=()=>{if(ze.length!==0)return{done:!1,value:ze.shift()};let{done:W,value:D}=Te.next();return{done:W,value:D}},se=W=>{let D=O=>{W(O),H.delete(D)};return H.add(D),{cancel:()=>{H.delete(D)}}},X=W=>{gs(g,W)},ne=(W=!1)=>{let D=!1;for(;!D;){let{done:O,value:Q}=F();if(O){D=!0;break}if(Re.isPause(Q)){if(W)continue;D=!0,ze.push(Q);break}else Q===`
39
- `?g(k=>[...k,Q]):typeof Q=="object"&&"text"in Q&&!N.has(Q)&&(N.add(Q),X(Q))}Pe&&!Pe.isSettled()?Pe.abort():(te.forEach(O=>O()),b.resolve())};return u.schedule(async W=>{let D=!1,O=!1;for(;!D;){let{done:Q,value:k}=F();if(Q){D=O=!0;break}let Be=new y;if(u.timelines.attachTimeline(Be),Be.registerSkipController(new U(()=>{ye(),D=!0,W.retry()})),Be.onSettled(()=>{ye()}),Pe=Be,Re.isPause(k)){let wt=Re.from(k),qn=l.preference.getPreference(_.Preferences.gameSpeed);if(wt.config.duration){let Qn=wt.config.duration/qn;await ii(Qn)}else{let Qn=l.preference.getPreference(_.Preferences.autoForward),Xn=y.race([y.create(ya=>{let va=se(Sa=>{Sa(),ya.resolve()});xt.push(()=>va.cancel())}),...Qn?[y.delay(l.config.autoForwardDefaultPause/qn)]:[]]);u.timelines.attachTimeline(Xn),await y.wait(Xn)}}else{if(k!==`
40
- `&&N.has(k))continue;N.add(k),X(k);let{gameSpeed:wt,cps:qn}=l.preference.getPreferences(),Xn=1e3/((typeof k=="object"&&"cps"in k&&k.cps!==void 0?k.cps:qn)*wt);await ii(Xn)}}O&&(te.forEach(Q=>Q()),b.resolve())},0),{getToken:()=>b,interact:()=>{let W=!1;H.forEach(D=>D(()=>W=!0)),!W&&ne()},update:()=>{Pe&&Pe.abort()},forceSkip:()=>{ne(!0)},timeline:x,onComplete:W=>(te.add(W),{cancel:()=>{te.delete(W)}})}}let T=n.config.action.sentence;if(!T)return null;let m=s??"bold",S={fontWeight:T.config.bold?m:r,fontSize:T.config.fontSize??i,color:Mi(T.config.color??o),fontFamily:T.config.fontFamily??a,fontStyle:T.config.italic?"italic":void 0},I=b=>({fontWeight:b.config.bold||T.config.bold?m:r,fontSize:b.config.fontSize??T.config.fontSize??i,color:Mi(b.config.color??T.config.color??o),fontFamily:b.config.fontFamily??T.config.fontFamily??a,fontStyle:b.config.italic??T.config.italic?"italic":void 0}),C=(b,x)=>b===`
41
- `?Ne.createElement("br",{key:x}):Ne.createElement(Qt.Span,{tag:`say.word.${x}`,key:x,style:{...I(b),...oi(l.config.app.debug,{outline:"1px dashed red"})},className:Ri("inline-block break-all",b.config.className)},b.config.ruby?Ne.createElement("ruby",{className:"align-bottom inline-block"},Ne.createElement("rt",{className:"block text-center"},b.config.ruby),b.text):b.text);return Ne.createElement("div",{...c,className:Ri("whitespace-pre-wrap",e),style:{...S,...t}},d.map(C))}function uc({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:p,fontSize:d,fontWeight:g,fontWeightBold:h,fontFamily:v,onCompleted:f,...T}){let m=ts(),[,S]=xo(0),I=m?.config??_.DefaultConfig,C=m?.preference.getPreferences()??_.DefaultPreference,b=s??C.cps,x=a??C.gameSpeed,N=c??I.autoForwardDefaultPause,H=r??I.autoForwardDefaultPause,te=Ne.useMemo(()=>cc(o,e,t),[o,e,t]),Te=Ne.useMemo(()=>lc(i,r,H),[i,r,H]),Pe=hs(f),[xt,ze]=xo(()=>n?[]:wo(te));fn(()=>{if(m)return m.preference.onPreferenceChange(()=>{S(G=>G+1)}).cancel},[m]),fn(()=>{Pe.current=f},[f]),fn(()=>{let G=!1,ae=[],ue=Math.max(.01,x),ie=O=>new Promise(Q=>{let k=setTimeout(Q,Math.max(0,O));ae.push(k)}),W=()=>{G||Pe.current?.()};return n?te.length===0?(ze([]),()=>{G=!0}):((async()=>{do{let O=ko(te);for(ze([]);!G;){let{done:Q,value:k}=O.next();if(Q)break;if(Re.isPause(k)){let Be=Re.from(k);await ie((Be.config.duration??N)/ue)}else gs(ze,k),k===`
42
- `?await ie(fs(b,x)):await ie(fs(k.cps??b,x))}if(G)return;W(),Te.enabled&&await ie(Te.delay)}while(!G&&Te.enabled)})(),()=>{G=!0,ae.forEach(O=>clearTimeout(O))}):(ze(wo(te)),W(),()=>{G=!0})},[te,n,Te,b,x,N]);let ye=e?.config,F=h??"bold",se={fontWeight:ye?.bold?F:g,fontSize:ye?.fontSize??d,color:Mi(ye?.color??l),fontFamily:ye?.fontFamily??v,fontStyle:ye?.italic?"italic":void 0},X=G=>({fontWeight:G.config.bold||ye?.bold?F:g,fontSize:G.config.fontSize??ye?.fontSize??d,color:Mi(G.config.color??ye?.color??l),fontFamily:G.config.fontFamily??ye?.fontFamily??v,fontStyle:G.config.italic??ye?.italic?"italic":void 0}),ne=(G,ae)=>G===`
43
- `?Ne.createElement("br",{key:ae}):Ne.createElement("span",{key:ae,style:X(G),className:Ri("inline-block break-all",G.config.className)},G.config.ruby?Ne.createElement("ruby",{className:"align-bottom inline-block"},Ne.createElement("rt",{className:"block text-center"},G.config.ruby),G.text):G.text);return Ne.createElement("div",{...T,className:Ri("whitespace-pre-wrap",u),style:{...se,...p}},xt.map(ne))}function ys(o){return Ne.createElement(Po,{...o,key:o.dialog?.config.action.id})}function pc({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=Ii({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Ne.createElement(Po,{...r,dialog:s,key:s.config.action.id})}function dc(o){let e=ct();return Ne.createElement(Po,{...o,dialog:e,key:e.config.action.id})}function Ot(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Ne.createElement(pc,{...o}):Ne.createElement(dc,{...o})}var mc=Ot;import Gi,{useEffect as fc,useLayoutEffect as hc,useMemo as Ss,useRef as gc,useState as yc}from"react";import Ni from"react";var Eo=Ni.createContext(null);function Do(){let o=Ni.useContext(Eo);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Lo=Ni.createContext(null);function vs(){let o=Ni.useContext(Lo);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function Hi({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let c=gc(null),{register:l,unregister:u,getIndex:p}=vs(),[d,g]=yc(-1),{choose:h,evaluated:v,gameState:f}=Do(),T=d===-1?null:v[d],m=Ss(()=>Se.getCtx({gameState:f}),[f]),{hidden:S,disabled:I}=Ss(()=>{if(!T)return{hidden:!1,disabled:!1};let x=T.config.hidden?.evaluate(m)?.value??!1,N=!x&&(T.config.disabled?.evaluate(m)?.value??!1);return{hidden:x,disabled:N}},[T,m]);hc(()=>{if(!c.current)return;let x=c;l(x);let N=p(x);return g(N),c.current.dataset.index=N.toString(),()=>u(x)},[l,u,p]),fc(()=>{if(!t)return;let x=N=>{N.key.toLowerCase()===t.toLowerCase()&&!N.ctrlKey&&!N.metaKey&&(N.preventDefault(),N.stopPropagation(),C())};return window.addEventListener("keydown",x,!0),()=>{window.removeEventListener("keydown",x,!0)}},[t]);function C(){if(d===-1||!v[d]||S||I)return;let x=v[d];h({...x,evaluated:q.getText(x.words||[])})}let b=T&&!S;return Gi.createElement(Gi.Fragment,null,Gi.createElement("button",{className:o,style:{...e,display:b?e?.display??void 0:"none"},onClick:C,ref:c,disabled:I},b&&Gi.createElement(ys,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Ae({useTypeEffect:!1,action:{sentence:T.prompt,words:T.words,character:null},gameState:f,evaluatedWords:T.words})})))}import Fi from"react";import{AnimatePresence as vc}from"motion/react";function Ui({children:o,...e}){let t=vc;return Fi.createElement(Fi.Fragment,null,Fi.createElement("div",{...e},Fi.createElement(t,null,o)))}import Ts from"react";function It({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=Ts.useContext(Xt),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return Ts.createElement("div",{...s,style:{color:l?on(l):void 0,...r}},u)}import Sc from"clsx";import Tc from"react";function bs(){let o=ct(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return Ac(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=Xr({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=Cc(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function bc({className:o,style:e,alt:t,...n}){let i=bs();return!i.visible||!i.src?null:Tc.createElement("img",{...n,"data-element-type":"dialog-avatar",className:Sc("dialog-avatar",o),src:i.src,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function Cc(o){return o?w.srcToURL(o):null}function Ac(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var Io=bc;import{useEffect as xc}from"react";function wc(){let o=ct(),[e]=re(o.deps),t=q.getText(o.config.evaluatedWords);return xc(()=>o.events.on(Ae.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 Oi,useEffect as Ro,useMemo as kc,useRef as Pc,useState as Cs}from"react";function Ec(){let o=ct(),[e]=re(o.deps),[t,n]=Cs(!0),[i,r]=Cs(!0),s=Pc(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Ro(()=>o.events.on(Ae.Events.onFlush,()=>{e()}).cancel,[o]);let u=kc(()=>{if(!c)return null;try{return st.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Ro(()=>{s.current=null,r(!0)},[c]),Ro(()=>{let v=!1,f=null,T=null,m=null;if(!u){n(!0);return}n(!1);let S=()=>{v||n(!0)};f=a.audioManager.getToken(u),f&&(f.isPlaying()||n(!0),T=()=>S(),m=()=>S(),f.once("ended",T),f.once("stop",m));let I=a.events.on(P.EventTypes["event:state.player.lineEnd"],()=>{S()});return()=>{v=!0,I.cancel(),f&&T&&f.off("ended",T),f&&m&&f.off("stop",m)}},[a,u]);let p=Oi(async v=>{let f=v??u;if(!f)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let T=f instanceof URL?fe.voice(f.toString()):typeof f=="string"?fe.voice(f):f,m=await a.getLiveGame().playSound(T);s.current=m;let S=()=>{r(!0)};return m.once("ended",S),m.once("stop",S),m},[a,u]),d=Oi(()=>u,[u]),g=Oi(()=>l,[l]),h=Oi(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:p,getVoice:d,getVoiceId:g,getVoiceSrc:h}}import Mo,{createContext as Kc,useContext as Vc,useEffect as ws,useRef as Wc}from"react";import{useState as Dc}from"react";function Ki(o){let[e]=Dc(o);return e}import{AnimatePresence as Lc}from"motion/react";var Vi=Lc;import On,{createContext as Gc,useContext as Hc,useEffect as Fc,useRef as Uc}from"react";import{useEffect as Hn,useLayoutEffect as Ic}from"react";function Rc(){let o=vt(),[e]=re();return Hn(()=>o.onChange(e).cancel,[]),o.getPathname()}function Mc(){let{router:o,path:e}=Un(),[t]=re();return Hn(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function Nc(){let o=vt(),[e]=re();return Hn(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Wi(o,e){let t=vt();Ic(()=>t.onUpdate(()=>o(t)).cancel,e),Hn(()=>{o(t)},[])}function Fn(){let o=vt(),[e]=re();return Hn(()=>o.onChange(e).cancel,[]),e}var As=Gc(null);function Kn({children:o,path:e,consumedBy:t}){let i={router:vt(),path:e,consumedBy:t};return On.createElement(As,{value:i},o)}function Un(){let o=Hc(As);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new E(`Invalid useLayout call: Trying to access layout without a parent.
44
- This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Oc({children:o,name:e,propagate:t}){let n=L(),[i]=re(),{path:r,router:s,consumedBy:a}=Un(),c=s.joinPath(r,e),l=Ki(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),p=Uc(!1),d=h=>{p.current=h,i()},g=s.matchPath(u,c);if(Fn(),Wi(h=>{let v=h.matchPath(h.getCurrentPath(),c);if(p.current&&!v){if(!o){d(!1);return}h.registerUnmountingPath(l)}v&&h.isPathsUnmounting()&&h.unregisterUnmountingPath(l),v&&!p.current&&!h.isTransitioning()&&d(!0)},[g,o]),Fc(()=>{if(!g)return;let h=s.mount(c);return()=>{h.cancel()}},[c,s,g]),a)throw new E("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return On.createElement(Kn,{path:c},On.createElement(Vi,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),d(!1)}},g&&p.current&&o))}function xs({children:o}){return Fn(),On.createElement(Kn,{path:Ut.rootPath},On.createElement(ki,{"data-layout-path":Ut.rootPath,key:Ut.rootPath},o))}var No=Kc(null);function zc(){return Vc(No)}function Bc({children:o,name:e}){let[t]=re(),{path:n,router:i,consumedBy:r}=Un(),s=zc(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=Ki(()=>i.createToken(l+"@page")),p=i.getCurrentPath(),d=!a,g=Wc(!1),h=m=>{g.current=m,t()},v=d&&i.exactMatch(p,n)||i.exactMatch(p,l);if(r&&r!==c)throw new E("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");Fn(),Wi(m=>{let S=d&&m.exactMatch(m.getCurrentPath(),n)||m.exactMatch(m.getCurrentPath(),l);if(g.current&&!S){if(!o){h(!1);return}m.registerUnmountingPath(u)}S&&m.isPathsUnmounting()&&m.unregisterUnmountingPath(u),S&&!g.current&&!m.isTransitioning()&&h(!0)},[v,o]),ws(()=>{if(!v)return;let m=d?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{m.cancel()}},[l,v]),ws(()=>()=>{i.unregisterUnmountingPath(u),h(!1)},[]);let f=Mo.createElement(Kn,{path:n,consumedBy:c},Mo.createElement(Vi,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),h(!1)}},v&&g.current&&o));return(m=>s?Mo.createElement(No,{value:{name:null}},m):m)(f)}import Go,{useCallback as $c,useEffect as Ho,useImperativeHandle as jc,useMemo as ks,useRef as Fo,useState as qc}from"react";var Qc=50,Xc={position:"relative",width:"100%",height:"100%",overflow:"hidden"},Ps={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function Yc(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function Es(o,e){return e==null?o:Math.max(o,e)}function Jc(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 Ds=Go.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:p},d){let g=Fo(null),[h,v]=qc({...Ps,width:"0px",height:"0px"}),f=Fo(u),T=Fo(null);Ho(()=>{f.current=u},[u]);let m=$c(()=>{let C=g.current;if(!C)return;let b=C.clientWidth,x=C.clientHeight;if(b<=0||x<=0||e<=0)return;let N=Jc(b,x,e),H=Es(N.width,n),te=Es(N.height,i),Te=T.current;(!Te||Te.width!==H||Te.height!==te)&&(T.current={width:H,height:te},v({...Ps,width:`${H}px`,height:`${te}px`}));let Pe=t>0?H/t:1;f.current?.({width:H,height:te,scale:Pe,containerWidth:b,containerHeight:x})},[e,t,n,i]),S=ks(()=>Dr(m,typeof r=="number"?r:Qc),[m,r]);Ho(()=>{m()},[m]),Ho(()=>{let C=new ResizeObserver(()=>{S()});g.current&&C.observe(g.current);let b=()=>{S()};return window.addEventListener("resize",b),()=>{C.disconnect(),window.removeEventListener("resize",b)}},[S]),jc(d,()=>({requestUpdate:m}),[m]);let I=ks(()=>Yc(l),[l]);return Go.createElement("div",{id:c,ref:g,style:Xc,...I},Go.createElement("div",{className:s,style:{...h,...a}},p))}),Ls=Ds;function Zc(){return L().getLiveGame()}import Ko from"react";import _c,{createContext as el,useContext as tl,useEffect as nl,useState as Is}from"react";var il={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Rs=el({state:il,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function Tt(){return tl(Rs)}function Uo(){let{dialogs:o}=Tt();return o}function ol(){let{isActive:o}=Tt();return o}function rl(){let{isVisible:o}=Tt();return o}function Oo({children:o}){let t=L().getLiveGame().getGameState(),[n,i]=Is(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Is(null);nl(()=>{let c=h=>({...h,dialogs:[...h.dialogs]}),l=t.events.on(P.EventTypes["event:state.nvl.enter"],(h,v)=>{i(c(t.getNvlState())),s(v?.showTransition||null)}),u=t.events.on(P.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),p=t.events.on(P.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),d=t.events.on(P.EventTypes["event:state.nvl.visibilityChange"],(h,v)=>{i(c(t.getNvlState())),s(v||null)}),g=t.events.on(P.EventTypes["event:state.nvl.change"],h=>{i(c(h))});return()=>{l.cancel(),u.cancel(),p.cancel(),d.cancel(),g.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return _c.createElement(Rs.Provider,{value:a},o)}import{AnimatePresence as sl,motion as al}from"motion/react";import cl from"clsx";function Vo({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=Tt(),{ratio:r}=ge(),s=L(),a=i?.duration?i.duration/1e3:.3;return Ko.createElement(sl,null,n&&Ko.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},Ko.createElement(al.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:cl("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 Jt from"react";function Wo({renderDialogItem:o,dialogs:e}){return Jt.createElement(Vo,{className:"bg-black/80 text-white p-16 inset-8"},Jt.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?Jt.createElement(It,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=Jt.createElement(Ot,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return Jt.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}):Jt.createElement(Jt.Fragment,null,r,s))})))}import tt,{useMemo as ll}from"react";import Ms from"clsx";function ul({children:o,className:e,style:t,renderDialogItem:n}){let i=Uo(),{state:r}=Tt();return tt.createElement("div",{"data-element-type":"nvl-dialog-list",className:Ms("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>tt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},tt.createElement(pl,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?tt.createElement(It,{className:"nvl-character-name font-bold mr-2"}):null,texts:tt.createElement(Ot,{className:"nvl-dialog-text"})}):o?tt.Children.map(o,c=>tt.isValidElement(c)?tt.cloneElement(c,{entry:s,index:a}):c):tt.createElement(Ns,{entry:s,index:a})))))}function Ns({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??tt.createElement(Ot,{className:"nvl-dialog-text"});return tt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Ms("nvl-dialog-item",t),style:n},r&&tt.createElement(It,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function pl({entry:o,children:e}){let n=L().getLiveGame().getGameState(),i=ll(()=>o.sentence.evaluate(Se.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=Ii({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return tt.createElement(Xt,{value:c},e)}function Hs({state:o}){let e=L(),t=vt(),n=zo(null),i=zo(null),r=zo(!1),[s]=at(_.Preferences.skipDelay),[a]=at(_.Preferences.skipInterval),[c]=Yt("skipAction");return ml(()=>{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},p=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(_.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let h=()=>{n.current=setInterval(()=>{o.events.emit(P.EventTypes["event:state.player.skip"],!1)},a)};u(),o.events.emit(P.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?h():i.current=setTimeout(h,s)}},d=g=>{e.keyMap.match("skipAction",g.key)&&u()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",p).cancel,h=e.getLiveGame().onWindowEvent("keyup",d).cancel;return()=>{u(),g(),h()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",p).cancel,h=e.getLiveGame().onPlayerEvent("keyup",d).cancel;return()=>{u(),g(),h()}}},[t,s,a,c]),Gs.createElement(Gs.Fragment,null)}import Fs,{useEffect as fl}from"react";function hl(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var Us=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],gl=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]'];function yl(o,e){return!o||e&&Us.some(t=>!!o.closest(t))?!1:[...gl,...Us].some(t=>!!o.closest(t))}function Os(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 Ks({state:o}){let e=L();return fl(()=>{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)||!Os(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!Os(i,s))||hl(r)||yl(r,o.isNvlMode())||(o.events.emit(P.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]),Fs.createElement(Fs.Fragment,null)}import{useEffect as Vn}from"react";function Bo({gameState:o}){let e=o.audioManager,[t]=at("voiceVolume"),[n]=at("bgmVolume"),[i]=at("soundVolume"),[r,s]=at("globalVolume");return Vn(()=>{s(e.getGlobalVolume())},[]),Vn(()=>{e.setGroupVolume("voice",t)},[t]),Vn(()=>{e.setGroupVolume("bgm",n)},[n]),Vn(()=>{e.setGroupVolume("sound",i)},[i]),Vn(()=>{e.setGlobalVolume(r)},[r]),null}import{useEffect as Bi,useRef as Tl}from"react";import $o,{createContext as vl,useContext as Sl,useState as Vs}from"react";var Zt=class Zt{constructor(){this.preloaded=[];this.events=new Y}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Zt.EventTypes["event:preloaded.add"],e),this.events.emit(Zt.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(Zt.EventTypes["event:preloaded.remove"],e),this.events.emit(Zt.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Fe.getSrc(e)}};Zt.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 Ge=Zt;var zi=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return Ir(e,{...n,signal:t})}static decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return Promise.resolve();let t=new window.Image;return t.src=e,typeof t.decode!="function"?Promise.resolve():t.decode().catch(()=>{})}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}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let n=t,i={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(p,d)=>{n=p,i={...i,...d}}]);let r=new AbortController,s=r.signal,a=[],l={promise:o.getImage(n,s,i).then(async p=>{this.preloadTasks.delete(t),p&&(this.add(t,p),await o.decodeImage(p))}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),a.forEach(d=>d(p))}),controller:r};this.preloadTasks.set(t,l);let u={abort:()=>{r.abort(),this.preloadTasks.delete(t)},onFinished:p=>(l.promise.then(p),u),onErrored:p=>(a.push(p),u)};return u}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){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var jo=vl(null);function Ws({children:o}){let e=L(),[t]=Vs(()=>new Ge),[n]=Vs(()=>new zi(e));return $o.createElement($o.Fragment,null,$o.createElement(jo,{value:{preloaded:t,cacheManager:n}},o))}function hn(){if(!jo)throw new Error("usePreloaded must be used within a PreloadedProvider");return Sl(jo)}function zs({state:o}){let{preloaded:e,cacheManager:t}=hn(),n=L(),i=Tl(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(Ge.EventTypes["event:preloaded.unmount"])}return Bi(()=>o.events.on(P.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Bi(()=>{if(typeof fetch>"u")return e.events.emit(Ge.EventTypes["event:preloaded.complete"]),e.events.emit(Ge.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(Ge.EventTypes["event:preloaded.complete"]),e.events.emit(Ge.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 p=performance.now(),d=Fe.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),g=new Cn(n.config.preloadConcurrency,n.config.preloadDelay),h=[],v=o.logger.group(s,!0),f=[];o.logger.debug(s,"preloading:",d,a);for(let T of d.image){let m=Fe.getSrc(T);if(m){if(h.push(m),t.has(m)||t.isPreloading(m)||f.includes(m)){o.logger.debug(s,`Image already loaded (${d.image.indexOf(T)+1}/${d.image.length})`,m),f.push(m);continue}f.push(m),g.addTask(()=>new Promise(S=>{t.preload(o,m).onFinished(()=>{o.logger.debug(s,`Image loaded (${d.image.indexOf(T)+1}/${d.image.length})`,m),S()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${d.image.indexOf(T)+1}/${d.image.length})`,m),S()})}))}}return v.end(),g.start().then(()=>{o.logger.info(s,"Image preload",`loaded ${t.size()} images in ${performance.now()-p}ms`),e.events.emit(Ge.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(Ge.EventTypes["event:preloaded.ready"]),t.filter(h)}),n.config.waitForPreload||e.events.emit(Ge.EventTypes["event:preloaded.ready"]),e.events.emit(Ge.EventTypes["event:preloaded.mount"]),u},[a,l]),Bi(()=>{i.current.clear()},[a]),Bi(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let p=performance.now(),d=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(m=>Fe.getPreloadableSrc(l,m)).filter(function(m){return m!==null});d.filter(function(m){return m?.activeType==="scene"}).forEach(m=>{i.current.has(m)||i.current.add(m)});let h=Fe.catSrc([...i.current,...d]),v=new Cn(n.config.preloadConcurrency,n.config.preloadDelay),f=[],T=o.logger.group(s);o.logger.debug(s,"preloading:",h);for(let m of h.image){let S=Fe.getSrc(m);if(S){if(f.push(S),t.has(S)||t.isPreloading(S)){o.logger.debug(s,`Image already loaded (${h.image.indexOf(m)+1}/${h.image.length})`,S);continue}v.addTask(()=>new Promise(I=>{t.preload(o,S).onFinished(()=>{o.logger.debug(s,`Image loaded (${h.image.indexOf(m)+1}/${h.image.length})`,S),I()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${h.image.indexOf(m)+1}/${h.image.length})`,S),I()})}))}}T.end(),v.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-p}ms`),t.filter(f)})},[c,l]),null}import bl from"clsx";import bt,{useCallback as qo,useMemo as Cl,useRef as Al}from"react";function Qo({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=L(),a=Al([]),c=qo(h=>(a.current.push(h),a.current.indexOf(h)),[]),l=qo(h=>{let v=a.current.indexOf(h);v!==-1&&a.current.splice(v,1)},[]),u=qo(h=>a.current.indexOf(h),[]),p=s.config.menu,d=Cl(()=>e.map(h=>({...h,words:h.prompt.evaluate(Se.getCtx({gameState:n}))})),[]);function g(h){t(h)}return bt.createElement(bt.Fragment,null,bt.createElement(Eo,{value:{evaluated:d,choose:g,gameState:n}},bt.createElement(Lo,{value:{register:c,unregister:l,getIndex:u}},bt.createElement(St,{className:"absolute"},r&&o&&bt.createElement(Gn,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),bt.createElement(Qt.Div,{color:"green",border:"dashed",className:bl("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},bt.createElement(p,{items:d.map((h,v)=>v)})))))}function Bs({items:o}){return bt.createElement(Pi,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>bt.createElement(Hi,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Xi from"react";import $i from"react";import Xo,{useEffect as Yo,useLayoutEffect as Jo,useRef as Zo,useState as _o}from"react";function gn({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,u]=_o(null),[p,d]=_o(null),g=Xo.useRef(null),[h]=_o(()=>new Zn("displayable.refGroup")),v=Zo(h.next()),f=Zo(ze()),m=L().getLiveGame().getGameState(),S=typeof a=="function"?a(l):a,[I]=re([p,l,f]);Yo(()=>m.events.depends([m.events.on(P.EventTypes["event:state.player.skip"],xt)]).cancel,[p,l,f]),Jo(()=>{if(x(),!l)return;if(f.current.some(([ae])=>!ae.current))throw new E("Displayable: Trying to access transition groups before they are mounted");let{controller:F,task:se}=l,X=ae=>{f.current.forEach(([ue],ie)=>{let W=se.resolve[ie],D=typeof W=="function"?W:W.resolver;if(!D)throw new E(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${ie}])`);let O=D(...ae),Q=K(S[ie]||S[S.length-1]||{},O);H(ue,c?c(Q):Q)})},ne=F.onUpdate(X);X(se.animations.map(ae=>ae.start));let G=!1;return Promise.all(f.current.map(([ae])=>{let ue=ae.current;return ue?.waitForLoad?ue.waitForLoad():Promise.resolve()})).then(()=>{G||F.start()}),()=>{G=!0,ne.cancel()}},[l]),Yo(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Jo(()=>{let F=e.toStyle(m,i);Object.assign(g.current.style,F),m.logger.debug("Displayable","Initial style applied",g.current,F)},[]);let C=Zo(()=>{});C.current=()=>{p||l||!g.current||(Object.assign(g.current.style,e.toStyle(m,i)),x())},Jo(()=>{C.current()});let{ratio:b}=ge();Yo(()=>b.onUpdate(()=>{C.current(),requestAnimationFrame(()=>C.current())}),[b]);function x(){let F=typeof a=="function"?a(l):a;if(!f.current||!f.current.length)throw new E("Displayable: Transition group refs are not initialized correctly");f.current.some(([se])=>!se.current)||f.current.forEach(([se],X)=>{H(se,F[X]||F[F.length-1]||{})})}function N(F){m.logger.debug("Displayable","Transform applied",e.toStyle(m,i),g.current),I(),r?.(F)}function H(F,se){if(!F.current)throw new E("Displayable: Trying to assign properties to unmounted element");let X=F.current,ne={},G={};Object.keys(se).forEach(ue=>{let ie=ue;ie==="style"&&se.style?Object.assign(ne,se.style):se[ie]!==void 0&&ie!=="key"&&(G[ie]=se[ie])}),Object.keys(ne).length>0&&Object.assign(X.style,ne);let ae=c?c(G):G;for(let[ue,ie]of Object.entries(ae))X.getAttribute(ue)!==ie&&X.setAttribute(ue,ie)}function te(F,se){p&&(p.abort(),d(null));let X=F.animate(e,{gameState:m,ref:g,overwrites:i}),ne=new ke(X);return m.timelines.attachTimeline(ne),X.onSkipControllerRegister(G=>{G.onAbort(()=>{ne.abort(),d(null)})}),d(X),X.then(()=>{d(null),N(F),se()}),ne}function Te(F,se){l&&l.controller.complete();let X=F.createTask(m),ne=F.requestAnimations(X.animations),G=new y().registerSkipController(new U(ne.cancel)),ae=new ke(G);G.skipController.onAbort(()=>{ne.cancel()}),ne.onCanceled(()=>{ae.abort(),u(null),m.logger.debug("Displayable","Transition cancelled",F)}),ne.onComplete(()=>{ye(),u(null),s?.(F),se(),G.resolve()}),m.timelines.attachTimeline(ae),u({task:X,controller:ne,transition:F,resolve:se});let ue;if(f.current=X.resolve.map(ie=>{let W=Xo.createRef(),D=typeof ie=="function"?void 0:ie.key;if(!D)return[W,h.next()];if(D==="target")return ue=h.next(),[W,ue];if(D==="current")return[W,v.current];throw new E("Displayable: Invalid key type")}),!ue)throw new E("Displayable: No target key found");return v.current=ue,ae}function Pe(F){return m.logger.debug("initDisplayable",o),te(Z.immediate(e.get()),F)}function xt(){t&&p&&(p.abort(),d(null),m.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),m.logger.debug("transition skipped"))}function ze(){return[[Xo.createRef(),v.current]]}function ye(){f.current.forEach(([F])=>{F.current=null}),f.current=ze()}return{transformRef:g,transitionRefs:f.current,transitionTask:l,initDisplayable:Pe,applyTransform:te,applyTransition:Te,updateStyleSync:x,flush:I,deps:[p,l,f]}}import{useEffect as xl}from"react";function Kt(o,e,t=[]){let i=L().getLiveGame().getGameState();return xl(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function er({state:o,text:e}){let{ratio:t}=ge(),[n]=re(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:u}=gn({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:p=>({width:"fit-content",transform:Z.propToCSSTransform(o,p,{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 Kt(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...u]),$i.createElement(Qt.Div,{"data-element-type":"text"},$i.createElement(Qt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([p,d])=>$i.createElement("span",{key:d,ref:p,className:e.config.className},$i.createElement("span",null,e.state.text)))))}import ut,{forwardRef as kl,useCallback as js,useImperativeHandle as Pl,useRef as Qi,useState as qs}from"react";import ji,{useEffect as tr,useRef as yn,forwardRef as wl}from"react";var $s=wl(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=yn(null),{ratio:a}=ge(),[c,l]=ji.useState(0),[u,p]=ji.useState(0),d=yn(null),g=yn(null),h=L(),v=yn(!1),f=yn(null),T=yn(null);ji.useImperativeHandle(r,()=>s.current,[]),tr(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>v.current,configurable:!0},waitForLoad:{value:()=>{let C=()=>{let b=s.current;return!b||typeof b.decode!="function"?Promise.resolve():b.decode().catch(()=>{})};return v.current?C():(f.current||(f.current=new Promise(b=>{T.current=b})),f.current.then(C))},configurable:!0}})},[]),tr(()=>(m(),a.onUpdate(m)),[o]),tr(()=>{let C=new MutationObserver(b=>{b.forEach(x=>{x.type==="attributes"&&x.attributeName==="src"&&s.current&&m()})});return s.current&&C.observe(s.current,{attributes:!0}),()=>{C.disconnect()}},[o]);function m(){if(s.current&&s.current.naturalWidth){let C,b,x;if(s.current.naturalWidth*s.current.naturalHeight===1)C=a.state.width,b=a.state.height,x=`${C} / ${b}`;else{let Te=t?h.config.width/s.current.naturalWidth:1;C=s.current.naturalWidth*a.state.scale*Te,b=s.current.naturalHeight*a.state.scale*Te,x="auto"}let N=d.current,H=!N||N.w!==C||N.h!==b||N.ar!==x,te=!!o&&g.current!==o;if(!H&&!te)return;H&&(d.current={w:C,h:b,ar:x},l(C),p(b),s.current.style.aspectRatio=x),o&&(g.current=o,o(C,b))}}function S(){m(),v.current=!0,T.current&&(T.current(),T.current=null,f.current=null),e&&e()}function I(){v.current=!0,T.current&&(T.current(),T.current=null,f.current=null)}return ji.createElement("img",{ref:s,onLoad:S,onError:I,width:c,height:u,alt:"",src:n,style:i})});$s.displayName="AspectScaleImage";var qi=$s;import Qs from"clsx";import{motion as El}from"motion/react";var Dl={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Xs=kl(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=Qi(null),a=Qi([]),c=o.findIndex(l=>l!==null);return Pl(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(()=>{})}),[]),ut.createElement("div",{ref:s},o.map((l,u)=>l===null?null:ut.createElement(qi,{key:"layer-"+u,ref:p=>{a.current[u]=p},src:t(l),style:Dl,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});Xs.displayName="LayerStack";function Ll(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 Il(o){return R.isStaticSrc(o)?o.state.currentSrc:R.getSrcURL(o)??void 0}var Rl={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function Ml({image:o,state:e}){let[t]=qs(()=>new Y),[n,i]=qs([]),{cacheManager:r}=hn(),s=Qi([]),a=Qi(null),c=R.isLayeredSrc(o)?R.getSrcURLs(o):null;function l(C){return!w.isDataURI(C)&&!r.has(C)&&!r.isPreloading(C)&&!s.current.includes(C)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${C}".
40
+ `&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function xc(o,e,t){return t||(o!==void 0?ve.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new Q(n.text,n.config)):[])}function Ac(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 xs(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function zi(o){return o===void 0?void 0:ln(o)}function Vo({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,...c}){let l=R(),u=l.getLiveGame().getGameState(),p=As(null),[d,g]=No(()=>n&&!n.config.useTypeEffect?Go(n.config.evaluatedWords):[]),[m,y]=de();if(!n)throw new Error("Dialog state is required");bn(()=>{if(!(!n.config.action.sentence||p.current))return u.logger.info("Initializing the sentence",n,p.current),u.schedule(({onCleanup:b})=>{if(!n.config.useTypeEffect){let A=new Set;for(let E of n.config.evaluatedWords)E.isTextEvent()&&Ki(E.text,A,u);n.dispatchComplete();return}g([]),p.current=v(),m(),p.current.onComplete(()=>{n.dispatchComplete()}),b(()=>{p.current?.timeline?.abort()})},0)},[]),bn(()=>n.events.depends([n.events.on(ke.Events.requestComplete,()=>{p.current?.interact()}),n.events.on(ke.Events.forceSkip,()=>{n.isEnded()||p.current?.forceSkip()})]).cancel,[n,y]),bn(()=>l.preference.events.depends([l.preference.onPreferenceChange(ne.Preferences.gameSpeed,()=>{p.current?.update()}),l.preference.onPreferenceChange(ne.Preferences.autoForward,()=>{p.current?.update()}),l.preference.onPreferenceChange(ne.Preferences.cps,()=>{p.current?.update()})]).cancel,[]);function v(){let b=new S,A=new Ee(b).setGuard(u.guard),E=new Set,O=new Set,Y=new Set,ie=new Set,Fe=Ho(n.config.evaluatedWords),ot=null,Be=[],be=[],K=()=>{Be.forEach(k=>k()),Be.length=0},se=()=>{if(be.length!==0)return{done:!1,value:be.shift()};let{done:k,value:H}=Fe.next();return{done:k,value:H}},ee=k=>{let H=fe=>{k(fe),Y.delete(H)};return Y.add(H),{cancel:()=>{Y.delete(H)}}},ae=k=>{ws(g,k)},V=(k=!1)=>{let H=!1;for(;!H;){let{done:fe,value:P}=se();if(fe){H=!0;break}if(Me.isPause(P)){if(k)continue;H=!0,be.push(P);break}else Ye.isTextEvent(P)?Ki(P,O,u):P===`
41
+ `?g(he=>[...he,P]):typeof P=="object"&&"text"in P&&!E.has(P)&&(E.add(P),ae(P))}ot&&!ot.isSettled()?ot.abort():(ie.forEach(fe=>fe()),b.resolve())};return u.schedule(async k=>{let H=!1,fe=!1;for(;!H;){let{done:P,value:he}=se();if(P){H=fe=!0;break}if(Ye.isTextEvent(he)){Ki(he,O,u);continue}let Lt=new S;if(u.timelines.attachTimeline(Lt),Lt.registerSkipController(new F(()=>{K(),H=!0,k.retry()})),Lt.onSettled(()=>{K()}),ot=Lt,Me.isPause(he)){let ei=Me.from(he),ti=l.preference.getPreference(ne.Preferences.gameSpeed);if(ei.config.duration){let ni=ei.config.duration/ti;await pi(ni)}else{let ni=l.preference.getPreference(ne.Preferences.autoForward),ii=S.race([S.create(Ia=>{let Ra=ee(Ma=>{Ma(),Ia.resolve()});Be.push(()=>Ra.cancel())}),...ni?[S.delay(l.config.autoForwardDefaultPause/ti)]:[]]);u.timelines.attachTimeline(ii),await S.wait(ii)}}else{if(he!==`
42
+ `&&E.has(he))continue;E.add(he),ae(he);let{gameSpeed:ei,cps:ti}=l.preference.getPreferences(),ii=1e3/((typeof he=="object"&&"cps"in he&&he.cps!==void 0?he.cps:ti)*ei);await pi(ii)}}fe&&(ie.forEach(P=>P()),b.resolve())},0),{getToken:()=>b,interact:()=>{let k=!1;Y.forEach(H=>H(()=>k=!0)),!k&&V()},update:()=>{ot&&ot.abort()},forceSkip:()=>{V(!0)},timeline:A,onComplete:k=>(ie.add(k),{cancel:()=>{ie.delete(k)}})}}let C=n.config.action.sentence;if(!C)return null;let f=s??"bold",h={fontWeight:C.config.bold?f:r,fontSize:C.config.fontSize??i,color:zi(C.config.color??o),fontFamily:C.config.fontFamily??a,fontStyle:C.config.italic?"italic":void 0},w=b=>({fontWeight:b.config.bold||C.config.bold?f:r,fontSize:b.config.fontSize??C.config.fontSize??i,color:zi(b.config.color??C.config.color??o),fontFamily:b.config.fontFamily??C.config.fontFamily??a,fontStyle:b.config.italic??C.config.italic?"italic":void 0}),T=(b,A)=>b===`
43
+ `?Ge.createElement("br",{key:A}):Ge.createElement(tn.Span,{tag:`say.word.${A}`,key:A,style:{...w(b),...di(l.config.app.debug,{outline:"1px dashed red"})},className:Wi("inline-block break-all",b.config.className)},b.config.ruby?Ge.createElement("ruby",{className:"align-bottom inline-block"},Ge.createElement("rt",{className:"block text-center"},b.config.ruby),b.text):b.text);return Ge.createElement("div",{...c,className:Wi("whitespace-pre-wrap",e),style:{...h,...t}},d.map(T))}function wc({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:p,fontSize:d,fontWeight:g,fontWeightBold:m,fontFamily:y,onCompleted:v,...C}){let f=us(),[,h]=No(0),w=f?.config??ne.DefaultConfig,T=f?.preference.getPreferences()??ne.DefaultPreference,b=s??T.cps,A=a??T.gameSpeed,E=c??w.autoForwardDefaultPause,O=r??w.autoForwardDefaultPause,Y=Ge.useMemo(()=>xc(o,e,t),[o,e,t]),ie=Ge.useMemo(()=>Ac(i,r,O),[i,r,O]),Fe=As(v),[ot,Be]=No(()=>n?[]:Go(Y));bn(()=>{if(f)return f.preference.onPreferenceChange(()=>{h(V=>V+1)}).cancel},[f]),bn(()=>{Fe.current=v},[v]),bn(()=>{let V=!1,me=[],ye=Math.max(.01,A),ce=H=>new Promise(fe=>{let P=setTimeout(fe,Math.max(0,H));me.push(P)}),ze=()=>{V||Fe.current?.()};return n?Y.length===0?(Be([]),()=>{V=!0}):((async()=>{do{let H=Ho(Y);for(Be([]);!V;){let{done:fe,value:P}=H.next();if(fe)break;if(Me.isPause(P)){let he=Me.from(P);await ce((he.config.duration??E)/ye)}else{if(Ye.isTextEvent(P))continue;ws(Be,P),P===`
44
+ `?await ce(xs(b,A)):await ce(xs(P.cps??b,A))}}if(V)return;ze(),ie.enabled&&await ce(ie.delay)}while(!V&&ie.enabled)})(),()=>{V=!0,me.forEach(H=>clearTimeout(H))}):(Be(Go(Y)),ze(),()=>{V=!0})},[Y,n,ie,b,A,E]);let be=e?.config,K=m??"bold",se={fontWeight:be?.bold?K:g,fontSize:be?.fontSize??d,color:zi(be?.color??l),fontFamily:be?.fontFamily??y,fontStyle:be?.italic?"italic":void 0},ee=V=>({fontWeight:V.config.bold||be?.bold?K:g,fontSize:V.config.fontSize??be?.fontSize??d,color:zi(V.config.color??be?.color??l),fontFamily:V.config.fontFamily??be?.fontFamily??y,fontStyle:V.config.italic??be?.italic?"italic":void 0}),ae=(V,me)=>V===`
45
+ `?Ge.createElement("br",{key:me}):Ge.createElement("span",{key:me,style:ee(V),className:Wi("inline-block break-all",V.config.className)},V.config.ruby?Ge.createElement("ruby",{className:"align-bottom inline-block"},Ge.createElement("rt",{className:"block text-center"},V.config.ruby),V.text):V.text);return Ge.createElement("div",{...C,className:Wi("whitespace-pre-wrap",u),style:{...se,...p}},ot.map(ae))}function ks(o){return Ge.createElement(Vo,{...o,key:o.dialog?.config.action.id})}function kc({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=Oi({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Ge.createElement(Vo,{...r,dialog:s,key:s.config.action.id})}function Ec(o){let e=mt();return Ge.createElement(Vo,{...o,dialog:e,key:e.config.action.id})}function jt(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Ge.createElement(kc,{...o}):Ge.createElement(Ec,{...o})}var Pc=jt;import Bi,{useEffect as Dc,useLayoutEffect as Lc,useMemo as Ps,useRef as Ic,useState as Rc}from"react";import $i from"react";var Fo=$i.createContext(null);function Uo(){let o=$i.useContext(Fo);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Oo=$i.createContext(null);function Es(){let o=$i.useContext(Oo);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function ji({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let c=Ic(null),{register:l,unregister:u,getIndex:p}=Es(),[d,g]=Rc(-1),{choose:m,evaluated:y,gameState:v}=Uo(),C=d===-1?null:y[d],f=Ps(()=>Ae.getCtx({gameState:v}),[v]),{hidden:h,disabled:w}=Ps(()=>{if(!C)return{hidden:!1,disabled:!1};let A=C.config.hidden?.evaluate(f)?.value??!1,E=!A&&(C.config.disabled?.evaluate(f)?.value??!1);return{hidden:A,disabled:E}},[C,f]);Lc(()=>{if(!c.current)return;let A=c;l(A);let E=p(A);return g(E),c.current.dataset.index=E.toString(),()=>u(A)},[l,u,p]),Dc(()=>{if(!t)return;let A=E=>{E.key.toLowerCase()===t.toLowerCase()&&!E.ctrlKey&&!E.metaKey&&(E.preventDefault(),E.stopPropagation(),T())};return window.addEventListener("keydown",A,!0),()=>{window.removeEventListener("keydown",A,!0)}},[t]);function T(){if(d===-1||!y[d]||h||w)return;let A=y[d];m({...A,evaluated:Q.getText(A.words||[])})}let b=C&&!h;return Bi.createElement(Bi.Fragment,null,Bi.createElement("button",{className:o,style:{...e,display:b?e?.display??void 0:"none"},onClick:T,ref:c,disabled:w},b&&Bi.createElement(ks,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new ke({useTypeEffect:!1,action:{sentence:C.prompt,words:C.words,character:null},gameState:v,evaluatedWords:C.words})})))}import qi from"react";import{AnimatePresence as Mc}from"motion/react";function Qi({children:o,...e}){let t=Mc;return qi.createElement(qi.Fragment,null,qi.createElement("div",{...e},qi.createElement(t,null,o)))}import Ds from"react";function Nt({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=Ds.useContext(nn),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return Ds.createElement("div",{...s,style:{color:l?ln(l):void 0,...r}},u)}import Nc from"clsx";import Gc from"react";function Ls(){let o=mt(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return Fc(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?M.getSrcURL(s):null,c=s&&M.isTagSrc(s)?[...s.state.currentSrc]:null,l=os({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=Vc(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Hc({className:o,style:e,alt:t,...n}){let i=Ls();return!i.visible||!i.src?null:Gc.createElement("img",{...n,"data-element-type":"dialog-avatar",className:Nc("dialog-avatar",o),src:i.src,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function Vc(o){return o?D.srcToURL(o):null}function Fc(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var Ko=Hc;import{useEffect as Uc}from"react";function Oc(){let o=mt(),[e]=de(o.deps),t=Q.getText(o.config.evaluatedWords);return Uc(()=>o.events.on(ke.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 Xi,useEffect as Wo,useMemo as Kc,useRef as Wc,useState as Is}from"react";function zc(){let o=mt(),[e]=de(o.deps),[t,n]=Is(!0),[i,r]=Is(!0),s=Wc(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Wo(()=>o.events.on(ke.Events.onFlush,()=>{e()}).cancel,[o]);let u=Kc(()=>{if(!c)return null;try{return pt.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Wo(()=>{s.current=null,r(!0)},[c]),Wo(()=>{let y=!1,v=null,C=null,f=null;if(!u){n(!0);return}n(!1);let h=()=>{y||n(!0)};v=a.audioManager.getToken(u),v&&(v.isPlaying()||n(!0),C=()=>h(),f=()=>h(),v.once("ended",C),v.once("stop",f));let w=a.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{h()});return()=>{y=!0,w.cancel(),v&&C&&v.off("ended",C),v&&f&&v.off("stop",f)}},[a,u]);let p=Xi(async y=>{let v=y??u;if(!v)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let C=v instanceof URL?Se.voice(v.toString()):typeof v=="string"?Se.voice(v):v,f=await a.getLiveGame().playSound(C);s.current=f;let h=()=>{r(!0)};return f.once("ended",h),f.once("stop",h),f},[a,u]),d=Xi(()=>u,[u]),g=Xi(()=>l,[l]),m=Xi(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:p,getVoice:d,getVoiceId:g,getVoiceSrc:m}}import zo,{createContext as tl,useContext as nl,useEffect as Ns,useRef as il}from"react";import{useState as $c}from"react";function Ji(o){let[e]=$c(o);return e}import{AnimatePresence as Bc}from"motion/react";var Yi=Bc;import Bn,{createContext as Jc,useContext as Yc,useEffect as Zc,useRef as _c}from"react";import{useEffect as Wn,useLayoutEffect as jc}from"react";function qc(){let o=xt(),[e]=de();return Wn(()=>o.onChange(e).cancel,[]),o.getPathname()}function Qc(){let{router:o,path:e}=$n(),[t]=de();return Wn(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function Xc(){let o=xt(),[e]=de();return Wn(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Zi(o,e){let t=xt();jc(()=>t.onUpdate(()=>o(t)).cancel,e),Wn(()=>{o(t)},[])}function zn(){let o=xt(),[e]=de();return Wn(()=>o.onChange(e).cancel,[]),e}var Rs=Jc(null);function jn({children:o,path:e,consumedBy:t}){let i={router:xt(),path:e,consumedBy:t};return Bn.createElement(Rs,{value:i},o)}function $n(){let o=Yc(Rs);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new I(`Invalid useLayout call: Trying to access layout without a parent.
46
+ This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function el({children:o,name:e,propagate:t}){let n=R(),[i]=de(),{path:r,router:s,consumedBy:a}=$n(),c=s.joinPath(r,e),l=Ji(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),p=_c(!1),d=m=>{p.current=m,i()},g=s.matchPath(u,c);if(zn(),Zi(m=>{let y=m.matchPath(m.getCurrentPath(),c);if(p.current&&!y){if(!o){d(!1);return}m.registerUnmountingPath(l)}y&&m.isPathsUnmounting()&&m.unregisterUnmountingPath(l),y&&!p.current&&!m.isTransitioning()&&d(!0)},[g,o]),Zc(()=>{if(!g)return;let m=s.mount(c);return()=>{m.cancel()}},[c,s,g]),a)throw new I("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return Bn.createElement(jn,{path:c},Bn.createElement(Yi,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),d(!1)}},g&&p.current&&o))}function Ms({children:o}){return zn(),Bn.createElement(jn,{path:Bt.rootPath},Bn.createElement(Gi,{"data-layout-path":Bt.rootPath,key:Bt.rootPath},o))}var $o=tl(null);function ol(){return nl($o)}function rl({children:o,name:e}){let[t]=de(),{path:n,router:i,consumedBy:r}=$n(),s=ol(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=Ji(()=>i.createToken(l+"@page")),p=i.getCurrentPath(),d=!a,g=il(!1),m=f=>{g.current=f,t()},y=d&&i.exactMatch(p,n)||i.exactMatch(p,l);if(r&&r!==c)throw new I("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");zn(),Zi(f=>{let h=d&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(g.current&&!h){if(!o){m(!1);return}f.registerUnmountingPath(u)}h&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(u),h&&!g.current&&!f.isTransitioning()&&m(!0)},[y,o]),Ns(()=>{if(!y)return;let f=d?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{f.cancel()}},[l,y]),Ns(()=>()=>{i.unregisterUnmountingPath(u),m(!1)},[]);let v=zo.createElement(jn,{path:n,consumedBy:c},zo.createElement(Yi,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),m(!1)}},y&&g.current&&o));return(f=>s?zo.createElement($o,{value:{name:null}},f):f)(v)}import Bo,{useCallback as sl,useEffect as jo,useImperativeHandle as al,useMemo as Gs,useRef as qo,useState as cl}from"react";var ll=50,ul={position:"relative",width:"100%",height:"100%",overflow:"hidden"},Hs={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function pl(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function Vs(o,e){return e==null?o:Math.max(o,e)}function dl(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 Fs=Bo.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:p},d){let g=qo(null),[m,y]=cl({...Hs,width:"0px",height:"0px"}),v=qo(u),C=qo(null);jo(()=>{v.current=u},[u]);let f=sl(()=>{let T=g.current;if(!T)return;let b=T.clientWidth,A=T.clientHeight;if(b<=0||A<=0||e<=0)return;let E=dl(b,A,e),O=Vs(E.width,n),Y=Vs(E.height,i),ie=C.current;(!ie||ie.width!==O||ie.height!==Y)&&(C.current={width:O,height:Y},y({...Hs,width:`${O}px`,height:`${Y}px`}));let Fe=t>0?O/t:1;v.current?.({width:O,height:Y,scale:Fe,containerWidth:b,containerHeight:A})},[e,t,n,i]),h=Gs(()=>Fr(f,typeof r=="number"?r:ll),[f,r]);jo(()=>{f()},[f]),jo(()=>{let T=new ResizeObserver(()=>{h()});g.current&&T.observe(g.current);let b=()=>{h()};return window.addEventListener("resize",b),()=>{T.disconnect(),window.removeEventListener("resize",b)}},[h]),al(d,()=>({requestUpdate:f}),[f]);let w=Gs(()=>pl(l),[l]);return Bo.createElement("div",{id:c,ref:g,style:ul,...w},Bo.createElement("div",{className:s,style:{...m,...a}},p))}),Us=Fs;function ml(){return R().getLiveGame()}import Jo from"react";import fl,{createContext as hl,useContext as gl,useEffect as yl,useState as Os}from"react";var vl={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Ks=hl({state:vl,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function wt(){return gl(Ks)}function Qo(){let{dialogs:o}=wt();return o}function Sl(){let{isActive:o}=wt();return o}function Tl(){let{isVisible:o}=wt();return o}function Xo({children:o}){let t=R().getLiveGame().getGameState(),[n,i]=Os(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Os(null);yl(()=>{let c=m=>({...m,dialogs:[...m.dialogs]}),l=t.events.on(L.EventTypes["event:state.nvl.enter"],(m,y)=>{i(c(t.getNvlState())),s(y?.showTransition||null)}),u=t.events.on(L.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),p=t.events.on(L.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),d=t.events.on(L.EventTypes["event:state.nvl.visibilityChange"],(m,y)=>{i(c(t.getNvlState())),s(y||null)}),g=t.events.on(L.EventTypes["event:state.nvl.change"],m=>{i(c(m))});return()=>{l.cancel(),u.cancel(),p.cancel(),d.cancel(),g.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return fl.createElement(Ks.Provider,{value:a},o)}import{AnimatePresence as bl,motion as Cl}from"motion/react";import xl from"clsx";function Yo({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=wt(),{ratio:r}=Te(),s=R(),a=i?.duration?i.duration/1e3:.3;return Jo.createElement(bl,null,n&&Jo.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},Jo.createElement(Cl.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:xl("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 rn from"react";function Zo({renderDialogItem:o,dialogs:e}){return rn.createElement(Yo,{className:"bg-black/80 text-white p-16 inset-8"},rn.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?rn.createElement(Nt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=rn.createElement(jt,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return rn.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}):rn.createElement(rn.Fragment,null,r,s))})))}import it,{useMemo as Al}from"react";import Ws from"clsx";function wl({children:o,className:e,style:t,renderDialogItem:n}){let i=Qo(),{state:r}=wt();return it.createElement("div",{"data-element-type":"nvl-dialog-list",className:Ws("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>it.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},it.createElement(kl,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?it.createElement(Nt,{className:"nvl-character-name font-bold mr-2"}):null,texts:it.createElement(jt,{className:"nvl-dialog-text"})}):o?it.Children.map(o,c=>it.isValidElement(c)?it.cloneElement(c,{entry:s,index:a}):c):it.createElement(zs,{entry:s,index:a})))))}function zs({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??it.createElement(jt,{className:"nvl-dialog-text"});return it.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Ws("nvl-dialog-item",t),style:n},r&&it.createElement(Nt,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function kl({entry:o,children:e}){let n=R().getLiveGame().getGameState(),i=Al(()=>o.sentence.evaluate(Ae.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=Oi({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return it.createElement(nn,{value:c},e)}function Bs({state:o}){let e=R(),t=xt(),n=_o(null),i=_o(null),r=_o(!1),[s]=dt(ne.Preferences.skipDelay),[a]=dt(ne.Preferences.skipInterval),[c]=on("skipAction");return Pl(()=>{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},p=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(ne.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let m=()=>{n.current=setInterval(()=>{o.events.emit(L.EventTypes["event:state.player.skip"],!1)},a)};u(),o.events.emit(L.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?m():i.current=setTimeout(m,s)}},d=g=>{e.keyMap.match("skipAction",g.key)&&u()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",p).cancel,m=e.getLiveGame().onWindowEvent("keyup",d).cancel;return()=>{u(),g(),m()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",p).cancel,m=e.getLiveGame().onPlayerEvent("keyup",d).cancel;return()=>{u(),g(),m()}}},[t,s,a,c]),$s.createElement($s.Fragment,null)}import js,{useEffect as Dl}from"react";function Ll(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var qs=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],Il=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]'];function Rl(o,e){return!o||e&&qs.some(t=>!!o.closest(t))?!1:[...Il,...qs].some(t=>!!o.closest(t))}function Qs(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 Xs({state:o}){let e=R();return Dl(()=>{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)||!Qs(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!Qs(i,s))||Ll(r)||Rl(r,o.isNvlMode())||(o.events.emit(L.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]),js.createElement(js.Fragment,null)}import{useEffect as qn}from"react";function er({gameState:o}){let e=o.audioManager,[t]=dt("voiceVolume"),[n]=dt("bgmVolume"),[i]=dt("soundVolume"),[r,s]=dt("globalVolume");return qn(()=>{s(e.getGlobalVolume())},[]),qn(()=>{e.setGroupVolume("voice",t)},[t]),qn(()=>{e.setGroupVolume("bgm",n)},[n]),qn(()=>{e.setGroupVolume("sound",i)},[i]),qn(()=>{e.setGlobalVolume(r)},[r]),null}import{useEffect as eo,useRef as Gl}from"react";import tr,{createContext as Ml,useContext as Nl,useState as Js}from"react";var sn=class sn{constructor(){this.preloaded=[];this.events=new te}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(sn.EventTypes["event:preloaded.add"],e),this.events.emit(sn.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(sn.EventTypes["event:preloaded.remove"],e),this.events.emit(sn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Oe.getSrc(e)}};sn.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 He=sn;var _i=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return Or(e,{...n,signal:t})}static decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return Promise.resolve();let t=new window.Image;return t.src=e,typeof t.decode!="function"?Promise.resolve():t.decode().catch(()=>{})}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}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let n=t,i={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(p,d)=>{n=p,i={...i,...d}}]);let r=new AbortController,s=r.signal,a=[],l={promise:o.getImage(n,s,i).then(async p=>{this.preloadTasks.delete(t),p&&(this.add(t,p),await o.decodeImage(p))}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),a.forEach(d=>d(p))}),controller:r};this.preloadTasks.set(t,l);let u={abort:()=>{r.abort(),this.preloadTasks.delete(t)},onFinished:p=>(l.promise.then(p),u),onErrored:p=>(a.push(p),u)};return u}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){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var nr=Ml(null);function Ys({children:o}){let e=R(),[t]=Js(()=>new He),[n]=Js(()=>new _i(e));return tr.createElement(tr.Fragment,null,tr.createElement(nr,{value:{preloaded:t,cacheManager:n}},o))}function Cn(){if(!nr)throw new Error("usePreloaded must be used within a PreloadedProvider");return Nl(nr)}function Zs({state:o}){let{preloaded:e,cacheManager:t}=Cn(),n=R(),i=Gl(new Set),[r]=de(),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(He.EventTypes["event:preloaded.unmount"])}return eo(()=>o.events.on(L.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),eo(()=>{if(typeof fetch>"u")return e.events.emit(He.EventTypes["event:preloaded.complete"]),e.events.emit(He.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(He.EventTypes["event:preloaded.complete"]),e.events.emit(He.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 p=performance.now(),d=Oe.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),g=new Pn(n.config.preloadConcurrency,n.config.preloadDelay),m=[],y=o.logger.group(s,!0),v=[];o.logger.debug(s,"preloading:",d,a);for(let C of d.image){let f=Oe.getSrc(C);if(f){if(m.push(f),t.has(f)||t.isPreloading(f)||v.includes(f)){o.logger.debug(s,`Image already loaded (${d.image.indexOf(C)+1}/${d.image.length})`,f),v.push(f);continue}v.push(f),g.addTask(()=>new Promise(h=>{t.preload(o,f).onFinished(()=>{o.logger.debug(s,`Image loaded (${d.image.indexOf(C)+1}/${d.image.length})`,f),h()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${d.image.indexOf(C)+1}/${d.image.length})`,f),h()})}))}}return y.end(),g.start().then(()=>{o.logger.info(s,"Image preload",`loaded ${t.size()} images in ${performance.now()-p}ms`),e.events.emit(He.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(He.EventTypes["event:preloaded.ready"]),t.filter(m)}),n.config.waitForPreload||e.events.emit(He.EventTypes["event:preloaded.ready"]),e.events.emit(He.EventTypes["event:preloaded.mount"]),u},[a,l]),eo(()=>{i.current.clear()},[a]),eo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let p=performance.now(),d=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>Oe.getPreloadableSrc(l,f)).filter(function(f){return f!==null});d.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{i.current.has(f)||i.current.add(f)});let m=Oe.catSrc([...i.current,...d]),y=new Pn(n.config.preloadConcurrency,n.config.preloadDelay),v=[],C=o.logger.group(s);o.logger.debug(s,"preloading:",m);for(let f of m.image){let h=Oe.getSrc(f);if(h){if(v.push(h),t.has(h)||t.isPreloading(h)){o.logger.debug(s,`Image already loaded (${m.image.indexOf(f)+1}/${m.image.length})`,h);continue}y.addTask(()=>new Promise(w=>{t.preload(o,h).onFinished(()=>{o.logger.debug(s,`Image loaded (${m.image.indexOf(f)+1}/${m.image.length})`,h),w()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${m.image.indexOf(f)+1}/${m.image.length})`,h),w()})}))}}C.end(),y.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-p}ms`),t.filter(v)})},[c,l]),null}import ro from"react";import to from"react";import ir,{useEffect as or,useLayoutEffect as rr,useRef as sr,useState as ar}from"react";function qt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,u]=ar(null),[p,d]=ar(null),g=ir.useRef(null),[m]=ar(()=>new si("displayable.refGroup")),y=sr(m.next()),v=sr(Be()),f=R().getLiveGame().getGameState(),h=typeof a=="function"?a(l):a,[w]=de([p,l,v]);or(()=>f.events.depends([f.events.on(L.EventTypes["event:state.player.skip"],ot)]).cancel,[p,l,v]),rr(()=>{if(A(),!l)return;if(v.current.some(([me])=>!me.current))throw new I("Displayable: Trying to access transition groups before they are mounted");let{controller:K,task:se}=l,ee=me=>{v.current.forEach(([ye],ce)=>{let ze=se.resolve[ce],k=typeof ze=="function"?ze:ze.resolver;if(!k)throw new I(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${ce}])`);let H=k(...me),fe=W(h[ce]||h[h.length-1]||{},H);O(ye,c?c(fe):fe)})},ae=K.onUpdate(ee);ee(se.animations.map(me=>me.start));let V=!1;return Promise.all(v.current.map(([me])=>{let ye=me.current;return ye?.waitForLoad?ye.waitForLoad():Promise.resolve()})).then(()=>{V||K.start()}),()=>{V=!0,ae.cancel()}},[l]),or(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),rr(()=>{let K=e.toStyle(f,i);Object.assign(g.current.style,K),f.logger.debug("Displayable","Initial style applied",g.current,K)},[]);let T=sr(()=>{});T.current=()=>{p||l||!g.current||(Object.assign(g.current.style,e.toStyle(f,i)),A())},rr(()=>{T.current()});let{ratio:b}=Te();or(()=>b.onUpdate(()=>{T.current(),requestAnimationFrame(()=>T.current())}),[b]);function A(){let K=typeof a=="function"?a(l):a;if(!v.current||!v.current.length)throw new I("Displayable: Transition group refs are not initialized correctly");v.current.some(([se])=>!se.current)||v.current.forEach(([se],ee)=>{O(se,K[ee]||K[K.length-1]||{})})}function E(K){f.logger.debug("Displayable","Transform applied",e.toStyle(f,i),g.current),w(),r?.(K)}function O(K,se){if(!K.current)throw new I("Displayable: Trying to assign properties to unmounted element");let ee=K.current,ae={},V={};Object.keys(se).forEach(ye=>{let ce=ye;ce==="style"&&se.style?Object.assign(ae,se.style):se[ce]!==void 0&&ce!=="key"&&(V[ce]=se[ce])}),Object.keys(ae).length>0&&Object.assign(ee.style,ae);let me=c?c(V):V;for(let[ye,ce]of Object.entries(me))ee.getAttribute(ye)!==ce&&ee.setAttribute(ye,ce)}function Y(K,se){p&&(p.abort(),d(null));let ee=K.animate(e,{gameState:f,ref:g,overwrites:i}),ae=new Ee(ee);return f.timelines.attachTimeline(ae),ee.onSkipControllerRegister(V=>{V.onAbort(()=>{ae.abort(),d(null)})}),d(ee),ee.then(()=>{d(null),E(K),se()}),ae}function ie(K,se){l&&l.controller.complete();let ee=K.createTask(f),ae=K.requestAnimations(ee.animations),V=new S().registerSkipController(new F(ae.cancel)),me=new Ee(V);V.skipController.onAbort(()=>{ae.cancel()}),ae.onCanceled(()=>{me.abort(),u(null),f.logger.debug("Displayable","Transition cancelled",K)}),ae.onComplete(()=>{be(),u(null),s?.(K),se(),V.resolve()}),f.timelines.attachTimeline(me),u({task:ee,controller:ae,transition:K,resolve:se});let ye;if(v.current=ee.resolve.map(ce=>{let ze=ir.createRef(),k=typeof ce=="function"?void 0:ce.key;if(!k)return[ze,m.next()];if(k==="target")return ye=m.next(),[ze,ye];if(k==="current")return[ze,y.current];throw new I("Displayable: Invalid key type")}),!ye)throw new I("Displayable: No target key found");return y.current=ye,me}function Fe(K){return f.logger.debug("initDisplayable",o),Y(X.immediate(e.get()),K)}function ot(){t&&p&&(p.abort(),d(null),f.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),f.logger.debug("transition skipped"))}function Be(){return[[ir.createRef(),y.current]]}function be(){v.current.forEach(([K])=>{K.current=null}),v.current=Be()}return{transformRef:g,transitionRefs:v.current,transitionTask:l,initDisplayable:Fe,applyTransform:Y,applyTransition:ie,updateStyleSync:A,flush:w,deps:[p,l,v]}}import{useEffect as Hl}from"react";function kt(o,e,t=[]){let i=R().getLiveGame().getGameState();return Hl(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function cr({state:o,text:e}){let{ratio:t}=Te(),[n]=de(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:u}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:p=>({width:"fit-content",transform:X.propToCSSTransform(o,p,{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 kt(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...u]),to.createElement(tn.Div,{"data-element-type":"text"},to.createElement(tn.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([p,d])=>to.createElement("span",{key:d,ref:p,className:e.config.className},to.createElement("span",null,e.state.text)))))}import ht,{forwardRef as Fl,useCallback as ea,useImperativeHandle as Ul,useRef as oo,useState as ta}from"react";import no,{useEffect as lr,useRef as xn,forwardRef as Vl}from"react";var _s=Vl(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=xn(null),{ratio:a}=Te(),[c,l]=no.useState(0),[u,p]=no.useState(0),d=xn(null),g=xn(null),m=R(),y=xn(!1),v=xn(null),C=xn(null);no.useImperativeHandle(r,()=>s.current,[]),lr(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>y.current,configurable:!0},waitForLoad:{value:()=>{let T=()=>{let b=s.current;return!b||typeof b.decode!="function"?Promise.resolve():b.decode().catch(()=>{})};return y.current?T():(v.current||(v.current=new Promise(b=>{C.current=b})),v.current.then(T))},configurable:!0}})},[]),lr(()=>(f(),a.onUpdate(f)),[o]),lr(()=>{let T=new MutationObserver(b=>{b.forEach(A=>{A.type==="attributes"&&A.attributeName==="src"&&s.current&&f()})});return s.current&&T.observe(s.current,{attributes:!0}),()=>{T.disconnect()}},[o]);function f(){if(s.current&&s.current.naturalWidth){let T,b,A;if(s.current.naturalWidth*s.current.naturalHeight===1)T=a.state.width,b=a.state.height,A=`${T} / ${b}`;else{let ie=t?m.config.width/s.current.naturalWidth:1;T=s.current.naturalWidth*a.state.scale*ie,b=s.current.naturalHeight*a.state.scale*ie,A="auto"}let E=d.current,O=!E||E.w!==T||E.h!==b||E.ar!==A,Y=!!o&&g.current!==o;if(!O&&!Y)return;O&&(d.current={w:T,h:b,ar:A},l(T),p(b),s.current.style.aspectRatio=A),o&&(g.current=o,o(T,b))}}function h(){f(),y.current=!0,C.current&&(C.current(),C.current=null,v.current=null),e&&e()}function w(){y.current=!0,C.current&&(C.current(),C.current=null,v.current=null)}return no.createElement("img",{ref:s,onLoad:h,onError:w,width:c,height:u,alt:"",src:n,style:i})});_s.displayName="AspectScaleImage";var io=_s;import na from"clsx";import{motion as Ol}from"motion/react";var Kl={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},ia=Fl(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=oo(null),a=oo([]),c=o.findIndex(l=>l!==null);return Ul(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(()=>{})}),[]),ht.createElement("div",{ref:s},o.map((l,u)=>l===null?null:ht.createElement(io,{key:"layer-"+u,ref:p=>{a.current[u]=p},src:t(l),style:Kl,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});ia.displayName="LayerStack";function Wl(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 zl(o){return M.isStaticSrc(o)?o.state.currentSrc:M.getSrcURL(o)??void 0}var $l={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function Bl({image:o,state:e}){let[t]=ta(()=>new te),[n,i]=ta([]),{cacheManager:r}=Cn(),s=oo([]),a=oo(null),c=M.isLayeredSrc(o)?M.getSrcURLs(o):null;function l(T){return!D.isDataURI(T)&&!r.has(T)&&!r.isPreloading(T)&&!s.current.includes(T)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${T}".
45
47
  This may be caused by complicated image action behavior that cannot be predicted.
46
- To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(C)),r.get(C)||C}let{transformRef:u,transitionRefs:p,transitionTask:d,initDisplayable:g,applyTransition:h,applyTransform:v,updateStyleSync:f,flush:T,deps:m}=gn({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:C=>{if(c)return(C?C.task.resolve:[null]).map(N=>N&&typeof N=="function"?{style:Rl}:{style:Ll(o.state.darkness)});let b=C?C.transition._getCurrentSrc():Il(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:w.isColor(b)?w.colorToString(b):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:w.isImageSrc(b)?w.srcToURL(b):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:C=>C.src?{...C,src:l(C.src)}:C});Kt(o,{createWearable:C=>{i(b=>[...b,C])},disposeWearable:C=>{i(b=>b.filter(x=>x.getId()!==C.getId()))},initDisplayable:g,applyTransform:v,applyTransition:h,events:t,updateStyleSync:f,flush:T},[...m]);let S=js((C,b)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${C}px`,height:`${b}px`}))},[t]),I=js(()=>{t.emit("event:image.onLoad")},[t]);return ut.createElement(El.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},ut.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?p.map(([C,b],x)=>{let N=d?d.task.resolve[x]:null;if(N&&typeof N=="function")return ut.createElement(qi,{key:b,ref:C,autoFit:o.config.autoFit});let H=N?N.key==="target"?d.transition._getTargetLayers():d.transition._getPrevLayers():c;return ut.createElement(Xs,{key:b,ref:C,src:H||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:x===0?S:void 0,onLoad:x===0?I:void 0})}):p.map(([C,b],x)=>ut.createElement(qi,{key:b,ref:C,autoFit:o.config.autoFit,onSizeChanged:x===0?S:void 0,onLoad:x===0?I:void 0})),ut.createElement("div",{className:Qs("w-full h-full top-0 left-0 absolute")},n.map(C=>ut.createElement("div",{className:Qs("w-full h-full relative"),key:"wearable-"+C.getId()},ut.createElement(Ys,{image:C,state:e}))))))}var Ys=ut.memo(Ml),Js=Ys;function nr({state:o,displayable:e}){return Xi.createElement(Xi.Fragment,null,e.map(t=>{if(t instanceof $t)return Xi.createElement(er,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof R)return Xi.createElement(Js,{state:o,image:t,key:"image-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Yi,{useEffect as Nl}from"react";import{motion as Gl}from"motion/react";function Zs({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=gn({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return Kt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Nl(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Yi.createElement(Yi.Fragment,null,Yi.createElement(Gl.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,p])=>Yi.createElement("div",{className:"relative w-full h-full",ref:u,key:p},t))))}import Hl from"clsx";import{AnimatePresence as Fl}from"motion/react";import{useEffect as ir,useReducer as Ul,useRef as Wn}from"react";import _t from"react";var Ol=120;function or({state:o,className:e,elements:t}){let{scene:n,layers:i,texts:r,menus:s}=t,a=Wn(!1),c=Wn({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),l=Wn([]),u=Wn(null),p=Wn(null),[,d]=Ul(f=>f+1,0),g=()=>{p.current&&(clearTimeout(p.current),p.current=null)},h=()=>{let f=u.current;if(!f)return;let T=c.current;f.forEach(({slot:m,presenceKey:S})=>{T.slotKeys.get(m)===S&&T.slotKeys.delete(m),T.exitingKeys.add(S)}),u.current=null,p.current=null,l.current=[],d()};ir(()=>n.events.depends([n.events.on(et.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),ir(()=>(n.events.emit(et.EventTypes["event:scene.mount"]),o.events.emit(P.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(et.EventTypes["event:scene.unmount"]),o.events.emit(P.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),ir(()=>()=>{g()},[]),Kt(n,{setBackgroundMusic(f,T){return new Promise(m=>{(async function(){n.state.backgroundMusic&&o.audioManager.isManaged(n.state.backgroundMusic)&&await o.audioManager.stop(n.state.backgroundMusic,T),f?(await o.audioManager.play(f,{end:f.state.volume,duration:T}),n.state.backgroundMusic=f):n.state.backgroundMusic=null,m()})()})}});let v=(()=>{let f=c.current,T=r.length>0?r.map(({action:I,onClick:C},b)=>({action:I,slot:b,useTypeEffect:!a.current,onFinished:x=>{x!==void 0&&(a.current=x),C(),o.events.emit(P.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):s.flatMap((I,C)=>{if(!I.action.prompt||!I.action.words)return[];let b=f.menuPromptIds.get(I);return b||(b=`menu-prompt-${n.getId()}-${f.nextKey++}`,f.menuPromptIds.set(I,b)),[{action:{sentence:I.action.prompt,words:I.action.words,character:null,id:b},slot:C,useTypeEffect:!1}]});if(T.length===0)return!u.current&&l.current.length>0&&(u.current=l.current.map(I=>({...I,active:!1}))),u.current&&!p.current&&(p.current=setTimeout(h,Ol)),u.current??[];g(),u.current=null;let m=new Set(T.map(({slot:I})=>I));for(let[I,C]of Array.from(f.slotKeys))m.has(I)||(f.exitingKeys.add(C),f.slotKeys.delete(I));let S=T.map(({slot:I,...C})=>{let b=f.slotKeys.get(I);return(!b||f.exitingKeys.has(b))&&(b=`say-${n.getId()}-${f.nextKey++}`,f.slotKeys.set(I,b)),{...C,presenceKey:b,slot:I,active:!0}});return l.current=S,S})();return _t.createElement("div",{className:Hl(e,"w-full h-full absolute")},[...i.entries()].sort(([f],[T])=>f.state.zIndex-T.state.zIndex).map(([f,T])=>_t.createElement(Zs,{state:o,layer:f,key:f.getId()},_t.createElement(nr,{state:o,displayable:T}))),_t.createElement(Fl,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{c.current.exitingKeys.clear()}},v.map(({action:f,onFinished:T,presenceKey:m,active:S,useTypeEffect:I})=>_t.createElement(Gn,{gameState:o,key:m,action:f,active:S,onFinished:T,useTypeEffect:I}))),s.map(({action:f,onClick:T},m)=>_t.createElement("div",{key:"menu-"+m,"data-element-type":"menu"},_t.createElement(Qo,{state:o,prompt:f.prompt,choices:f.choices,renderPrompt:!f.prompt,afterChoose:S=>{a.current=!1,T(S),o.stage.next()},words:f.words}))))}import Kl from"react";import{useEffect as rr,useRef as Vl}from"react";import{useCallback as _s}from"react";function ea(o){let e=_s(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=_s(()=>{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 sr({gameState:o,video:e}){let t=Vl(null),{show:n,hide:i}=ea(t);rr(()=>o.events.depends([o.events.on(P.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),rr(()=>{i(),e.state.display&&n()},[]),rr(()=>{if(!t.current)return;let s=t.current,a=!1,c=()=>new E(`Failed to add event listener, ref is not available
47
- at Video.tsx: useEffect`),l=()=>{a||!s||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();i()},play:()=>{if(!t.current)throw c();let p=t.current;return p.currentTime=0,new Promise(d=>{o.schedule(({retry:g})=>{if(p.readyState<3){let T=()=>{p.removeEventListener("loadeddata",T),g()};p.addEventListener("loadeddata",T);return}let h=()=>{f(),d()},v=()=>{f(),d()},f=()=>{p.removeEventListener("ended",h),p.removeEventListener("stopped",v)};p.addEventListener("ended",h),p.addEventListener("stopped",v),u.push(f),p.play().catch(T=>{o.logger.error("Failed to play video: "+T),f(),d()})},10)})},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play()},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:p=>{if(!t.current)throw c();t.current.currentTime=p}}))},u=[];return s.addEventListener("canplay",l),()=>{a=!1,s.removeEventListener("canplay",l),u.forEach(p=>p()),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 Kl.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 Wl from"clsx";import zl,{useCallback as Bl,useEffect as Ji,useRef as $l}from"react";function ar({children:o,className:e,gameState:t}){let{ratio:n}=ge(),i=L(),[r]=re(),s=$l(null),a=i.config.minWidth,c=i.config.minHeight,l=Bl(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 Ji(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Ji(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Ji(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Ji(()=>t.events.on(P.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),zl.createElement(Ls,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:Wl(e),onUpdate:l},o)}import ta,{useEffect as jl,useRef as ql,useState as na}from"react";function cr({src:o,width:e,height:t}){let[n,i]=na({x:0,y:0}),[r,s]=na(!1),a=ql(null),{ratio:c}=ge();return jl(()=>{let l=u=>{if(a.current){let p=a.current.getBoundingClientRect(),d=u.clientX-p.left,g=u.clientY-p.top;i({x:d,y:g}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),ta.createElement(St,{ref:a,className:"overflow-hidden absolute"},ta.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 ia from"react";import Rt from"react";function lr({error:o,errorInfo:e}){return L().config.app.debug?Rt.createElement("div",{className:"text-left"},Rt.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),Rt.createElement("p",{className:"text-red-700"},"Message: ",o.message),Rt.createElement("pre",null,"Error Stack: ",o?.stack),Rt.createElement("pre",null,"Component Stack: ",e?.componentStack),Rt.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):Rt.createElement("div",{className:"bg-white w-full h-full"},Rt.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),Rt.createElement("p",null,"Please contact the game developer for further assistance."))}var Zi=class extends ia.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?ia.createElement(lr,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import sa from"clsx";import z,{useEffect as Ct,useReducer as aa,useState as vn}from"react";import{flushSync as ca}from"react-dom";import{useRef as Ql}from"react";import{useEffect as Xl}from"react";function oa({gameState:o}){let e=Ql(null);return Xl(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(P.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import zn,{useEffect as Yl}from"react";function ur({gameState:o}){let[e]=re(),{ratio:t}=ge(),n=o.notificationMgr;Yl(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return zn.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"},zn.createElement(i,{notifications:n.toArray()}))}function ra({notifications:o}){return zn.createElement(Ui,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>zn.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},zn.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function la({story:o=Ln.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:p=!0}){let[d,g]=aa(D=>D+1,0),[h,v]=aa(D=>D+1,0),[f,T]=vn(0),m=L(),[S]=vn(()=>new P(m,{update:g,forceUpdate:()=>{S.logger.weakWarn("Player","force update"),ca(()=>{g()})},forceRemount:()=>{S.logger.weakWarn("Player","force remount"),ca(()=>{T(D=>D+1),g()})},next:ue})),I=z.createRef(),C=z.createRef(),[b,x]=vn(!1),N=z.useRef(!1),H=z.useRef(null),te=z.useRef(null),{preloaded:Te}=hn(),[Pe,xt]=vn(!1),ze=z.useRef(!1),[ye,F]=vn(!1),se=z.useRef(!1),X=z.useRef(null),ne=z.useRef(!1),[G]=vn(new Map);function ae(D){return{game:m,gameState:S,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable(),scene:D}}function ue(){let D=()=>{G.forEach(k=>k.cancel())};if(S.rollLock.isLocked())return;D();let O=!1,Q=0;for(;!O;){if(Q++>m.config.maxStackModelLoop)throw new E("Max stack model loop reached");let k=m.getLiveGame().next();if(!k){if(m.getLiveGame().stackModel&&!m.getLiveGame().stackModel.isEmpty())continue;break}if(y.isAwaitable(k)){if(H.current===k)break;H.current=k,k.onSettled(()=>{k.isFailed()||(H.current===k&&(H.current=null),ue())}),k.onFailed(Be=>{H.current===k&&(H.current=null),S.logger.error("Player",Be)}),O=!0;break}if(k instanceof nn){if(te.current===k)break;te.current=k,k.nextUnlock().then(()=>{te.current===k&&(te.current=null),ue()}),O=!0;break}if(Oe.isCalledActionResult(k)&&k.wait&&Oe.isStackModelsAwaiting(k.wait.type,k.wait.stackModels)){if(H.current===k)break;if(H.current=k,k.wait){let Be=Oe.executeStackModelGroup(k.wait.type,k.wait.stackModels);Be.then(()=>{H.current===k&&(H.current=null),ue()}),Be.onFailed(wt=>{H.current===k&&(H.current=null),S.logger.error("Player",wt)})}O=!0;break}S.handle(k)}S.stage.update()}Ct(()=>{S.audioManager.initialize()},[]),Ct(()=>(m.getLiveGame().setGameState(S),o&&!m.getLiveGame().isPlaying()&&m.getLiveGame().loadStory(o),S.playerCurrent=I.current,S.mainContentNode=C.current,()=>{m.getLiveGame().setGameState(void 0),S.playerCurrent=null}),[m,o]),Ct(()=>je(()=>{x(!0);let D=S.getLastScene(),O=[];D?O.push(D.events.once("event:scene.mount",()=>{S.stage.next()}).cancel):S.stage.next();let Q=S.events.on(P.EventTypes["event:state.end"],()=>{c&&c({game:m,gameState:S,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()})});return S.stage.update(),()=>{D&&O.forEach(k=>k()),Q.cancel()}}),[]),Ct(()=>je(()=>{b&&i&&!N.current&&(N.current=!0,S.stage.forceUpdate(),m.hooks.trigger("init",[]),i({game:m,gameState:S,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()}))}),[b]),Ct(()=>je(()=>{if(Pe&&s&&!ze.current){ze.current=!0;let D=X.current||S.getLastScene()||S.getPreloadingScene(),O=ae(D);s(O)}}),[Pe]),Ct(()=>je(()=>{if(ye&&!se.current){se.current=!0;let D=X.current||S.getLastScene()||S.getPreloadingScene(),O=ae(D);m.markPreloadComplete(O)&&r&&r(O)}}),[ye]),Ct(()=>S.events.on(P.EventTypes["event:state.scene.mount"],D=>{X.current||(X.current=D,v())}).cancel,[]),Ct(()=>{if(!ye||!p||ne.current||m.isFirstSceneReady())return;let D=X.current||S.getLastScene();if(!D)return;let O=null,Q=null,k=!1;ne.current=!0;let Be=()=>{k=!0,ne.current=!1;let wt=ae(D);m.markFirstSceneReady(wt)&&a&&a(wt)};return typeof requestAnimationFrame=="function"?O=requestAnimationFrame(()=>{Q=setTimeout(Be,0)}):Q=setTimeout(Be,0),()=>{k||(ne.current=!1,O!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(O),Q!==null&&clearTimeout(Q))}},[p,h,d,ye]),Ct(()=>Te.events.depends([Te.events.on(Ge.EventTypes["event:preloaded.ready"],()=>{xt(!0),S.stage.update(),o&&m.getLiveGame().isPlaying()&&ue()}),Te.events.on(Ge.EventTypes["event:preloaded.complete"],()=>{F(!0)})]).cancel,[]),Ct(()=>{S.flushDep=d},[d]);let ie=e||m.config.width,W=t||m.config.height;return z.createElement(Zi,{onError:l},z.createElement("div",{style:{width:typeof ie=="number"?`${ie}px`:ie,height:typeof W=="number"?`${W}px`:W},className:sa(n,"__narraleaf_content-player"),ref:I,tabIndex:0},z.createElement(ar,{className:sa("flex-grow overflow-auto"),gameState:S},z.createElement(Bo,{gameState:S}),z.createElement(oa,{gameState:S}),z.createElement(St,{className:"absolute",ref:C,style:{cursor:S.game.config.cursor?"none":"auto",overflow:S.game.config.showOverflow?"visible":"hidden"}},m.config.cursor&&z.createElement(cr,{src:m.config.cursor,width:m.config.cursorWidth,height:m.config.cursorHeight}),z.createElement(Jl,{show:Pe&&p,key:f},z.createElement(Oo,null,z.createElement(Hs,{state:S}),z.createElement(Ks,{state:S}),S.getSceneElements().map(D=>z.createElement(or,{key:"scene-"+D.scene.getId(),state:S,elements:D})),S.getVideos().map((D,O)=>z.createElement("div",{className:"w-full h-full absolute",key:"video-"+O,"data-element-type":"video"},z.createElement(sr,{gameState:S,video:D}))),z.createElement(Zl,{NvlComponent:m.config.nvlDialog}))),z.createElement(zs,{state:S}),z.createElement(xs,null,u),z.createElement(ur,{gameState:S})))))}function Jl({children:o,show:e}){return z.createElement(z.Fragment,null,e?o:null)}function Zl({NvlComponent:o}){let{dialogs:e,state:t}=Tt(),i=L().getLiveGame().getGameState(),r=z.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Se.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 z.createElement(o,{dialogs:r})}import"client-only";import Sn from"react";function ua({children:o,game:e}){return Sn.createElement(Sn.Fragment,null,Sn.createElement(rs,null,Sn.createElement(es,{game:e},Sn.createElement(Ws,null,Sn.createElement(os,null,o)))))}var _l=(r=>(r.image="narraleaf:image",r.text="narraleaf:text",r.layer="narraleaf:layer",r.scene="narraleaf:scene",r.video="narraleaf:video",r))(_l||{});import eu from"clsx";import At,{useEffect as pa,useRef as tu}from"react";import{motion as nu,useIsPresent as iu}from"motion/react";var ou={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function ru({children:o,initial:e,transition:t,...n}){let i=L(),r=ct(),{ratio:s}=ge(),[a]=at(_.Preferences.showDialog),c=tu(null),[l]=Yt("nextAction"),u=iu();function p(){r.requestComplete()}return pa(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
48
- at Say.tsx: onElementClick`);return}let d=h=>{h.repeat||i.keyMap.match("nextAction",h.key)&&r.requestComplete()};window.addEventListener("keydown",d);let g=r.events.on(Ae.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",d),g.cancel()}},[r,l]),pa(()=>{let d=i.preference.onPreferenceChange(_.Preferences.autoForward,g=>{g&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{d.cancel()}},[r]),At.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},At.createElement("div",{className:eu("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:p,style:{...oi(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},At.createElement(nu.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)))}function da({children:o,...e}){let t=ct();return!t.config.action.sentence||!t.config.action.words?null:At.createElement(ru,{...e},o)}var dl=da;function ma(){return At.createElement(da,null,At.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},At.createElement(Io,null),At.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},At.createElement(It,null),At.createElement(Ot,{...ou}))))}var Bn={say:ma,menu:Bs,notification:ra,nvlDialog:Wo};var _i=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 $n=class{constructor(e={}){this.keyMap=e;this.events=new Y}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 fa=(e=>(e.game="game",e))(fa||{}),Ke=class Ke{constructor(e){this.hooks=new ei;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new Mn(Ke.DefaultPreference);this.keyMap=new $n({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new Y;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=K(Ke.DefaultConfig,e),this.plugins=new _i(this),this.router=new Ut(this)}configure(e){let[t,n]=Hr(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=K(this.config,t),this.getLiveGame().getGameState()?.events.emit(P.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}onPreloadComplete(e){return this.lifecycleEvents.on(Ke.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Ke.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(Ke.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Ke.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(Ke.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Ke.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new gt(this)}};Ke.defaultSettings={volume:1},Ke.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},Ke.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"},Ke.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:Bn.notification,menu:Bn.menu,dialog:Bn.say,nvlDialog:Bn.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100},Ke.GameSettingsNamespace=fa,Ke.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var _=Ke;var eo=class eo extends j{static executeActionsAsync(e,t){let n=e.game.getLiveGame().requestAsyncStackModel([{type:t.type,node:t.contentNode}]);return e.game.getLiveGame().executeAsyncStackModel(n)}checkActionChain(e){if(e.some(t=>!!t.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return e}executeAction(e,t){let n=this.contentNode,[i]=n.getContent();if(this.type===xe.do)return[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:i[0].contentNode}];if(this.type===xe.doAsync){let r=eo.executeActionsAsync(e,i[0]);return e.timelines.attachTimeline(r),super.executeAction(e,t)}else if(this.type===xe.any){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().createStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:r}}}else if(this.type===xe.all){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().createStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:r}}}else if(this.type===xe.allAsync){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return e.timelines.attachTimeline(y.all(...r.map(s=>e.game.getLiveGame().executeAsyncStackModel(s)))),super.executeAction(e,t)}else if(this.type===xe.repeat){let[r,s]=this.contentNode.getContent();if(s<=0||r.length===0)return super.executeAction(e,t);let a=Oe.createCountLoop(e.game.getLiveGame(),s,this.checkActionChain(r));return e.logger.debug("ControlAction","repeat",r,s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===xe.while){let[r,s]=this.contentNode.getContent();if(r.length===0)return super.executeAction(e,t);if(!s.evaluate({gameState:e}).value)return super.executeAction(e,t);let a=Oe.createConditionLoop(e.game.getLiveGame(),s,this.getId(),this.checkActionChain(r));return e.logger.debug("ControlAction","while",r),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===xe.break){if(!t.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return t.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===xe.sleep){let[,r]=this.contentNode.getContent();if(e.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let s;typeof r=="number"?s=y.delay(r):y.isAwaitable(r)?s=r:s=y.fromPromise(r);let a=new y,c=new ke(s);return e.timelines.attachTimeline(c),s.then(()=>{a.resolve({type:this.type,node:this.contentNode.getChild()})}),a.onSkipControllerRegister(l=>{l.onAbort(()=>{c.abort()})}),a}else if(this.type===xe.waitForClick){if(e.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let r=new y,s=new y,a=new ke(s);e.timelines.attachTimeline(a);let c=e.game.preference,l=c.getPreference(_.Preferences.autoForward),u=c.getPreference(_.Preferences.gameSpeed),p=l?e.game.config.autoForwardDelay/u:null,d=!1,g=null,h=null,v=null,f=()=>{h?.cancel(),v?.cancel(),g&&(clearTimeout(g),g=null)},T=()=>{d||(d=!0,f(),s.resolve())};return h=e.events.on(P.EventTypes["event:state.player.stageClick"],T),v=e.events.on(P.EventTypes["event:state.player.skip"],T),p!==null&&(g=setTimeout(T,p)),s.then(()=>{r.resolve({type:this.type,node:this.contentNode.getChild()})}),r.onSkipControllerRegister(m=>{m.onAbort(()=>{d||(d=!0,f(),a.abort())})}),r}throw new Error("Unknown control action type: "+this.type)}getFutureActions(e,t){if(this.callee.config.allowFutureScene===!1&&t.allowFutureScene===!1)return[...super.getFutureActions(e,t)];if(this.type===xe.break||this.type===xe.waitForClick)return super.getFutureActions(e,t);let n=this.contentNode.getContent()[0],i=super.getFutureActions(e,t);return[...n??[],...i]}stringify(e,t,n){if(this.type===xe.break)return super.stringifyWithContent("Control","break");if(this.type===xe.waitForClick)return super.stringifyWithContent("Control","waitForClick");let i=this.contentNode,[r]=i.getContent();return super.stringifyWithContent("Control",r.map(s=>s.stringify(e,t,n)).join(";"))}};eo.ActionTypes=xe;var he=eo;var Ie=class o extends ce{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()}do(t){return this.push(he.ActionTypes.do,t)}doAsync(t){return this.push(he.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(he.ActionTypes.any,t)}all(t){return this.pushUnchained(he.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(he.ActionTypes.allAsync,t)}repeat(t,n){return this.push(he.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=V.from(t);return this.pushWithLambda(he.ActionTypes.while,n,i)}breakLoop(){let t=new he(this.chain(),he.ActionTypes.break,new A().setContent([]));return this.chain(t)}sleep(t){return this.push(he.ActionTypes.sleep,[],t)}waitForClick(){let t=new he(this.chain(),he.ActionTypes.waitForClick,new A().setContent([]));return this.chain(t)}push(t,n,...i){let r=this.narrativeToActions(n),s=new he(this.chain(),t,new A().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new he(this.chain(),t,new A().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new he(this.chain(),t,new A().setContent([this.construct(r),i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Pt.say(n).getActions():De.toActions([n]))}};var B=class B extends ft{static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return w.isStaticImageData(t)?w.srcToURL(t):w.isColor(t)?t:w.isImageSrc(t)?w.srcToURL(t):B.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&&!w.isImageSrc(e)&&!w.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)&&(w.isImageSrc(t)||w.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:B.isLayeredSrc(e)?null:B.isTagSrc(e)&&e.config.src.resolve?B.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):B.isStaticSrc(e)?w.isStaticImageData(e.state.currentSrc)?w.srcToURL(e.state.currentSrc):w.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=>B.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(B.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new B({src:e})}constructor(e={}){super();let t=B.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 Ie,n=>{if(w.isImageSrc(e)||w.isColor(e)){if(w.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 le(n,le.ActionTypes.setAppearance,new A().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Ie,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 me("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:B.StateSerializer.serialize(this.state),transformState:Ce.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=B.StateSerializer.deserialize(e.state),this.transformState=Ce.deserialize(e.transformState),this}_applyTransition(e,t){return new Le(this.chain(),Ee.applyTransition,new A().setContent([e,t]))}_init(e,t){return new Le(this.chain(),Ee.init,new A().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new le(this.chain(),le.ActionTypes.initWearable,new A().setContent([e]))}_flush(){return new le(this.chain(),le.ActionTypes.flush,new A)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!B.isTagSrc(this))throw new Error(`Tag not defined
49
- 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}_mixedSrcError(){throw new me(`Trying to mix src and tags
48
+ To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(T)),r.get(T)||T}let{transformRef:u,transitionRefs:p,transitionTask:d,initDisplayable:g,applyTransition:m,applyTransform:y,updateStyleSync:v,flush:C,deps:f}=qt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:T=>{if(c)return(T?T.task.resolve:[null]).map(E=>E&&typeof E=="function"?{style:$l}:{style:Wl(o.state.darkness)});let b=T?T.transition._getCurrentSrc():zl(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:D.isColor(b)?D.colorToString(b):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:D.isImageSrc(b)?D.srcToURL(b):M.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:T=>T.src?{...T,src:l(T.src)}:T});kt(o,{createWearable:T=>{i(b=>[...b,T])},disposeWearable:T=>{i(b=>b.filter(A=>A.getId()!==T.getId()))},initDisplayable:g,applyTransform:y,applyTransition:m,events:t,updateStyleSync:v,flush:C},[...f]);let h=ea((T,b)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${T}px`,height:`${b}px`}))},[t]),w=ea(()=>{t.emit("event:image.onLoad")},[t]);return ht.createElement(Ol.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},ht.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?p.map(([T,b],A)=>{let E=d?d.task.resolve[A]:null;if(E&&typeof E=="function")return ht.createElement(io,{key:b,ref:T,autoFit:o.config.autoFit});let O=E?E.key==="target"?d.transition._getTargetLayers():d.transition._getPrevLayers():c;return ht.createElement(ia,{key:b,ref:T,src:O||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:A===0?h:void 0,onLoad:A===0?w:void 0})}):p.map(([T,b],A)=>ht.createElement(io,{key:b,ref:T,autoFit:o.config.autoFit,onSizeChanged:A===0?h:void 0,onLoad:A===0?w:void 0})),ht.createElement("div",{className:na("w-full h-full top-0 left-0 absolute")},n.map(T=>ht.createElement("div",{className:na("w-full h-full relative"),key:"wearable-"+T.getId()},ht.createElement(oa,{image:T,state:e}))))))}var oa=ht.memo(Bl),ra=oa;function ur({state:o,displayable:e}){return ro.createElement(ro.Fragment,null,e.map(t=>{if(t instanceof Yt)return ro.createElement(cr,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof M)return ro.createElement(ra,{state:o,image:t,key:"image-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import so,{useEffect as jl}from"react";import{motion as ql}from"motion/react";function sa({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return kt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),jl(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),so.createElement(so.Fragment,null,so.createElement(ql.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,p])=>so.createElement("div",{className:"relative w-full h-full",ref:u,key:p},t))))}import Ql from"clsx";import{useEffect as aa}from"react";import pr from"react";function dr({state:o,className:e,elements:t}){let{scene:n,layers:i}=t;return aa(()=>n.events.depends([n.events.on(nt.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),aa(()=>(n.events.emit(nt.EventTypes["event:scene.mount"]),o.events.emit(L.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(nt.EventTypes["event:scene.unmount"]),o.events.emit(L.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),kt(n,{setBackgroundMusic(r,s){return new Promise(a=>{(async function(){n.state.backgroundMusic&&o.audioManager.isManaged(n.state.backgroundMusic)&&await o.audioManager.stop(n.state.backgroundMusic,s),r?(await o.audioManager.play(r,{end:r.state.volume,duration:s}),n.state.backgroundMusic=r):n.state.backgroundMusic=null,a()})()})}}),pr.createElement("div",{className:Ql(e,"w-full h-full absolute")},[...i.entries()].sort(([r],[s])=>r.state.zIndex-s.state.zIndex).map(([r,s])=>pr.createElement(sa,{state:o,layer:r,key:r.getId()},pr.createElement(ur,{state:o,displayable:s}))))}import{AnimatePresence as Zl}from"motion/react";import{useEffect as _l,useReducer as eu,useRef as Qn}from"react";import Xl from"clsx";import Et,{useCallback as mr,useMemo as Jl,useRef as Yl}from"react";function fr({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=R(),a=Yl([]),c=mr(m=>(a.current.push(m),a.current.indexOf(m)),[]),l=mr(m=>{let y=a.current.indexOf(m);y!==-1&&a.current.splice(y,1)},[]),u=mr(m=>a.current.indexOf(m),[]),p=s.config.menu,d=Jl(()=>e.map(m=>({...m,words:m.prompt.evaluate(Ae.getCtx({gameState:n}))})),[]);function g(m){t(m)}return Et.createElement(Et.Fragment,null,Et.createElement(Fo,{value:{evaluated:d,choose:g,gameState:n}},Et.createElement(Oo,{value:{register:c,unregister:l,getIndex:u}},Et.createElement(At,{className:"absolute"},r&&o&&Et.createElement(Kn,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),Et.createElement(tn.Div,{color:"green",border:"dashed",className:Xl("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},Et.createElement(p,{items:d.map((m,y)=>y)})))))}function ca({items:o}){return Et.createElement(Hi,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>Et.createElement(ji,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import tu from"clsx";import Xn from"react";var nu=120;function hr({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=Qn(!1),a=Qn({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),c=Qn([]),l=Qn(null),u=Qn(null),[,p]=eu(y=>y+1,0),d=()=>{u.current&&(clearTimeout(u.current),u.current=null)},g=()=>{let y=l.current;if(!y)return;let v=a.current;y.forEach(({slot:C,presenceKey:f})=>{v.slotKeys.get(C)===f&&v.slotKeys.delete(C),v.exitingKeys.add(f)}),l.current=null,u.current=null,c.current=[],p()};_l(()=>()=>{d()},[]);let m=(()=>{let y=a.current,v=i.length>0?i.map(({action:h,onClick:w},T)=>({action:h,slot:T,useTypeEffect:!s.current,onFinished:b=>{b!==void 0&&(s.current=b),w(),o.events.emit(L.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((h,w)=>{if(!h.action.prompt||!h.action.words)return[];let T=y.menuPromptIds.get(h);return T||(T=`menu-prompt-${n.getId()}-${y.nextKey++}`,y.menuPromptIds.set(h,T)),[{action:{sentence:h.action.prompt,words:h.action.words,character:null,id:T},slot:w,useTypeEffect:!1}]});if(v.length===0)return!l.current&&c.current.length>0&&(l.current=c.current.map(h=>({...h,active:!1}))),l.current&&!u.current&&(u.current=setTimeout(g,nu)),l.current??[];d(),l.current=null;let C=new Set(v.map(({slot:h})=>h));for(let[h,w]of Array.from(y.slotKeys))C.has(h)||(y.exitingKeys.add(w),y.slotKeys.delete(h));let f=v.map(({slot:h,...w})=>{let T=y.slotKeys.get(h);return(!T||y.exitingKeys.has(T))&&(T=`say-${n.getId()}-${y.nextKey++}`,y.slotKeys.set(h,T)),{...w,presenceKey:T,slot:h,active:!0}});return c.current=f,f})();return Xn.createElement("div",{className:tu(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs"},Xn.createElement(Zl,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},m.map(({action:y,onFinished:v,presenceKey:C,active:f,useTypeEffect:h})=>Xn.createElement(Kn,{gameState:o,key:C,action:y,active:f,onFinished:v,useTypeEffect:h}))),r.map(({action:y,onClick:v},C)=>Xn.createElement("div",{key:"menu-"+C,"data-element-type":"menu"},Xn.createElement(fr,{state:o,prompt:y.prompt,choices:y.choices,renderPrompt:!y.prompt,afterChoose:f=>{s.current=!1,v(f),o.stage.next()},words:y.words}))))}import la,{useEffect as iu}from"react";import{motion as ou}from"motion/react";function ua({state:o,camera:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return kt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),iu(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),la.createElement(ou.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"camera"},i.map(([u,p])=>la.createElement("div",{className:"relative w-full h-full",ref:u,key:p},t)))}import ru from"react";import{useEffect as gr,useRef as su}from"react";import{useCallback as pa}from"react";function da(o){let e=pa(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=pa(()=>{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 yr({gameState:o,video:e}){let t=su(null),{show:n,hide:i}=da(t);gr(()=>o.events.depends([o.events.on(L.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),gr(()=>{i(),e.state.display&&n()},[]),gr(()=>{if(!t.current)return;let s=t.current,a=!1,c=new Set,l=()=>new I(`Failed to add event listener, ref is not available
49
+ 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 m=t.current;return g||m.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(m.currentTime=0,new Promise(y=>{let v=!1,C=null,f=[],h=()=>{v||(v=!0,c.delete(h),C&&C(),f.forEach(w=>w()),y())};c.add(h),C=o.schedule(({retry:w})=>{if(v)return;if(m.readyState<3){let E=()=>{m.removeEventListener("loadeddata",E),w()};m.addEventListener("loadeddata",E),f.push(()=>m.removeEventListener("loadeddata",E));return}let T=()=>h(),b=()=>h(),A=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),h()};m.addEventListener("ended",T),m.addEventListener("stopped",b),m.addEventListener("error",A),f.push(()=>{m.removeEventListener("ended",T),m.removeEventListener("stopped",b),m.removeEventListener("error",A)}),m.play().catch(E=>{o.logger.error("Failed to play video: "+E),h()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(m=>{o.logger.error("Failed to resume video: "+m)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:m=>{if(!t.current)throw l();t.current.currentTime=m}}))},p=()=>u(!1),d=()=>{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",p),s.addEventListener("error",d),s.readyState>=3?u(!1):s.error&&d(),()=>{s.removeEventListener("canplay",p),s.removeEventListener("error",d),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 ru.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 au,{useEffect as cu,useRef as lu}from"react";var ma={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 uu(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&ma[e]?ma[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function vr({gameState:o,vfx:e}){let t=lu(null);return cu(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,c=new Set,l=new Set,u=[],p=w=>{n.style.transition="",n.style.opacity=String(w)},d=()=>{n.play().catch(w=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+w)})},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(w=>{let T=!1,b=()=>E(),A=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),E()},E=()=>{T||(T=!0,l.delete(E),n.removeEventListener("loadeddata",b),n.removeEventListener("error",A),w())};l.add(E),n.addEventListener("loadeddata",b),n.addEventListener("error",A),(n.readyState>=2||n.error)&&E()}),m=(w,T,b)=>{let A=T?.duration??0,E=++s;return b.instant||A<=0?(p(w),Promise.resolve()):new Promise(O=>{let Y=!1,ie=null,Fe=()=>{Y||(Y=!0,l.delete(Fe),ie!==null&&clearTimeout(ie),s===E&&t.current&&p(w),O())};l.add(Fe),n.style.transition=`opacity ${A}ms ${uu(o,T?.easing)}`,n.offsetWidth,n.style.opacity=String(w),ie=setTimeout(Fe,A)})},y=w=>{r||(r=!0,i=w,o.mountState(e,{show:async T=>{a=!0;let b={instant:!1};c.add(b);try{if(await g(),!t.current)return;e.state.paused||d(),await m(e.config.opacity,T,b)}finally{c.delete(b)}},hide:async T=>{a=!0;let b={instant:!1};c.add(b);try{await m(0,T,b),t.current&&n.pause()}finally{c.delete(b)}},pause:()=>{n.pause()},resume:()=>{d()},setRate:T=>{n.playbackRate=T}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&p(e.config.opacity)},0)))},v=()=>y(!1),C=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(n.error?` (media error code ${n.error.code})`:"")),y(!0)},f=o.events.on(L.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(w=>{w.instant=!0}),[...l].forEach(w=>w()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),h=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&d()};return document.addEventListener("visibilitychange",h),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&&d(),n.addEventListener("canplay",v),n.addEventListener("error",C),n.readyState>=3?y(!1):n.error&&C(),()=>{n.removeEventListener("canplay",v),n.removeEventListener("error",C),document.removeEventListener("visibilitychange",h),f.cancel(),u.forEach(w=>w()),[...l].forEach(w=>w()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),au.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 pu from"clsx";import du,{useCallback as mu,useEffect as ao,useRef as fu}from"react";function Sr({children:o,className:e,gameState:t}){let{ratio:n}=Te(),i=R(),[r]=de(),s=fu(null),a=i.config.minWidth,c=i.config.minHeight,l=mu(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 ao(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),ao(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),ao(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),ao(()=>t.events.on(L.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),du.createElement(Us,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:pu(e),onUpdate:l},o)}import fa,{useEffect as hu,useRef as gu,useState as ha}from"react";function Tr({src:o,width:e,height:t}){let[n,i]=ha({x:0,y:0}),[r,s]=ha(!1),a=gu(null),{ratio:c}=Te();return hu(()=>{let l=u=>{if(a.current){let p=a.current.getBoundingClientRect(),d=u.clientX-p.left,g=u.clientY-p.top;i({x:d,y:g}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),fa.createElement(At,{ref:a,className:"overflow-hidden absolute"},fa.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 ga from"react";import Gt from"react";function br({error:o,errorInfo:e}){return R().config.app.debug?Gt.createElement("div",{className:"text-left"},Gt.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),Gt.createElement("p",{className:"text-red-700"},"Message: ",o.message),Gt.createElement("pre",null,"Error Stack: ",o?.stack),Gt.createElement("pre",null,"Component Stack: ",e?.componentStack),Gt.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):Gt.createElement("div",{className:"bg-white w-full h-full"},Gt.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),Gt.createElement("p",null,"Please contact the game developer for further assistance."))}var co=class extends ga.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?ga.createElement(br,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import Sa from"clsx";import U,{useEffect as Pt,useReducer as Ta,useState as An}from"react";import{flushSync as ba}from"react-dom";import{useRef as yu}from"react";import{useEffect as vu}from"react";function ya({gameState:o}){let e=yu(null);return vu(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(L.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import Jn,{useEffect as Su}from"react";function Cr({gameState:o}){let[e]=de(),{ratio:t}=Te(),n=o.notificationMgr;Su(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return Jn.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"},Jn.createElement(i,{notifications:n.toArray()}))}function va({notifications:o}){return Jn.createElement(Qi,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>Jn.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},Jn.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function Ca({story:o=Hn.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:p=!0}){let[d,g]=Ta(k=>k+1,0),[m,y]=Ta(k=>k+1,0),[v,C]=An(0),f=R(),[h]=An(()=>new L(f,{update:g,forceUpdate:()=>{h.logger.weakWarn("Player","force update"),ba(()=>{g()})},forceRemount:()=>{h.logger.weakWarn("Player","force remount"),ba(()=>{C(k=>k+1),g()})},next:ye})),w=U.createRef(),T=U.createRef(),[b,A]=An(!1),E=U.useRef(!1),O=U.useRef(null),Y=U.useRef(null),{preloaded:ie}=Cn(),[Fe,ot]=An(!1),Be=U.useRef(!1),[be,K]=An(!1),se=U.useRef(!1),ee=U.useRef(null),ae=U.useRef(!1),[V]=An(new Map);function me(k){return{game:f,gameState:h,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable(),scene:k}}function ye(){let k=()=>{V.forEach(P=>P.cancel())};if(h.rollLock.isLocked())return;k();let H=!1,fe=0;for(;!H;){if(fe++>f.config.maxStackModelLoop)throw new I("Max stack model loop reached");let P=f.getLiveGame().next();if(!P){if(f.getLiveGame().stackModel&&!f.getLiveGame().stackModel.isEmpty())continue;break}if(S.isAwaitable(P)){if(O.current===P)break;O.current=P,P.onSettled(()=>{P.isFailed()||(O.current===P&&(O.current=null),ye())}),P.onFailed(he=>{O.current===P&&(O.current=null),h.logger.error("Player",he)}),H=!0;break}if(P instanceof cn){if(Y.current===P)break;Y.current=P,P.nextUnlock().then(()=>{Y.current===P&&(Y.current=null),ye()}),H=!0;break}if(Ke.isCalledActionResult(P)&&P.wait&&Ke.isStackModelsAwaiting(P.wait.type,P.wait.stackModels)){if(O.current===P)break;if(O.current=P,P.wait){let he=Ke.executeStackModelGroup(P.wait.type,P.wait.stackModels);he.then(()=>{O.current===P&&(O.current=null),ye()}),he.onFailed(Lt=>{O.current===P&&(O.current=null),h.logger.error("Player",Lt)})}H=!0;break}h.handle(P)}h.stage.update()}Pt(()=>{h.audioManager.initialize()},[]),Pt(()=>(f.getLiveGame().setGameState(h),o&&!f.getLiveGame().isPlaying()&&f.getLiveGame().loadStory(o),h.playerCurrent=w.current,h.mainContentNode=T.current,()=>{f.getLiveGame().setGameState(void 0),h.playerCurrent=null}),[f,o]),Pt(()=>qe(()=>{A(!0);let k=h.getLastScene(),H=[];k?H.push(k.events.once("event:scene.mount",()=>{h.stage.next()}).cancel):h.stage.next();let fe=h.events.on(L.EventTypes["event:state.end"],()=>{c&&c({game:f,gameState:h,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()})});return h.stage.update(),()=>{k&&H.forEach(P=>P()),fe.cancel()}}),[]),Pt(()=>qe(()=>{b&&i&&!E.current&&(E.current=!0,h.stage.forceUpdate(),f.hooks.trigger("init",[]),i({game:f,gameState:h,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()}))}),[b]),Pt(()=>qe(()=>{if(Fe&&s&&!Be.current){Be.current=!0;let k=ee.current||h.getLastScene()||h.getPreloadingScene(),H=me(k);s(H)}}),[Fe]),Pt(()=>qe(()=>{if(be&&!se.current){se.current=!0;let k=ee.current||h.getLastScene()||h.getPreloadingScene(),H=me(k);f.markPreloadComplete(H)&&r&&r(H)}}),[be]),Pt(()=>h.events.on(L.EventTypes["event:state.scene.mount"],k=>{ee.current||(ee.current=k,y())}).cancel,[]),Pt(()=>{if(!be||!p||ae.current||f.isFirstSceneReady())return;let k=ee.current||h.getLastScene();if(!k)return;let H=null,fe=null,P=!1;ae.current=!0;let he=()=>{P=!0,ae.current=!1;let Lt=me(k);f.markFirstSceneReady(Lt)&&a&&a(Lt)};return typeof requestAnimationFrame=="function"?H=requestAnimationFrame(()=>{fe=setTimeout(he,0)}):fe=setTimeout(he,0),()=>{P||(ae.current=!1,H!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(H),fe!==null&&clearTimeout(fe))}},[p,m,d,be]),Pt(()=>ie.events.depends([ie.events.on(He.EventTypes["event:preloaded.ready"],()=>{ot(!0),h.stage.update(),o&&f.getLiveGame().isPlaying()&&ye()}),ie.events.on(He.EventTypes["event:preloaded.complete"],()=>{K(!0)})]).cancel,[]),Pt(()=>{h.flushDep=d},[d]);let ce=e||f.config.width,ze=t||f.config.height;return U.createElement(co,{onError:l},U.createElement("div",{style:{width:typeof ce=="number"?`${ce}px`:ce,height:typeof ze=="number"?`${ze}px`:ze},className:Sa(n,"__narraleaf_content-player"),ref:w,tabIndex:0},U.createElement(Sr,{className:Sa("flex-grow overflow-auto"),gameState:h},U.createElement(er,{gameState:h}),U.createElement(ya,{gameState:h}),U.createElement(At,{className:"absolute",ref:T,style:{cursor:h.game.config.cursor?"none":"auto",overflow:h.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},f.config.cursor&&U.createElement(Tr,{src:f.config.cursor,width:f.config.cursorWidth,height:f.config.cursorHeight}),U.createElement(Tu,{show:Fe&&p,key:v},U.createElement(Xo,null,U.createElement(Bs,{state:h}),U.createElement(Xs,{state:h}),U.createElement(bu,{state:h},h.getSceneElements().map(k=>U.createElement(dr,{key:"scene-"+k.scene.getId(),state:h,elements:k})),h.getVideos().map((k,H)=>U.createElement("div",{className:"w-full h-full absolute",key:"video-"+H,"data-element-type":"video"},U.createElement(yr,{gameState:h,video:k}))),h.getVfx().map(k=>U.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+k.getId(),"data-element-type":"vfx",style:{zIndex:k.config.zIndex}},U.createElement(vr,{gameState:h,vfx:k})))),h.getSceneElements().map(k=>U.createElement(hr,{key:"scene-dialogs-"+k.scene.getId(),state:h,elements:k})),U.createElement(Cu,{NvlComponent:f.config.nvlDialog}))),U.createElement(Zs,{state:h}),U.createElement(Ms,null,u),U.createElement(Cr,{gameState:h})))))}function Tu({children:o,show:e}){return U.createElement(U.Fragment,null,e?o:null)}function bu({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?U.createElement(ua,{state:o,camera:t},e):U.createElement(U.Fragment,null,e)}function Cu({NvlComponent:o}){let{dialogs:e,state:t}=wt(),i=R().getLiveGame().getGameState(),r=U.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Ae.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 wn from"react";function xa({children:o,game:e}){return wn.createElement(wn.Fragment,null,wn.createElement(fs,null,wn.createElement(ls,{game:e},wn.createElement(Ys,null,wn.createElement(ms,null,o)))))}var xu=(a=>(a.image="narraleaf:image",a.text="narraleaf:text",a.layer="narraleaf:layer",a.scene="narraleaf:scene",a.video="narraleaf:video",a.vfx="narraleaf:vfx",a.camera="narraleaf:camera",a))(xu||{});import Au from"clsx";import Dt,{useEffect as Aa,useRef as wu}from"react";import{motion as ku,useIsPresent as Eu}from"motion/react";var Pu={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Du({children:o,initial:e,transition:t,...n}){let i=R(),r=mt(),{ratio:s}=Te(),[a]=dt(ne.Preferences.showDialog),c=wu(null),[l]=on("nextAction"),u=Eu();function p(){r.requestComplete()}return Aa(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
50
+ at Say.tsx: onElementClick`);return}let d=m=>{m.repeat||i.keyMap.match("nextAction",m.key)&&r.requestComplete()};window.addEventListener("keydown",d);let g=r.events.on(ke.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",d),g.cancel()}},[r,l]),Aa(()=>{let d=i.preference.onPreferenceChange(ne.Preferences.autoForward,g=>{g&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{d.cancel()}},[r]),Dt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},Dt.createElement("div",{className:Au("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:p,style:{...di(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},Dt.createElement(ku.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)))}function wa({children:o,...e}){let t=mt();return!t.config.action.sentence||!t.config.action.words?null:Dt.createElement(Du,{...e},o)}var El=wa;function ka(){return Dt.createElement(wa,null,Dt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},Dt.createElement(Ko,null),Dt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},Dt.createElement(Nt,null),Dt.createElement(jt,{...Pu}))))}var Yn={say:ka,menu:ca,notification:va,nvlDialog:Zo};var lo=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 Zn=class{constructor(e={}){this.keyMap=e;this.events=new te}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 Ea=(e=>(e.game="game",e))(Ea||{}),We=class We{constructor(e){this.hooks=new ci;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new Un(We.DefaultPreference);this.keyMap=new Zn({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new te;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=W(We.DefaultConfig,e),this.plugins=new lo(this),this.router=new Bt(this)}configure(e){let[t,n]=Br(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=W(this.config,t),this.getLiveGame().getGameState()?.events.emit(L.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}onPreloadComplete(e){return this.lifecycleEvents.on(We.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(We.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(We.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(We.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(We.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(We.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new bt(this)}};We.defaultSettings={volume:1},We.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},We.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"},We.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:Yn.notification,menu:Yn.menu,dialog:Yn.say,nvlDialog:Yn.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100},We.GameSettingsNamespace=Ea,We.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var ne=We;var uo=class uo extends B{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===Z.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===Z.doAsync){if(r.length===0)return super.executeAction(t,n);let s=uo.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===Z.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===Z.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===Z.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(S.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===Z.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=Ke.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===Z.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=Ke.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===Z.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===Z.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=S.delay(s):S.isAwaitable(s)?a=s:a=S.fromPromise(s);let c=new S,l=new Ee(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===Z.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,c=new Ee(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(ne.Preferences.autoForward),p=l.getPreference(ne.Preferences.gameSpeed),d=u?t.game.config.autoForwardDelay/p:null,g=!1,m=null,y=null,v=null,C=()=>{y?.cancel(),v?.cancel(),m&&(clearTimeout(m),m=null)},f=()=>{g||(g=!0,C(),a.resolve())};return y=t.events.on(L.EventTypes["event:state.player.stageClick"],f),v=t.events.on(L.EventTypes["event:state.player.skip"],f),d!==null&&(m=setTimeout(f,d)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(h=>{h.onAbort(()=>{g||(g=!0,C(),c.abort())})}),s}else{if(this.type===Z.label)return super.executeAction(t,n);if(this.type===Z.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Pe(`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===Z.break||this.type===Z.waitForClick||this.type===Z.label||this.type===Z.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===Z.break)return super.stringifyWithContent("Control","break");if(this.type===Z.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===Z.label||this.type===Z.jump){let[a]=this.contentNode.getContent(),c=this.type===Z.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(";"))}};uo.ActionTypes=Z;var _=uo;var Re=class o extends oe{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(_.ActionTypes.do,t)}doAsync(t){return this.push(_.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(_.ActionTypes.any,t)}all(t){return this.pushUnchained(_.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(_.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(_.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=z.from(t);return this.pushWithLambda(_.ActionTypes.while,n,i)}breakLoop(){let t=new _(this.chain(),_.ActionTypes.break,new x().setContent([]));return this.chain(t)}sleep(t){return this.push(_.ActionTypes.sleep,[],t)}waitForClick(){let t=new _(this.chain(),_.ActionTypes.waitForClick,new x().setContent([]));return this.chain(t)}label(t){let n=new _(this.chain(),_.ActionTypes.label,new x().setContent([t]));return this.chain(n)}jump(t){let n=new _(this.chain(),_.ActionTypes.jump,new x().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new _(this.chain(),t,new x().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new _(this.chain(),t,new x().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new _(this.chain(),t,new x().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Rt.say(n).getActions():Le.toActions([n]))}};var j=class j extends rt{static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return D.isStaticImageData(t)?D.srcToURL(t):D.isColor(t)?t:D.isImageSrc(t)?D.srcToURL(t):j.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&&!D.isImageSrc(e)&&!D.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)&&(D.isImageSrc(t)||D.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:j.isLayeredSrc(e)?null:j.isTagSrc(e)&&e.config.src.resolve?j.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):j.isStaticSrc(e)?D.isStaticImageData(e.state.currentSrc)?D.srcToURL(e.state.currentSrc):D.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=>j.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(j.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new j({src:e})}constructor(e={}){super();let t=j.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 Re,n=>{if(D.isImageSrc(e)||D.isColor(e)){if(D.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 x().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Re,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 ue("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:j.StateSerializer.serialize(this.state),transformState:le.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=j.StateSerializer.deserialize(e.state),this.transformState=le.deserialize(e.transformState),this}_applyTransition(e,t){return new Ie(this.chain(),De.applyTransition,new x().setContent([e,t]))}_init(e,t){return new Ie(this.chain(),De.init,new x().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new ge(this.chain(),ge.ActionTypes.initWearable,new x().setContent([e]))}_flush(){return new ge(this.chain(),ge.ActionTypes.flush,new x)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!j.isTagSrc(this))throw new Error(`Tag not defined
51
+ 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(D.isImageSrc(e)||D.isColor(e)){if(D.isColor(e)&&!this.config.isBackground)throw new ue("Color src is not allowed for non-background image");this.state.currentSrc=e;return}if(!j.isTagSrc(this))throw this._mixedSrcError();let t=this.state.currentSrc,n=this.resolveTags(t,e);this.state.currentSrc=n}_mixedSrcError(){throw new ue(`Trying to mix src and tags
50
52
  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
51
53
  Wearable must be an Image with isWearable set to true
52
54
  It seems like you are trying to add a non-wearable image to wearables
53
55
  Image below violates the rule:
54
- `+e)}_invalidTagGroupDefinitionError(){throw new Error("Invalid tag group definition. Tags in groups must be unique and not conflicting with each other.")}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(le.resolveCurrentSrc(this))._setTargetSrc(t))),new le(e,le.ActionTypes.setSrc,new A().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){let e=this.config.src;return e?.slots?B.getAllLayerSrc(this).forEach(t=>this.srcManager.registerRawSrc(t)):e?.resolve?this.srcManager.registerRawSrc(B.getSrcFromTags(e.defaults,e.resolve)):w.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(w.srcToURL(this.state.currentSrc)),this}static normalizeSrcDefinition(e){return B.isLayeredDefinition(e)?{groups:e.layers.filter(B.isLayerVariants).map(t=>Object.keys(t)),defaults:[...e.defaults],resolve:null,slots:e.layers}:B.isTagDefinition(e)?{groups:e.groups,defaults:[...e.defaults],resolve:e.resolve,slots:null}:null}createImageConfig(e){let t=e.get();return B.DefaultImageConfig.create({...t,src:B.normalizeSrcDefinition(t.src)})}getInitialState(){return B.DefaultImageState.create().assign({currentSrc:B.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(Ce.DefaultTransformState.keys());return new Ce(Ce.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(B.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();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
56
+ `+e)}_invalidTagGroupDefinitionError(){throw new Error("Invalid tag group definition. Tags in groups must be unique and not conflicting with each other.")}_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 x().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){let e=this.config.src;return e?.slots?j.getAllLayerSrc(this).forEach(t=>this.srcManager.registerRawSrc(t)):e?.resolve?this.srcManager.registerRawSrc(j.getSrcFromTags(e.defaults,e.resolve)):D.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(D.srcToURL(this.state.currentSrc)),this}static normalizeSrcDefinition(e){return j.isLayeredDefinition(e)?{groups:e.layers.filter(j.isLayerVariants).map(t=>Object.keys(t)),defaults:[...e.defaults],resolve:null,slots:e.layers}:j.isTagDefinition(e)?{groups:e.groups,defaults:[...e.defaults],resolve:e.resolve,slots:null}:null}createImageConfig(e){let t=e.get();return j.DefaultImageConfig.create({...t,src:j.normalizeSrcDefinition(t.src)})}getInitialState(){return j.DefaultImageState.create().assign({currentSrc:j.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(le.DefaultTransformState.keys());return new le(le.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(j.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();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
55
57
  Tag "${r}" is conflicting with another tag
56
58
  Error found in config.tag.defaults`);if(!n.has(r))throw new Error(`Tag not found
57
59
  Tag "${r}" is not defined in tagDefinitions
58
- 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 me(`Layer has no default
59
- The layer 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 le(e,le.ActionTypes.setDarkness,new A().setContent([t,n,i]))}};B.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",B.StateSerializer=new $e,B.DefaultUserConfig=new J({name:"(anonymous)",autoInit:!0,src:B.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...Ce.DefaultTransformState.getDefaultConfig()},{position:e=>M.tryParsePosition(e)}),B.DefaultImageConfig=new J({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),B.DefaultImageState=new J({currentSrc:B.DefaultImagePlaceholder,darkness:0});var R=B;var de=class extends ht{_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)=>K(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>K(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(this._isLayered())return{};if(w.isColor(e))return{src:R.DefaultImagePlaceholder,style:{backgroundColor:w.isRGBAColor(e)?w.RGBAColorToHex(e):e}};if(w.isImageSrc(e))return{src:w.srcToURL(e)};throw new me("Image transition src cannot be identified, using: "+e)}};var to=class o extends de{constructor(t,n,i,r){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=i;this.easing=r}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var jn=class jn extends j{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 w.isImageSrc(e.state.currentSrc)?w.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===Je.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new y(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===Je.setSrc){let n=this.contentNode.getContent()[0];if(w.isColor(n)&&!this.callee.config.isBackground)throw new me("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===Je.flush)return super.executeAction(e,t);if(this.type===Je.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 p=new y(v=>v).registerSkipController(new U(()=>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,p.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(p).attachChild(g);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},c,[]),p}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 p=new y(v=>v).registerSkipController(new U(()=>super.executeAction(e,t)));i._setPrevSrc(jn.resolveCurrentSrc(this.callee))._setTargetSrc(u);let g=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(p).attachChild(g);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},c,[]),p}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===Je.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 y(g=>g),u=new to(s,n,i,r);if(R.isLayeredSrc(this.callee)){let g=R.getSrcURLs(this.callee);u._setPrevLayers(g)._setTargetLayers(g)}else{let g=jn.resolveCurrentSrc(this.callee);u._setPrevSrc(g)._setTargetSrc(g)}let p=c.applyTransition(u,()=>{this.callee.state.darkness=n,l.resolve(super.executeAction(e,t))}),d=e.timelines.attachTimeline(l).attachChild(p);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:d},()=>{l.isSettled()||l.abort(),p.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")}};jn.ActionTypes=Je;var le=jn;var Mt=class Mt extends j{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 Mt.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 me("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 y().registerSkipController(new U(()=>(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 y(l=>l),c=null;return a.registerSkipController(new U(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===$.action)return super.executeAction(e,t);if(this.is(Mt,"scene:init")){let n=new y(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 Mt.handleSceneInit(this.callee,r,e,y.forward(n,r))}else if(this.type===$.exit){let n=Mt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new y(s=>s);e.timelines.attachTimeline(r),Mt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Mt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===$.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===$.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===$.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===$.transitionToScene){let[n,i,r]=this.contentNode.getContent();return n._setPrevSrc(le.resolveCurrentSrc(this.callee.background)),i?n._setTargetSrc(le.resolveCurrentSrc(i.background)):r&&n._setTargetSrc(r),this.applyTransition(e,n,t)}else if(this.type===$.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===$.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=y.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===$.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=y.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===$.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===$.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===$.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 me(`Scene with name ${e} not found
60
+ 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 ue(`Layer has no default
61
+ The layer 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 x().setContent([t,n,i]))}};j.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",j.StateSerializer=new je,j.DefaultUserConfig=new $({name:"(anonymous)",autoInit:!0,src:j.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...le.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}),j.DefaultImageConfig=new $({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),j.DefaultImageState=new $({currentSrc:j.DefaultImagePlaceholder,darkness:0});var M=j;var Ve=class extends Tt{_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)=>W(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>W(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(this._isLayered())return{};if(D.isColor(e))return{src:M.DefaultImagePlaceholder,style:{backgroundColor:D.isRGBAColor(e)?D.RGBAColorToHex(e):e}};if(D.isImageSrc(e))return{src:D.srcToURL(e)};throw new ue("Image transition src cannot be identified, using: "+e)}};var po=class o extends Ve{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 _n=class _n extends B{static resolveTagSrc(e,t){if(!M.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return M.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(M.isLayeredSrc(e))throw e._mixedSrcError();if(M.isStaticSrc(e))return D.isImageSrc(e.state.currentSrc)?D.srcToURL(e.state.currentSrc):e.state.currentSrc;if(M.isTagSrc(e)&&e.config.src.resolve)return M.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===_e.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new S(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===_e.setSrc){let n=this.contentNode.getContent()[0];if(D.isColor(n)&&!this.callee.config.isBackground)throw new ue("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===_e.flush)return super.executeAction(e,t);if(this.type===_e.setAppearance){let[n,i]=this.contentNode.getContent();if(!M.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(M.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let p=new S(y=>y).registerSkipController(new F(()=>super.executeAction(e,t)));i._setPrevLayers(M.getSrcURLs(this.callee))._setTargetLayers(M.getSrcURLs(this.callee,s));let g=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),m=e.timelines.attachTimeline(p).attachChild(g);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:m},c,[]),p}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=M.getSrcFromTags(s,l);if(e.logger.debug("Image - Set Appearance",s,u),i){let p=new S(y=>y).registerSkipController(new F(()=>super.executeAction(e,t)));i._setPrevSrc(_n.resolveCurrentSrc(this.callee))._setTargetSrc(u);let g=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),m=e.timelines.attachTimeline(p).attachChild(g);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:m},c,[]),p}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===_e.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 S(g=>g),u=new po({from:s,to:n,duration:i,easing:r});if(M.isLayeredSrc(this.callee)){let g=M.getSrcURLs(this.callee);u._setPrevLayers(g)._setTargetLayers(g)}else{let g=_n.resolveCurrentSrc(this.callee);u._setPrevSrc(g)._setTargetSrc(g)}let p=c.applyTransition(u,()=>{this.callee.state.darkness=n,l.resolve(super.executeAction(e,t))}),d=e.timelines.attachTimeline(l).attachChild(p);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:d},()=>{l.isSettled()||l.abort(),p.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")}};_n.ActionTypes=_e;var ge=_n;var Ht=class Ht extends B{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 Ht.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 ue("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 S().registerSkipController(new F(()=>(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 S(l=>l),c=null;return a.registerSkipController(new F(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===q.action)return super.executeAction(e,t);if(this.is(Ht,"scene:init")){let n=new S(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 Ht.handleSceneInit(this.callee,r,e,S.forward(n,r))}else if(this.type===q.exit){let n=Ht.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new S(s=>s);e.timelines.attachTimeline(r),Ht.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Ht.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===q.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===q.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===q.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===q.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===q.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===q.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=S.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===q.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=S.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===q.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===q.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===q.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 ue(`Scene with name ${e} not found
60
62
  Make sure you have registered the scene using story.register
61
63
  Action: (id: ${this.getId()}) ${this.type}
62
- At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===$.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")}};Mt.ActionTypes=$;var ee=Mt;var pr=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)}},pt=class pt{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)||pt.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return pt.isHexString(e)||pt.isNamedColor(e)||pt.isRGBAColor(e)}static isNamedColor(e){return Mr(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(pt.isHexString(e))return e;if(pt.isNamedColor(e))return e;if(pt.isRGBAColor(e))return pt.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},p=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...p}}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)}};pt.RGBColor=pr;var w=pt,dr=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},we=class o extends dr{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},bi=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 le)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof ee){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
64
+ At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===q.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")}};Ht.ActionTypes=q;var re=Ht;var xr=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)}},gt=class gt{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)||gt.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return gt.isHexString(e)||gt.isNamedColor(e)||gt.isRGBAColor(e)}static isNamedColor(e){return Wr(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(gt.isHexString(e))return e;if(gt.isNamedColor(e))return e;if(gt.isRGBAColor(e))return gt.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},p=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...p}}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)}};gt.RGBColor=xr;var D=gt,Ar=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},xe=class o extends Ar{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},Di=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 re){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
63
65
  Scene: ${s.config.name}
64
66
 
65
- At: ${t.__stack}`;throw new we(a)}}else i.set(s.config.name,s);if(t.type===$.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===Je.setSrc){let i=t.contentNode.getContent()[0];w.isImageURL(i)&&w.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},me=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`
67
+ At: ${t.__stack}`;throw new xe(a)}}else i.set(s.config.name,s);if(t.type===q.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===_e.setSrc){let i=t.contentNode.getContent()[0];D.isImageURL(i)&&D.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},ue=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`
66
68
  Using action (id: ${e.getId()})
67
- at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},E=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Ue=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function su(o,e){return q.color(o,e)}function au(o){return q.bold(o)}function cu(o){return q.italic(o)}var mr=class o extends de{constructor(t,n){super();this.duration=t;this.easing=n}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-t}})),this.asTarget(t=>({style:{opacity:t}}))]}}copy(){return new o(this.duration,this.easing)}};var fr=class o extends de{constructor(t,n=[0,0],i){super();this.duration=t;this.startPos=n;this.easing=i}createTask(t){let{invertX:n,invertY:i}=t.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((r,s,a)=>({style:{opacity:r,translate:`${n?-s:s}px ${i?-a:a}px`}}))]}}copy(){return new o(this.duration,this.startPos,this.easing)}};var hr=class o extends de{constructor(t,n,i){super();this.duration=t;this.easing=n;this.clipPathResolver=i}static circle(t){let{duration:n,easing:i,center:r="50% 50%",from:s=0,to:a=150}=t;return new o(n,i,c=>o.circleClipPath(o.lerp(s,a,c),r))}static wipe(t){let{duration:n,easing:i,direction:r="left",reverse:s=!1}=t,a=s?0:100,c=s?100:0;return new o(n,i,l=>o.wipeClipPath(r,o.lerp(a,c,l)))}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({style:{opacity:1,clipPath:"none"}})),this.asTarget(t=>({style:{opacity:1,clipPath:this.clipPathResolver(t)}}))]}}copy(){return new o(this.duration,this.easing,this.clipPathResolver)}static lerp(t,n,i){return t+(n-t)*i}static circleClipPath(t,n){return`circle(${o.formatNumber(t)}% at ${n})`}static wipeClipPath(t,n){let i=o.formatNumber(n);switch(t){case"right":return`inset(0 0 0 ${i}%)`;case"top":return`inset(0 0 ${i}% 0)`;case"bottom":return`inset(${i}% 0 0 0)`;case"left":default:return`inset(0 ${i}% 0 0)`}}static formatNumber(t){return Number.isInteger(t)?String(t):t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}};function We(o){return o<0?0:o>1?1:o}function Vt(o){return{maskImage:o,WebkitMaskImage:o,maskSize:"100% 100%",WebkitMaskSize:"100% 100%",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat"}}function gr(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function lu(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 uu(o){return o==="vertical"?"to right":"to bottom"}function no(o,e,t){let n=Math.max(0,e),i=-n+We(t)*(100+n);return`linear-gradient(${lu(o)}, #000 ${i}%, transparent ${i+n}%)`}function io(o,e,t){let n=100/Math.max(1,e),i=We(t)*n;return`repeating-linear-gradient(${uu(o)}, #000 0, #000 ${i}%, transparent ${i}%, transparent ${n}%)`}function ha(o,e,t){let n=Math.max(0,e),i=(1-We(t))*150;return`radial-gradient(circle at ${o}, transparent ${i-n}%, #000 ${i}%)`}function ga(o,e,t){let n=Math.max(0,e),i=We(t)*150;return`radial-gradient(circle at ${o}, #000 ${i-n}%, transparent ${i}%)`}var yr=class o extends de{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.feather=e.feather??12,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:Vt(no(this.direction,this.feather,e))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,feather:this.feather,easing:this.easing})}};var vr=class o extends de{constructor(e){super(),this.duration=e.duration,this.orientation=e.orientation??"horizontal",this.slats=e.slats??8,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:Vt(io(this.orientation,this.slats,e))}))]}}copy(){return new o({duration:this.duration,orientation:this.orientation,slats:this.slats,easing:this.easing})}};var Sr=class o extends de{constructor(e){super(),this.duration=e.duration,this.center=e.center??"50% 50%",this.feather=e.feather??12,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:Vt(ga(this.center,this.feather,e))}))]}}copy(){return new o({duration:this.duration,center:this.center,feather:this.feather,easing:this.easing})}};var Tr=class o extends de{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-We(t),filter:`blur(${e*We(t)}px)`}})),this.asTarget(t=>({style:{opacity:We(t),filter:`blur(${e*(1-We(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var br=class o extends de{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisUnit(){switch(this.direction){case"right":return{axis:"x",unit:"vw",sign:1};case"top":return{axis:"y",unit:"vh",sign:-1};case"bottom":return{axis:"y",unit:"vh",sign:1};case"left":default:return{axis:"x",unit:"vw",sign:-1}}}translate(e){let{axis:t,unit:n}=this.axisUnit(),i=`${e}${n}`;return{translate:t==="x"?`${i} 0px`:`0px ${i}`}}createTask(){let{sign:e}=this.axisUnit();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*We(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-We(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var Cr=class o extends de{constructor(t,n,i,r,s){super();this.duration=t;this.color=n;this.hold=i;this.coverMask=r;this.easing=s}static fade(t){return new o(t.duration,t.color??"#000000",t.hold??.3,null,t.easing)}static wipe(t){let n=t.direction??"left",i=t.feather??12;return new o(t.duration,t.color??"#000000",t.hold??.3,r=>no(n,i,r),t.easing)}static blinds(t){let n=t.orientation??"horizontal",i=t.slats??8;return new o(t.duration,t.color??"#000000",t.hold??.3,r=>io(n,i,r),t.easing)}static iris(t){let n=t.center??"50% 50%",i=t.feather??12;return new o(t.duration,t.color??"#000000",t.hold??.3,r=>ha(n,i,r),t.easing)}coverStyle(t){return this.coverMask?{...gr(this.color),opacity:1,...Vt(this.coverMask(t))}:{...gr(this.color),opacity:We(t)}}createTask(){let n=(1-We(this.hold))/2,i=1-n,r=.5,s=a=>a<=n?n<=0?1:a/n:a>=i?i>=1?1:(1-a)/(1-i):1;return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(a=>({style:{opacity:a<r?1:0}})),this.asTarget(a=>({style:{opacity:a<r?0:1}})),a=>({src:R.DefaultImagePlaceholder,style:this.coverStyle(s(a))})]}}copy(){return new o(this.duration,this.color,this.hold,this.coverMask,this.easing)}};var Ar=class extends In{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 V(()=>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 oo=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=De.isChained(e)?e.getActions():e;return Ie.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}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 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 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(P.EventTypes["event:state.dialog.change"],t),e.events.on(P.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};oo.DynamicPersistent=ln;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
68
- @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-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}}}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.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}.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}.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}.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-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
69
- `,document.head.appendChild(o)}export{zt as Align,Io as Avatar,vr as Blinds,Tr as BlurDissolve,mi as Character,nt as CommonPosition,xn as CommonPositionType,mo as Condition,Ie as Control,_e as Coord2D,Wo as DefaultNvlContainer,Ns as DefaultNvlDialogItem,oo as DevTools,dl as Dialog,mr as Dissolve,_l as ExposedStateType,fr as FadeIn,Ds as FixedAspectRatioContainer,Ar as Gallery,_ as Game,Pi as GameMenu,ua as GameProviders,P as GameState,R as Image,de as ImageTransition,St as Isolated,Hi as Item,mn as KeyBindingType,$n as KeyMap,V as Lambda,pn as Layer,Oc as Layout,Kn as LayoutRouterProvider,gt as LiveGame,hr as MaskTransition,fo as Menu,Dn as NVLToken,mt as Namespace,It as Nametag,Pt as Narrator,Ui as Notifications,Vo as NvlContainer,ul as NvlDialogList,Oo as NvlProvider,Bc as Page,No as PageInjectContext,Re as Pause,cn as Persistent,la as Player,Mn as Preference,br as Push,is as RootPath,et as Scene,Se as Script,pe as Sentence,In as Service,Sr as SoftIris,yr as SoftWipe,fe as Sound,Nt as SoundType,ja as Stage,wn as Storable,Ln as Story,$t as Text,kn as TextTransition,mc as Texts,uc as TextsPreview,Cr as ThroughColor,Z as Transform,ht as Transition,yo as Video,q as Word,au as b,su as c,cu as i,bs as useAvatar,wc as useDialog,L as useGame,ol as useIsNvlMode,rl as useIsNvlVisible,Yt as useKeyBinding,Zc as useLiveGame,Tt as useNvl,Uo as useNvlDialogs,Mc as useParams,Rc as usePathname,at as usePreference,Nc as useQueryParams,vt as useRouter,Do as useUIMenuContext,Ec as useVoiceState};
69
+ at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},I=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Pe=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function Lu(o,e){return Q.color(o,e)}function Iu(o){return Q.bold(o)}function Ru(o){return Q.italic(o)}var wr=class o extends Ve{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 kr=class o extends Ve{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 J(o){return o<0?0:o>1?1:o}function Pa(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function Er(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function Da(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 La(o){return o==="vertical"?"to right":"to bottom"}var Pr=class o extends Ve{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-J(t),filter:`blur(${e*J(t)}px)`}})),this.asTarget(t=>({style:{opacity:J(t),filter:`blur(${e*(1-J(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var Dr=class o extends Ve{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisUnit(){switch(this.direction){case"right":return{axis:"x",unit:"vw",sign:1};case"top":return{axis:"y",unit:"vh",sign:-1};case"bottom":return{axis:"y",unit:"vh",sign:1};case"left":default:return{axis:"x",unit:"vw",sign:-1}}}translate(e){let{axis:t,unit:n}=this.axisUnit(),i=`${e}${n}`;return{translate:t==="x"?`${i} 0px`:`0px ${i}`}}createTask(){let{sign:e}=this.axisUnit();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*J(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-J(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 mo(o,e,t){return o<e?e:o>t?t:o}var Vt=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${G(t)}deg`:Da(t);return{mask:(r,s)=>{let a=-n+(s?1-J(r):J(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+J(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=J((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-J(r))*150;return`radial-gradient(${i} at ${t}, transparent ${G(c-n)}%, #000 ${G(c)}%)`}let a=J(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+J(s)*(360+i);if(c){let p=Math.max(0,360-l-i),d=Math.max(p,360-l);return`conic-gradient(from ${G(n)}deg at ${t}, transparent ${G(p)}deg, #000 ${G(d)}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-J(a):J(a))*(s+r),u=mo(l,0,s),p=mo(l+r,0,s),d=`repeating-conic-gradient(from ${G(i)}deg at ${n}`;return c?`${d}, transparent 0deg, transparent ${G(u)}deg, #000 ${G(p)}deg, #000 ${G(s)}deg)`:`${d}, #000 0deg, #000 ${G(u)}deg, transparent ${G(p)}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`:La(t),s=100/n;return{mask:(a,c)=>{let l=-i+(c?1-J(a):J(a))*(s+i),u=mo(l,0,s),p=mo(l+i,0,s);return c?`repeating-linear-gradient(${r}, transparent 0, transparent ${G(u)}%, #000 ${G(p)}%, #000 ${G(s)}%)`:`repeating-linear-gradient(${r}, #000 0, #000 ${G(u)}%, transparent ${G(p)}%, 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=J(e.stagger??0)*.5,a=(c,l,u)=>{let p=-i+J(l)*(100+i);return u?`radial-gradient(circle farthest-corner at ${c}, transparent ${G(p)}%, #000 ${G(p+i)}%)`:`radial-gradient(circle farthest-corner at ${c}, #000 ${G(p)}%, transparent ${G(p+i)}%)`};return{size:`${G(100/n)}% ${G(100/t)}%`,repeat:"repeat",mask:(c,l)=>{let u=l?1-J(c):J(c);if(s<=0)return a("50% 50%",u,l);let p=J(u/(1-s)),d=J((u-s)/(1-s));return l?`${a("50% 50%",d,!0)}, ${a("0% 0%",p,!0)}`:`${a("50% 50%",p)}, ${a("0% 0%",d)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return Pa(e.mask(t,n),e.size,e.repeat)}};var Lr=class o extends Ve{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{...Er(this.color),opacity:J(e)};let n={...Er(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...Vt.toStyle(this.pattern,e,!this.inverted)}:{...n,...Vt.toStyle(this.uncover,e)}:{...n,...Vt.toStyle(this.pattern,e,this.inverted)}}createTask(){let t=(1-J(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:M.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 Ir=class o extends Ve{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:Vt.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var Rr=class extends Vn{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 z(()=>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 fo=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=Le.isChained(e)?e.getActions():e;return Re.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}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 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 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(L.EventTypes["event:state.dialog.change"],t),e.events.on(L.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};fo.DynamicPersistent=hn;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
70
+ @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-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}.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-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
71
+ `,document.head.appendChild(o)}export{Xt as Align,Ko as Avatar,Pr as BlurDissolve,Gn as Camera,bi as Character,Qe as CommonPosition,un as CommonPositionType,Co as Condition,Re as Control,tt as Coord2D,Zo as DefaultNvlContainer,zs as DefaultNvlDialogItem,fo as DevTools,El as Dialog,wr as Dissolve,xu as ExposedStateType,kr as FadeIn,Fs as FixedAspectRatioContainer,Rr as Gallery,ne as Game,Hi as GameMenu,xa as GameProviders,L as GameState,M as Image,Ve as ImageTransition,At as Isolated,ji as Item,Tn as KeyBindingType,Zn as KeyMap,z as Lambda,yn as Layer,el as Layout,jn as LayoutRouterProvider,bt as LiveGame,Vt as Mask,xo as Menu,Nn as NVLToken,St as Namespace,Nt as Nametag,Rt as Narrator,Qi as Notifications,Yo as NvlContainer,wl as NvlDialogList,Xo as NvlProvider,rl as Page,$o as PageInjectContext,Me as Pause,fn as Persistent,Ca as Player,Un as Preference,Dr as Push,Ir as Reveal,ds as RootPath,nt as Scene,Ae as Script,ve as Sentence,Vn as Service,Se as Sound,Ut as SoundType,sc as Stage,Ln as Storable,Hn as Story,Yt as Text,Ye as TextEvent,In as TextTransition,Pc as Texts,wc as TextsPreview,Lr as ThroughColor,X as Transform,Tt as Transition,Eo as Vfx,ko as Video,Q as Word,Iu as b,Lu as c,Ru as i,Ls as useAvatar,Oc as useDialog,R as useGame,Sl as useIsNvlMode,Tl as useIsNvlVisible,on as useKeyBinding,ml as useLiveGame,wt as useNvl,Qo as useNvlDialogs,Qc as useParams,qc as usePathname,dt as usePreference,Xc as useQueryParams,xt as useRouter,Uo as useUIMenuContext,zc as useVoiceState};