narraleaf-react 0.29.0 → 0.29.1

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 (2) hide show
  1. package/dist/main.js +2 -2
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -24,7 +24,7 @@ To prevent unintended behavior and unexpected results, the sound have to be on t
24
24
  Maybe you bind the same wearable image to multiple parent images
25
25
  Parent Conflict (src: `+d.get(y)?.state.currentSrc+`)
26
26
  Current Parent (src: `+m.state.currentSrc+")");d.set(y,m)}});let p=[...this._initScene(this),...l.map(m=>m._init(this)),...u.map(m=>{if(!d.has(m))throw new Error("Wearable image must have a parent image");return d.get(m)._initWearable(m)}),...a.map(m=>m._init()),...c.map(m=>m._init()),...r],h=super.constructNodes(p),g=new C(this.sceneRoot,void 0,h||void 0).setContent(this);return h?.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 ie&&r.type===te.label){let[s]=r.contentNode.getContent();if(i.has(s))throw new Ge(`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 ie&&r.type===te.jump){let[s]=r.contentNode.getContent(),a=i.get(s);if(!a)throw new Ge(`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"?qt.say(n).getActions():ze.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(k.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:k.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===J.jumpTo){let u=c,d=He.getScene(t,u.contentNode.getContent()[0]);if(!d)throw c._sceneNotFoundError(c.getSceneName(u.contentNode.getContent()[0]));let p=Ee.getPreloadableSrc(t,c);if(p&&this.srcManager.register(p),r.has(u)||n.has(d))continue;r.add(u),a.add(d),n.add(d)}}else if(c instanceof ye){let l=Ee.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof tt)this.srcManager.register(c.callee);else if(c instanceof it){let l=c.type===$t.say?c.contentNode.getContent():null;for(let u of ta(c.callee,l))this.srcManager.register({type:"image",src:k.srcToURL(u)})}else if(c instanceof ie){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 Ge(`Duplicate static action id: ${c}`);i.add(c)}});let r=0,s=()=>{let a=`a-${r++}`;for(;i.has(a);)a=`a-${r++}`;return i.add(a),a};n.forEach(a=>{let c=a.getStaticId();a.resolveId(c||s())})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((i,r)=>{i.resolveId(`e-${r}`)})}getVoice(t){if(!t)return null;let n=this.config.voices;if(n){if(typeof n=="function"){let r=n(t);return typeof r=="string"?this.voiceOfSrc(r):(He.validateVoice(r),r)}let i=n[t];return typeof i=="string"?this.voiceOfSrc(i):i||null}return null}voiceOfSrc(t){let n=this.voiceCache.get(t);if(n)return n;let i=ge.voice(t);return this.voiceCache.set(t,i),i}getSceneRoot(){if(!this.sceneRoot)throw new Error("Scene root is not constructed");return this.sceneRoot}stringify(t,n,i){return super.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).map(r=>r.stringify(t,n,i)).join(";")}reset(){super.reset(),this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&!Fi(t.backgroundMusic.config.type,[nt.bgm]))throw new Ge(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
27
- To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new R({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new re(this.chain(),"scene:jumpTo",new C().setContent([t])))}_exit(){return new re(this.chain(),"scene:exit",new C().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new re(i,J.transitionToScene,new C().setContent([t,n]))):i}_init(t){return new re(this.chain(),"scene:init",new C().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};He.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},He.DefaultUserConfig=new K({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),He._defaultSceneConfig=null;var ht=He;import*as la from"howler";var ji=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 Xc={volume:1,limit:1/0},Jc=class ia{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={...Xc,...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 ia(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}}},oa=!1;function Zc(o){oa=o}function rn(o,e){oa||(e!==void 0?console.warn(o,e):console.warn(o))}var _c=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){rn("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){rn("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){rn("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()}},na=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}},el=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 _c(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){rn("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){rn("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 na(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new na(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}},tl=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}},nl=10*1024*1024,il=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 tl(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}}},ol={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},ra=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...ol,...o},Zc(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new il(this.audioContext),this.masterChannel=new Jc("__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=>{rn("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let d=new el(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,h=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",h),d.once("stop",h)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<nl?"full":"stream"}catch(t){return rn("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=>{rn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var de=class de{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new ra({maxChannels:de.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=de.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,de.BusRampTimeConstant),r.setValueAtTime(s,a+de.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${nt.sound}" instead.`)),this.channels.get(nt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=de.defaultFade(e)){let n=new T;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=de.clipRegionOf(e),a=await i.play(r,{volume:0,...de.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(l=>{a.once("ended",()=>l())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=de.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new P(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=await n.play(i,{volume:0,...de.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new T;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new T;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}pause(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),i.token.fade(0,i.originalVolume,t).finished.then(()=>{e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return T.resolve(void 0);let n=this.state.get(e),i=de.clampToRegion(t,de.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),T.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,T.resolve(void 0)):T.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...de.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(de.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c,e.state.paused?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};de.MaxChannels=1024,de.BusRampTimeConstant=.02,de.BusRampSettle=de.BusRampTimeConstant*5;var qi=de;import*as ul from"html-to-image";var Yi=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 T,n=new xe(t);return t.registerSkipController(new G(()=>{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")}};function Qi(o,e,t){let n={},i={};Object.keys(e).forEach(s=>{let a=s;a==="style"&&e.style?Object.assign(n,e.style):e[a]!==void 0&&a!=="key"&&(i[a]=e[a])}),Object.keys(n).length>0&&Object.assign(o.style,n);let r=t?t(i):i;for(let[s,a]of Object.entries(r))o.getAttribute(s)!==a&&o.setAttribute(s,a)}var rl=4e3,ca={zIndex:0,visibility:"visible"},sl={...ca,zIndex:1},sa={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function Xi(){return{zIndex:"auto",visibility:"visible",opacity:1,transform:"none",translate:"none",filter:"none",clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat"}}function al(){return{...Xi(),visibility:"hidden"}}var Ji=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?this.sceneElements.set(e.getId(),t):this.sceneElements.delete(e.getId())}registerOverlayHost(e){this.overlayHost=e}reset(){this.running?.controller.complete(),this.running=null}skip(){this.running&&(this.gameState.logger.debug("StageTransition","Transition skipped"),this.running.controller.complete())}apply(e,t,n){this.running?.controller.complete();let i=e;typeof i._setDetached=="function"&&i._setDetached(!0);let r=e.createTask(this.gameState),s=e.requestAnimations(r.animations),a=new T().registerSkipController(new G(s.cancel)),c=new xe(a),l=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return l.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:l,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,Xi()],[t.from,al()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,Xi()],[t.to,Xi()]]),c.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),c}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,c=r.kind==="overlay"?sa:r.role==="target"?sl:ca,l=$({style:c},a(...t));Qi(s,l,cl)})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{let r=this.sceneElements.get(n.getId());r&&Object.assign(r.style,i)}),this.running===e&&(this.running=null)}createOverlay(){let e=document.createElement("div");return e.setAttribute("data-element-type","stage-transition-overlay"),Object.assign(e.style,sa),this.overlayHost?.appendChild(e),e}waitForSceneReady(e){let t=this.sceneElements.get(e.getId());if(!t)return{promise:Promise.resolve(),cancel:()=>{}};let n=()=>{},i=new Promise(s=>{n=this.gameState.schedule(()=>{this.gameState.logger.weakWarn("StageTransition","Timed out waiting for the incoming scene to load"),s()},rl)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(ll)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},aa=["src","width","height"];function cl(o){if(!aa.some(t=>t in o))return o;let e={...o};return aa.forEach(t=>delete e[t]),e}function ll(o){return o.getAttribute("src")?typeof o.decode=="function"?o.decode().then(()=>{},()=>{}):o.complete?Promise.resolve():new Promise(e=>{let t=()=>{o.removeEventListener("load",t),o.removeEventListener("error",t),e()};o.addEventListener("load",t),o.addEventListener("error",t)}):Promise.resolve()}var Zi=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=Ii(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var _i=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??Ii(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var hn=class extends j{executeAction(e,t){let n=new T().registerSkipController(new G(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(l,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};hn.ActionTypes=Ps;var gn=class gn extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=fe.isSentence(t)?t:t===null?null:new fe(t),this.config=$(gn.defaultConfig,n)}static prompt(t,n={}){return new gn(t!==void 0?t:null,n)}static choose(t,n){return new gn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return fe.isSentence(t)&&n?i.choices.push({prompt:fe.toSentence(t),action:this.narrativeToActions(n),config:{}}):(Z.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:fe.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:fe.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?q.from(t.config.disabled):void 0,hidden:t.config?.hidden?q.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 Ge("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=q.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Ge("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=q.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:q.not(q.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:q.not(q.from(t))}})}fromChained(t){return[new hn(this.chain(),hn.ActionTypes.action,new C().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?qt.say(n).getActions():ze.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??{}}))}};gn.defaultConfig={},gn.targetAction=hn;var or=gn;var Gt=class Gt extends ut{static get DefaultUserConfig(){return Gt._defaultUserConfig??(Gt._defaultUserConfig=new K({...X.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e={}){super();let t=Gt.DefaultUserConfig.create(e),n=Gt.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}resetCamera(e,t){return this.transform(new _({position:new ct("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,filter:"none"},{duration:e,ease:t}))}reset(){return super.reset(),this.transformState=this.getInitialTransformState(),this}toData(){return{transformState:this.transformState.serialize()}}fromData(e){return this.transformState=X.deserialize(e.transformState),this}copy(){return new Gt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(X.DefaultTransformState.keys());return new X(X.DefaultTransformState.create(e.get()).get())}};Gt._defaultUserConfig=null,Gt.DefaultConfig=new K({name:"(camera)"});var Zn=Gt;var sn=class sn extends En{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.name=t;let{camera:i,...r}=n;this.config=$(sn.defaultConfig,r),this._camera=i??new Zn}static empty(){return new sn("empty").entry(new ht("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 Dn(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 Ge(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return Fs(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 ne(`Service ${i} serialize method should not return a promise`);if(!$o(r))throw new ne(`Service ${i} serialize method should return a pure object.
27
+ To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new R({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new re(this.chain(),"scene:jumpTo",new C().setContent([t])))}_exit(){return new re(this.chain(),"scene:exit",new C().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new re(i,J.transitionToScene,new C().setContent([t,n]))):i}_init(t){return new re(this.chain(),"scene:init",new C().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};He.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},He.DefaultUserConfig=new K({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),He._defaultSceneConfig=null;var ht=He;import*as la from"howler";var ji=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 Xc={volume:1,limit:1/0},Jc=class ia{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={...Xc,...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 ia(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}}},oa=!1;function Zc(o){oa=o}function rn(o,e){oa||(e!==void 0?console.warn(o,e):console.warn(o))}var _c=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){rn("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){rn("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){rn("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()}},na=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}},el=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 _c(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){rn("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){rn("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 na(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new na(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}},tl=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}},nl=10*1024*1024,il=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 tl(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}}},ol={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},ra=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...ol,...o},Zc(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new il(this.audioContext),this.masterChannel=new Jc("__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=>{rn("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let d=new el(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,h=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",h),d.once("stop",h)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<nl?"full":"stream"}catch(t){return rn("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=>{rn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var de=class de{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new ra({maxChannels:de.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=de.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,de.BusRampTimeConstant),r.setValueAtTime(s,a+de.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${nt.sound}" instead.`)),this.channels.get(nt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=de.defaultFade(e)){let n=new T;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=de.clipRegionOf(e),a=await i.play(r,{volume:0,...de.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(l=>{a.once("ended",()=>l())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=de.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new P(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=await n.play(i,{volume:0,...de.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new T;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new T;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}pause(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new T;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),i.token.fade(0,i.originalVolume,t).finished.then(()=>{e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return T.resolve(void 0);let n=this.state.get(e),i=de.clampToRegion(t,de.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),T.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,T.resolve(void 0)):T.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...de.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(de.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c,e.state.paused?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};de.MaxChannels=1024,de.BusRampTimeConstant=.02,de.BusRampSettle=de.BusRampTimeConstant*5;var qi=de;import*as ul from"html-to-image";var Yi=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 T,n=new xe(t);return t.registerSkipController(new G(()=>{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")}};function Qi(o,e,t){let n={},i={};Object.keys(e).forEach(s=>{let a=s;a==="style"&&e.style?Object.assign(n,e.style):e[a]!==void 0&&a!=="key"&&(i[a]=e[a])}),Object.keys(n).length>0&&Object.assign(o.style,n);let r=t?t(i):i;for(let[s,a]of Object.entries(r))o.getAttribute(s)!==a&&o.setAttribute(s,a)}var rl=4e3,ca={zIndex:0,visibility:"visible"},sl={...ca,zIndex:1},sa={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function Xi(){return{zIndex:"auto",visibility:"visible",opacity:1,transform:"none",translate:"none",filter:"none",clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat"}}function al(){return{...Xi(),visibility:"hidden"}}var Ji=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?this.sceneElements.set(e.getId(),t):this.sceneElements.delete(e.getId())}registerOverlayHost(e){this.overlayHost=e}reset(){this.running?.controller.complete(),this.running=null}skip(){this.running&&(this.gameState.logger.debug("StageTransition","Transition skipped"),this.running.controller.complete())}apply(e,t,n){this.running?.controller.complete();let i=e;typeof i._setDetached=="function"&&i._setDetached(!0);let r=e.createTask(this.gameState),s=e.requestAnimations(r.animations),a=new T().registerSkipController(new G(s.cancel)),c=new xe(a),l=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return l.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:l,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,Xi()],[t.from,al()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,Xi()],[t.to,Xi()]]),c.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),c}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,c=r.kind==="overlay"?sa:r.role==="target"?sl:ca,l=$({style:c},a(...t));Qi(s,l,cl)})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{let r=this.sceneElements.get(n.getId());r&&Object.assign(r.style,i)}),this.running===e&&(this.running=null)}createOverlay(){let e=document.createElement("div");return e.setAttribute("data-element-type","stage-transition-overlay"),Object.assign(e.style,sa),this.overlayHost?.appendChild(e),e}waitForSceneReady(e){let t=this.sceneElements.get(e.getId());if(!t)return{promise:Promise.resolve(),cancel:()=>{}};let n=()=>{},i=new Promise(s=>{n=this.gameState.schedule(()=>{this.gameState.logger.weakWarn("StageTransition","Timed out waiting for the incoming scene to load"),s()},rl)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(ll)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},aa=["src","width","height"];function cl(o){if(!aa.some(t=>t in o))return o;let e={...o};return aa.forEach(t=>delete e[t]),e}function ll(o){return o.getAttribute("src")?typeof o.decode=="function"?o.decode().then(()=>{},()=>{}):o.complete?Promise.resolve():new Promise(e=>{let t=()=>{o.removeEventListener("load",t),o.removeEventListener("error",t),e()};o.addEventListener("load",t),o.addEventListener("error",t)}):Promise.resolve()}var Zi=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=Ii(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var _i=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??Ii(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var hn=class extends j{executeAction(e,t){let n=new T().registerSkipController(new G(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(l,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};hn.ActionTypes=Ps;var gn=class gn extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=fe.isSentence(t)?t:t===null?null:new fe(t),this.config=$(gn.defaultConfig,n)}static prompt(t,n={}){return new gn(t!==void 0?t:null,n)}static choose(t,n){return new gn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return fe.isSentence(t)&&n?i.choices.push({prompt:fe.toSentence(t),action:this.narrativeToActions(n),config:{}}):(Z.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:fe.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:fe.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?q.from(t.config.disabled):void 0,hidden:t.config?.hidden?q.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 Ge("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=q.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Ge("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=q.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:q.not(q.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:q.not(q.from(t))}})}fromChained(t){return[new hn(this.chain(),hn.ActionTypes.action,new C().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?qt.say(n).getActions():ze.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??{}}))}};gn.defaultConfig={},gn.targetAction=hn;var or=gn;var Gt=class Gt extends ut{static get DefaultUserConfig(){return Gt._defaultUserConfig??(Gt._defaultUserConfig=new K({...X.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e={}){super();let t=Gt.DefaultUserConfig.create(e),n=Gt.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}resetCamera(e,t){return this.transform(new _([{props:{filter:"none"},options:{duration:0}},{props:{position:new ct("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1},options:{duration:e,ease:t}}]))}reset(){return super.reset(),this.transformState=this.getInitialTransformState(),this}toData(){return{transformState:this.transformState.serialize()}}fromData(e){return this.transformState=X.deserialize(e.transformState),this}copy(){return new Gt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(X.DefaultTransformState.keys());return new X(X.DefaultTransformState.create(e.get()).get())}};Gt._defaultUserConfig=null,Gt.DefaultConfig=new K({name:"(camera)"});var Zn=Gt;var sn=class sn extends En{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.name=t;let{camera:i,...r}=n;this.config=$(sn.defaultConfig,r),this._camera=i??new Zn}static empty(){return new sn("empty").entry(new ht("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 Dn(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 Ge(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return Fs(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 ne(`Service ${i} serialize method should not return a promise`);if(!$o(r))throw new ne(`Service ${i} serialize method should return a pure object.
28
28
  A pure object should:
29
29
  1. be an object literal
30
30
  2. not have any prototype
@@ -78,5 +78,5 @@ Scene: ${s.config.name}
78
78
  At: ${t.__stack}`;throw new Ge(a)}}else i.set(s.config.name,s);if(t.type===J.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(r.has(c))return;r.add(c)}}}checkImage(e,t){if(t.type===dt.setSrc){let i=t.contentNode.getContent()[0];k.isImageURL(i)&&k.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},ne=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`
79
79
  Using action (id: ${e.getId()})
80
80
  at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},P=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Ve=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function fd(o,e){return Z.color(o,e)}function hd(o){return Z.bold(o)}function gd(o){return Z.italic(o)}var gs=class o extends Me{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 ys=class o extends Me{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 Q(o){return o<0?0:o>1?1:o}function Oc(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function vs(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function Uc(o){switch(o){case"left":return"to left";case"top":return"to top";case"bottom":return"to bottom";case"right":default:return"to right"}}function Wc(o){return o==="vertical"?"to right":"to bottom"}var Ss=class o extends Me{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-Q(t),filter:`blur(${e*Q(t)}px)`}})),this.asTarget(t=>({style:{opacity:Q(t),filter:`blur(${e*(1-Q(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var Ts=class o extends Me{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*Q(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-Q(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var bs=class o extends Me{constructor(e){super(),this.duration=e.duration,this.ev=e.ev??4.6,this.lift=e.lift??.04,this.hold=e.hold??0,this.easing=e.easing}burnStyle(e){let t=Q(e);if(t<=0)return{filter:"none"};let n=Q(this.lift)*t,i=Math.pow(2,Math.max(0,this.ev)*t);return{filter:`invert(1) brightness(${1-n}) invert(1) brightness(${i})`}}createTask(){let t=(1-Q(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.burnStyle(r(s))}})),this.asTarget(s=>({style:{opacity:s<i?0:1,...this.burnStyle(r(s))}}))]}}copy(){return new o({duration:this.duration,ev:this.ev,lift:this.lift,hold:this.hold,easing:this.easing})}};function N(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function Uo(o,e,t){return o<e?e:o>t?t:o}var Jt=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${N(t)}deg`:Uc(t);return{mask:(r,s)=>{let a=-n+(s?1-Q(r):Q(r))*(100+n);return s?`linear-gradient(${i}, transparent ${N(a)}%, #000 ${N(a+n)}%)`:`linear-gradient(${i}, #000 ${N(a)}%, transparent ${N(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${N(t)}deg`,`${N(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let c=-n+Q(s)*(50+n);if(!a){let l=u=>`linear-gradient(${u}, #000 ${N(c)}%, transparent ${N(c+n)}%)`;return`${l(i)}, ${l(r)}`}if(c<0){let l=Q((c+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${N(50-c-n)}%, rgba(0,0,0,${N(l)}) 50%, transparent ${N(50+c+n)}%)`}return`linear-gradient(${i}, transparent ${N(50-c-n)}%, #000 ${N(50-c)}%, #000 ${N(50+c)}%, transparent ${N(50+c+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let c=(1-Q(r))*150;return`radial-gradient(${i} at ${t}, transparent ${N(c-n)}%, #000 ${N(c)}%)`}let a=Q(r)*150;return`radial-gradient(${i} at ${t}, #000 ${N(a-n)}%, transparent ${N(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let c=r==="counterclockwise"!=!!a,l=-i+Q(s)*(360+i);if(c){let d=Math.max(0,360-l-i),p=Math.max(d,360-l);return`conic-gradient(from ${N(n)}deg at ${t}, transparent ${N(d)}deg, #000 ${N(p)}deg)`}let u=Math.max(0,l);return`conic-gradient(from ${N(n)}deg at ${t}, #000 ${N(u)}deg, transparent ${N(Math.max(u,l+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,c)=>{let l=-r+(c?1-Q(a):Q(a))*(s+r),u=Uo(l,0,s),d=Uo(l+r,0,s),p=`repeating-conic-gradient(from ${N(i)}deg at ${n}`;return c?`${p}, transparent 0deg, transparent ${N(u)}deg, #000 ${N(d)}deg, #000 ${N(s)}deg)`:`${p}, #000 0deg, #000 ${N(u)}deg, transparent ${N(d)}deg, transparent ${N(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,e.slats??8),i=Math.max(0,e.feather??0),r=typeof t=="number"?`${N(t)}deg`:Wc(t),s=100/n;return{mask:(a,c)=>{let l=-i+(c?1-Q(a):Q(a))*(s+i),u=Uo(l,0,s),d=Uo(l+i,0,s);return c?`repeating-linear-gradient(${r}, transparent 0, transparent ${N(u)}%, #000 ${N(d)}%, #000 ${N(s)}%)`:`repeating-linear-gradient(${r}, #000 0, #000 ${N(u)}%, transparent ${N(d)}%, transparent ${N(s)}%)`}}}static dots(e={}){let t=Math.max(1,e.rows??6),n=Math.max(1,e.cols??10),i=Math.max(0,e.feather??20),s=Q(e.stagger??0)*.5,a=(c,l,u)=>{let d=-i+Q(l)*(100+i);return u?`radial-gradient(circle farthest-corner at ${c}, transparent ${N(d)}%, #000 ${N(d+i)}%)`:`radial-gradient(circle farthest-corner at ${c}, #000 ${N(d)}%, transparent ${N(d+i)}%)`};return{size:`${N(100/n)}% ${N(100/t)}%`,repeat:"repeat",mask:(c,l)=>{let u=l?1-Q(c):Q(c);if(s<=0)return a("50% 50%",u,l);let d=Q(u/(1-s)),p=Q((u-s)/(1-s));return l?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return Oc(e.mask(t,n),e.size,e.repeat)}};var As=class o extends Me{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{...vs(this.color),opacity:Q(e)};let n={...vs(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...Jt.toStyle(this.pattern,e,!this.inverted)}:{...n,...Jt.toStyle(this.uncover,e)}:{...n,...Jt.toStyle(this.pattern,e,this.inverted)}}createTask(){let t=(1-Q(this.hold))/2,n=1-t,i=.5,r=s=>s<=t?t<=0?1:s/t:s>=n?n>=1?1:(1-s)/(1-n):1;return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(s=>({style:{opacity:s<i?1:0}})),this.asTarget(s=>({style:{opacity:s<i?0:1}})),s=>({src:R.DefaultImagePlaceholder,style:this.coverStyle(r(s),s>=n)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var xs=class o extends Me{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:Jt.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var Cs=class extends ei{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 q(()=>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 Wo=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=ze.isChained(e)?e.getActions():e;return je.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return R.getSrcURLs(e,t)}static registerDisplayable(e,t,n=null,i=null){e.findElementByDisplayable(t)||(e.createDisplayable(t,n,i),e.flush())}static setElementId(e,t){e.setId(t)}static setElementStaticId(e,t){e.setStaticId(t)}static getDisplayableTransformProps(e){return{...e.transformState.get()}}static setDisplayableTransformProps(e,t,n,i={}){let r=t.transformState;i.merge===!1?r.forceOverwrite(n):r.assign(Symbol("DevTools.setDisplayableTransformProps"),n),t.markDirty(),e.getExposedState(t)?.updateStyleSync?.(),e.flush()}static getPuppetStatus(e){return e._getStatus()}static onPuppetStatusChange(e,t){return e._onStatusChange(t)}static async describePuppet(e,t){try{return await t._describe()}catch(n){return e.logger.error("DevTools","Puppet backend threw while describing itself",n),null}}static getPuppetState(e){return xt.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?xt.normalizeState(n):xt.mergeState(t.state,n),t._applyState().catch(r=>{e.logger.error("DevTools","Puppet backend threw while applying state",r)}),e.flush()}static async runPuppetCommand(e,t,n,i){try{await t._runCommand(n,i)||e.logger.weakWarn("DevTools",`Puppet command "${n}" was dropped: the puppet is not mounted.`)}catch(r){e.logger.error("DevTools",`Puppet backend threw while running "${n}"`,r)}}static listPuppetBackends(e){return e.listPuppetBackends()}static getCurrentDialog(e){if(e.isNvlMode()){let n=e.getNvlState();if(!n.activeDialogId||n.phase==="idle")return null;let i=e.getNvlDialog(n.activeDialogId);return i?{actionId:i.actionId||null,ended:n.phase==="awaitAdvance",mode:"nvl"}:null}let t=e.getAdvDialogState();return t?{actionId:t.actionId,ended:t.ended,mode:"adv"}:null}static onDialogStateChange(e,t){let n=[e.events.on(E.EventTypes["event:state.dialog.change"],t),e.events.on(E.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};Wo.DynamicPersistent=Ln;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
81
- @layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.isolate{isolation:isolate}.z-20{z-index:20}.container{width:100%}.\\!hidden{display:none!important}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow,.grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.mask-repeat{-webkit-mask-repeat:repeat;mask-repeat:repeat}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.ordinal{--tw-ordinal:ordinal;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.decoration-dotted{text-decoration-style:dotted}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-filter{backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}\r
81
+ @layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.isolate{isolation:isolate}.z-20{z-index:20}.container{width:100%}.\\!hidden{display:none!important}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow,.grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.mask-repeat{-webkit-mask-repeat:repeat;mask-repeat:repeat}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.ordinal{--tw-ordinal:ordinal;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.decoration-dotted{text-decoration-style:dotted}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.grayscale{--tw-grayscale:grayscale(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,)}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-filter{backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}\r
82
82
  `,document.head.appendChild(o)}export{dn as Align,en as AudioBusError,qn as AudioBusMixer,jn as AudioBusTree,Lr as Avatar,Ss as BlurDissolve,Zn as Camera,Ki as Character,ct as CommonPosition,wn as CommonPositionType,ir as Condition,je as Control,ft as Coord2D,gi as Darkness,nt as DefaultAudioBusIds,Wr as DefaultNvlContainer,Za as DefaultNvlDialogItem,Wo as DevTools,rp as Dialog,gs as Dissolve,sd as ExposedStateType,bs as Exposure,ys as FadeIn,qa as FixedAspectRatioContainer,Cs as Gallery,oe as Game,ao as GameMenu,Nc as GameProviders,E as GameState,R as Image,Me as ImageTransition,Ft as Isolated,So as Item,Gn as KeyBindingType,hi as KeyMap,q as Lambda,In as Layer,Pu as Layout,li as LayoutRouterProvider,Mt as LiveGame,Jt as Mask,Vi as MaxAudioBusDepth,or as Menu,Jn as NVLToken,It as Namespace,Qt as Nametag,qt as Narrator,bo as Notifications,Ur as NvlContainer,Zu as NvlDialogList,Fr as NvlProvider,Iu as Page,Mr as PageInjectContext,$e as Pause,Dn as Persistent,Mc as Player,ni as Preference,xt as Puppet,Ts as Push,xs as Reveal,ga as RootPath,ht as Scene,Ae as Script,qs as SeededBusPreferenceKeys,fe as Sentence,ei as Service,ge as Sound,Qs as SoundType,Cl as Stage,zn as Storable,_n as Story,fn as Text,lt as TextEvent,Yn as TextTransition,_l as Texts,Xl as TextsPreview,As as ThroughColor,_ as Transform,Nt as Transition,cr as Vfx,ar as Video,Z as Word,Fi as acceptsAudioBus,hd as b,fd as c,er as getActiveAudioBusTree,Kl as getWordRenderer,gd as i,Wl as registerWordRenderer,Bl as unregisterWordRenderer,Oa as useAvatar,mu as useDialog,np as useDialogOverlay,L as useGame,ju as useIsNvlMode,qu as useIsNvlVisible,vn as useKeyBinding,Uu as useLiveGame,Wt as useNvl,Vr as useNvlDialogs,bu as useParams,Tu as usePathname,ln as usePreference,Au as useQueryParams,Vt as useRouter,op as useSuspendAdvance,kr as useUIMenuContext,gu as useVoiceState};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "narraleaf-react",
3
- "version": "0.29.0",
3
+ "version": "0.29.1",
4
4
  "description": "A React visual novel player framework",
5
5
  "type": "module",
6
6
  "main": "./dist/main.js",