narraleaf-react 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js
CHANGED
|
@@ -1,88 +1,88 @@
|
|
|
1
|
-
var
|
|
1
|
+
var he={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",applyLoop:"displayable:applyLoop",stopLoop:"displayable:stopLoop",init:"displayable:init",bringToFront:"displayable:bringToFront"},Jt={say:"character:say",action:"character:action",setName:"character:setName"},W={action:"scene:action",init:"scene:init",exit:"scene:exit",jumpTo:"scene:jumpTo",callTo:"scene:callTo",preSuspend:"scene:preSuspend",resume:"scene:resume",setBackgroundMusic:"scene:setBackgroundMusic",preUnmount:"scene:preUnmount",transitionToScene:"scene:transitionToScene",nvlBlock:"scene:nvlBlock",nvlShow:"scene:nvlShow",nvlHide:"scene:nvlHide",nvlEnd:"scene:nvlEnd"};var ht={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},pa={action:"condition:action"},da={action:"script:action"},ma={action:"menu:action"},Ft={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute",seek:"sound:seek"},ce={action:"control:action",do:"control:do",doAsync:"control:doAsync",any:"control:any",all:"control:all",allAsync:"control:allAsync",repeat:"control:repeat",while:"control:while",break:"control:break",sleep:"control:sleep",waitForClick:"control:waitForClick",label:"control:label",jump:"control:jump"},ji={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},oi={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},An={action:"layer:action",setZIndex:"layer:setZIndex"},Dt={action:"video:action",preload:"video:preload",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"},Zt={action:"vfx:action",preload:"vfx:preload",show:"vfx:show",hide:"vfx:hide",pause:"vfx:pause",resume:"vfx:resume",setRate:"vfx:setRate"},nt={action:"puppet:action",setMotion:"puppet:setMotion",setExpression:"puppet:setExpression",setSkin:"puppet:setSkin",setParam:"puppet:setParam",setSlot:"puppet:setSlot",command:"puppet:command"};var fa=(d=>(d[d.string=0]="string",d[d.number=1]="number",d[d.boolean=2]="boolean",d[d.object=3]="object",d[d.array=4]="array",d[d.function=5]="function",d[d.symbol=6]="symbol",d[d.undefined=7]="undefined",d[d.null=8]="null",d[d.date=9]="date",d[d.regexp=10]="regexp",d[d.other=11]="other",d))(fa||{}),vr=(function(o){return typeof o=="string"?0:typeof o=="number"?1:typeof o=="boolean"?2:typeof o=="object"?Array.isArray(o)?4:o===null?8:o instanceof Date?9:o instanceof RegExp?10:3:typeof o=="function"?5:typeof o=="symbol"?6:typeof o>"u"?7:11});vr.DataTypes=fa;function Q(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,l)=>vr(a)===3&&vr(l)===3?a.constructor!==Object||l.constructor!==Object?l||a:Q(a,l):Array.isArray(a)&&Array.isArray(l)?l&&l.length>0?[...l]:[...a]:a===void 0&&Array.isArray(l)?[...l]:l===void 0?Array.isArray(a)?[...a]:a:Array.isArray(l)?[...l]:l;for(let s in o)n(o,s)&&(i[s]=r(s,o[s],e[s]));for(let s in e)n(e,s)&&!n(i,s)&&(typeof e[s]=="object"&&e[s]!==null?e[s].constructor===Object?i[s]=Q({},e[s]):Array.isArray(e[s])?i[s]=[...e[s]]:i[s]=e[s]:i[s]=e[s]);if(t.length){let[s,...a]=t;return Q(i,s,...a)}return i}var Ye=class Ye{constructor(e=(n=>n),t){this.solved=!1;this.aborted=!1;this.failed=!1;this.error=null;this.listeners=[];this.failListeners=[];this.settledListeners=[];this.onRegisterSkipController=[];this.skipControllerAbortToken=null;this.settledNotified=!1;this.receiver=e,this.skipController=t,this.__stack=Sr()}static isAwaitable(e){return e instanceof Ye}static fromPromise(e){let t=new Ye;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new Ye;return t.resolve(e),t}static delay(e){let t=new Ye;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new Ye;return e(t),t}static wait(e){let t=new Ye;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new Ye;return e.length===0?(t.resolve(void 0),t):(e.forEach(n=>{n.then(i=>{e.forEach(r=>{r!==n&&r.skipController?.abort()}),t.resolve(i)}),n.onFailed(i=>t.fail(i))}),t.registerSkipController(new B(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new Ye().registerSkipController(n||new B(()=>t));e.then(()=>i.resolve(t)),e.onFailed(a=>i.fail(a));let r=e.skipController?.onAbort(()=>{i.skipController?.abort(),r?.cancel(),s?.cancel()}),s=i.skipController?.onAbort(()=>{e.skipController?.abort(),r?.cancel(),s?.cancel()});return i}static toPromise(e){return new Promise((t,n)=>{e.then(t),e.onFailed(n)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new Ye;return e.length===0?(t.resolve(),t):(e.forEach(n=>{n.onSettled(()=>t.resolve()),n.onFailed(i=>{t.fail(i),e.forEach(r=>{r!==n&&r.abort()})})}),t.registerSkipController(new B(()=>{e.forEach(n=>n.abort())})),t)}static all(...e){let t=new Ye;if(e.length===0)return t.resolve(),t;let n=0;return e.forEach(i=>{i.onSettled(()=>{n++,n===e.length&&t.resolve()}),i.onFailed(r=>{e.forEach(s=>{s!==i&&s.abort()}),t.fail(r)})}),t.registerSkipController(new B(()=>{e.forEach(i=>i.abort())})),t}registerSkipController(e){this.skipControllerAbortToken?.cancel(),this.skipController=e,this.skipControllerAbortToken=e.onAbort(()=>{this.aborted=!0,this.notifySettled()});for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.isSettled()){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result);this.notifySettled()}}fail(e){if(!this.isSettled()){this.error=e,this.failed=!0,this.skipController&&this.skipController.cancel();for(let t of this.failListeners)t(e);this.notifySettled()}}then(e,t){return this.solved?e(this.result):this.failed?t?.(this.error):(this.pushListener(e),t&&this.pushFailListener(t)),this}onSettled(e){if(this.isSettled())e();else return this.settledListeners.push(e),{cancel:()=>{this.offSettledListener(e)}};return{cancel:()=>{}}}onFailed(e){if(this.failed)e(this.error);else if(!this.isSettled())return this.pushFailListener(e),{cancel:()=>{this.offFailListener(e)}};return{cancel:()=>{}}}onSkipControllerRegister(e){return this.skipController?e(this.skipController):this.onRegisterSkipController.push(e),{cancel:()=>{this.offSkipControllerRegister(e)}}}offSkipControllerRegister(e){let t=this.onRegisterSkipController.indexOf(e);return t!==-1&&this.onRegisterSkipController.splice(t,1),this}abort(){return this.isSettled()?this.result:(this.aborted=!0,this.skipController?this.skipController.abort():this.notifySettled(),this.result)}isSolved(){return this.solved&&!this.aborted&&!this.failed}isAborted(){return this.aborted}isFailed(){return this.failed}isSettled(){return this.solved||this.aborted||this.failed}pushListener(e){return this.listeners.length>=Ye.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many listeners, this may cause performance issues."),this.listeners.push(e),this}pushFailListener(e){return this.failListeners.length>=Ye.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many failure listeners, this may cause performance issues."),this.failListeners.push(e),this}offListener(e){let t=this.listeners.indexOf(e);return t!==-1&&this.listeners.splice(t,1),this}offFailListener(e){let t=this.failListeners.indexOf(e);return t!==-1&&this.failListeners.splice(t,1),this}offSettledListener(e){let t=this.settledListeners.indexOf(e);return t!==-1&&this.settledListeners.splice(t,1),this}notifySettled(){if(!this.settledNotified){this.settledNotified=!0;for(let e of this.settledListeners)e()}}};Ye.nothing=e=>e,Ye.maxListeners=8;var v=Ye;function ha(o){let e=new WeakSet;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return;if(e.add(n),Array.isArray(n)){let r=[];for(let s of n)r.push(t(s));return r}let i={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=t(n[r]));return i}return t(o)}function On(o){return typeof o=="string"?o:`#${(o.r||0).toString(16).padStart(2,"0")}${(o.g||0).toString(16).padStart(2,"0")}${(o.b||0).toString(16).padStart(2,"0")}${o.a===void 0?"":o.a.toString(16).padStart(2,"0")}`}var ee=class{constructor(){this.events={};this.maxListeners=10}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this.events[e].length>this.maxListeners&&console.warn(`NarraLeaf-React: Event ${e} has more than ${this.maxListeners} listeners (total: ${this.events[e].length}), this may cause performance issues.`),this.emit("event:EventDispatcher.register",e,t),{type:e,listener:t,cancel:()=>{this.off(e,t)}}}depends(e){return{cancel:()=>{e.forEach(t=>t.cancel())}}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(n=>n!==t))}emit(e,...t){if(!this.events[e])return 0;let n=this.events[e].length;return this.events[e].forEach(i=>{i(...t)}),n}once(e,t){let n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n)}async any(e,...t){if(this.events[e]||(this.events[e]=[]),this.events[e].length>0){await Promise.all(this.events[e].map(n=>n(...t)));return}return new Promise(n=>{let i="event:EventDispatcher.register",r=this.on(i,(s,a)=>{if(s===e){this.off(i,r);let l=a?.(...t);l!==null&&typeof l=="object"&&l.then?l.then(n):n(l)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function Sr(o=1){let e=new Error().stack;return e?e.split(`
|
|
2
2
|
`).slice(o+1).join(`
|
|
3
|
-
`).trim():""}function Ji(o){return new Promise(e=>setTimeout(e,o))}var Xi=class Xi{constructor(e){this.abortHandler=e;this.events=new Z;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Xi.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Xi.EventTypes={"event:skipController.abort":"event:skipController.abort"};var B=Xi;var oi=class{constructor(){this.locked=!1;this.listeners=[];this.unlockListeners=[]}lock(){return this.locked=!0,this}unlock(){this.locked=!1;for(let e of this.listeners)e();for(let e of this.unlockListeners)e();return this.listeners=[],this}onUnlock(e){return this.unlockListeners.push(e),e}offUnlock(e){this.unlockListeners=this.unlockListeners.filter(t=>t!==e)}async nextUnlock(){if(this.locked)return new Promise(e=>{this.listeners.push(e)})}isLocked(){return this.locked}},Nn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new oi;return this.locks.push(t),t}off(e){this.locks=this.locks.filter(t=>t!==e)}async nextUnlock(){let e=this.locks.map(t=>t.nextUnlock());return Promise.all(e)}isLocked(){return this.locks.some(e=>e.isLocked())}};function Fn(o,e,t={}){return o?e:t}function ha(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var $i=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function ga(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function ya(o,e){let n=await(await fetch(o,e)).blob();return{url:URL.createObjectURL(n),bytes:n.size}}var Gn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}get size(){return this.tasks.length}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),this.tasks.length!==0&&(await Ji(this.delay),await e())};await e()}};function ct(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function va(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var Xe=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function Sa(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function ba(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function ri(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function Sr(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!Sr(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var ji=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Zi(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function Ta(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var qi=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Qi=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var Yi=class{constructor(e){this.items=[];this.pushValidator=[];e&&(this.items=[...e])}addPushValidator(e){return this.pushValidator.push(e),this}removePushValidator(e){this.pushValidator=this.pushValidator.filter(t=>t!==e)}push(...e){for(let t of e)this.pushValidator.some(n=>!n(t))||this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}toArray(){return[...this.items]}forEach(e){this.items.forEach(e)}forEachReverse(e){for(let t=this.items.length-1;t>=0;t--)e(this.items[t])}map(e){return this.items.map(e)}get(e){return this.items[e]}};function Aa(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function Ca(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,l=16777216,c=r*a>>>0,u=r*l+s*a>>>0,p=s*l+(u>>>0)>>>0;e=c,t=p}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var si=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=vr(),this._id="",this._staticId=null}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}abandon(e){}getId(){return this._id}setId(e){this._id=e}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};si.ActionTypes={action:"action"};var X=class extends si{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new v(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var Te=class Te extends X{static handleSceneInit(e,t,n,i){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,async r=>{await Te.initBackgroundMusic(e,r,n),i.resolve(t),n.logger.debug("Scene Action","Scene init")}),i)}static async initBackgroundMusic(e,t,n){if(n?.isSceneSuspended(e))return;let i=e.state.backgroundMusic;i&&(n?.audioManager.isRunningFromLoad(i)||await t.setBackgroundMusic(i,e.config.backgroundMusicFade))}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new te("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,i=t.findElementByScene(n);i&&t.removeElement(i);let r=t.fromElementSnapshot(e.element);if(t.addElement(r),t.setSceneSuspended(n,e.element.suspended===!0),t.restoreVideosOf(n,e.element.videos),n.local.getNamespace(t.getStorable()).load(e.local),e.state){let[,s]=t.getLiveGame().constructMaps();n.fromData(e.state,s)}e.background&&n.background.fromData(e.background)}applyStageTransition(e,t,n,i){let r=new v().registerSkipController(new B(()=>(e.logger.info("Stage Transition","Skipped"),super.executeAction(e,i)))),s=()=>{r.isSettled()||r.resolve(super.executeAction(e,i))},a=e.stageTransition.apply(t,{from:this.callee,to:n},s),l=e.timelines.attachTimeline(r).attachChild(a);return a.onCancelled(s),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:l},()=>{r.isSettled()||r.abort(),a.abort()}),r}static unloadScene(e,t){t.settlePendingLines(e),t.getStorable().removeNamespace(e.local.getNamespaceName()),t.offSrcManager(e.srcManager).removeScene(e),e.state.backgroundImage.reset()}static unwindCallStack(e){let t=e.getSuspendedScenes(),n=t.map(i=>[i,Te.createSceneSnapshot(i,e)]);return t.forEach(i=>{i.events.emit("event:scene.preUnmount"),Te.unloadScene(i,e)}),n}static rewindCallStack(e,t){e.forEach(([n,i])=>{let r=new v(s=>s);t.timelines.attachTimeline(r),Te.handleSceneInit(n,{type:z.callTo,node:null},t,r),Te.restoreSceneSnapshot(i,t),t.setSceneSuspended(n,!0)})}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}abandon(e){if(this.type!==z.resume)return;let t=this.contentNode.getContent()[0],n=this.callee,i=n.state.backgroundMusic;e.isSceneActive(t)&&(t.events.emit("event:scene.preUnmount"),Te.unloadScene(t,e)),e.setSceneSuspended(n,!1),i&&e.audioManager.isManaged(i)&&e.audioManager.resume(i,n.config.backgroundMusicFade)}applyNvlVisibility(e,t,n,i){e.setNvlVisibility(t,n);let r=Math.max(0,n?.duration||0);if(r===0)return super.executeAction(e,i);let s=super.executeAction(e,i),a=new v(c=>c),l=null;return a.registerSkipController(new B(()=>(l&&(clearTimeout(l),l=null),s))),l=e.setTimeout(()=>{l=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===z.action)return super.executeAction(e,t);if(this.is(Te,"scene:init")){let n=new v(s=>s),i=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{Te.unloadScene(this.callee,e)},[]);let r={type:this.type,node:this.contentNode.getChild()};return Te.handleSceneInit(this.callee,r,e,v.forward(n,r))}else if(this.type===z.exit){let n=Te.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new v(s=>s);e.timelines.attachTimeline(r),Te.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Te.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===z.jumpTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=e.getLiveGame().getStackModelForce().serialize(),s=Te.unwindCallStack(e);e.actionHistory.push({action:this,stackModel:t.stackModel},(l,c)=>{Te.rewindCallStack(c,e);let[u]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(l,u)},[r,s]);let a=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:a}),null}else if(this.type===z.preSuspend){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));if(e.isSceneActive(i))throw new te(`Cannot call scene ${this.getSceneName(n)}: it is already on stage.
|
|
4
|
-
A returnable jump suspends the scene it leaves rather than unloading it, so a scene cannot be called from itself or from anything it has called.`,this);if(e.isSceneSuspended(this.callee))throw this._callerAlreadyParkedError(n);let r=e.getSuspendedScenes().length,s=e.game.config.maxSceneCallDepth;if(r>=s)throw new
|
|
5
|
-
Each returnable jump keeps the scene it left mounted, so a chain of them holds every scene in the chain on the stage at once. Raise maxSceneCallDepth if the story really needs to go this deep.`,this);let a=this.callee.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{a&&e.audioManager.isManaged(a)&&e.audioManager.resume(a,0)},[]),a&&e.audioManager.isManaged(a)&&e.audioManager.pause(a,this.callee.config.backgroundMusicFade),super.executeAction(e,t)}else if(this.type===
|
|
6
|
-
Make sure you have registered the scene using story.register`,this)}_callerAlreadyParkedError(e){let t=this.getSceneName(this.callee);return new
|
|
7
|
-
A returnable jump suspends the scene it is taken from, and a scene has one place on the stage, so two calls cannot be open from the same scene at the same time. Take the calls one after the other in a single branch rather than one per branch of a concurrent group.`,this)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===z.callTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`callTo {${i.stringify(e,t,n)}}`)}if(this.type===z.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};Te.ActionTypes=z;var oe=Te;var br=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},A=class o extends br{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var eo={center:"center",left:"left",right:"right"};import{animate as wa}from"motion/react";var Vn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(Vn||{}),xa={left:"33.33%",center:"50%",right:"66.66%"},gt=class gt{static isUnknown(e){return e===gt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},l=t?{right:s}:{left:s};return this.wrap({...a,...l})}static calc(e,t,n){if(e==null||e===""||gt.isUnknown(e))return"auto";let i=!(t===void 0||gt.isUnknown(t));if(typeof n=="number"&&n>0){let s=gt.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}let r=typeof e=="number"?`${e}px`:e;return i?`calc(${r} + ${t}px)`:`calc(${r} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(ut.isCommonPositionType(e))return yt.fromCommonPosition(e);if(yt.isCoord2DPosition(e))return e;if(Cn.isAlignPosition(e))return yt.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return gt.isUnknown(e)||e===void 0?gt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return yt.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:gt.isUnknown(t.x)?0:t.x,y:gt.isUnknown(t.y)?0:t.y,xoffset:gt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:gt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(Vn).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof ut||e instanceof yt||e instanceof Cn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return yt.fromCommonPosition(new ut(e));if(this.isRawAlignPosition(e))return yt.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new yt(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};gt.Unknown=Symbol("Unknown");var V=gt,to=class to{static isCommonPositionType(e){return e instanceof to}constructor(e){this.position=e}toCSS(){return{x:xa[this.position],y:"50%",xoffset:0,yoffset:0}}};to.Positions=Vn;var ut=to,yt=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:xa[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>typeof n!="number"||!Number.isFinite(n)?V.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:V.isUnknown(t.x)?e.x:t.x,y:V.isUnknown(t.y)?e.y:t.y,xoffset:V.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:V.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=V.orUnknown(e.x),this.y=V.orUnknown(e.y),this.xoffset=V.orUnknown(e.xoffset),this.yoffset=V.orUnknown(e.yoffset)):(this.x=V.orUnknown(e),this.y=V.orUnknown(t),this.xoffset=V.Unknown,this.yoffset=V.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},Cn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=V.orUnknown(e.xalign),this.yalign=V.orUnknown(e.yalign),this.xoffset=V.orUnknown(e.xoffset),this.yoffset=V.orUnknown(e.yoffset)):(this.xalign=V.orUnknown(e),this.yalign=V.orUnknown(t),this.xoffset=V.Unknown,this.yoffset=V.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:V.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:V.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var $=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Tr(this.mergeWithDefaultConfig(e))}copy(){return new o(Q({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?Q({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},Tr=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(Q({},this.config))}join(e){let t=va(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var uu={[eo.left]:"25.33%",[eo.center]:"50%",[eo.right]:"75.66%"},Lt=class Lt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Lt(Lt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?V.toCoord2D(V.tryParsePosition(e||t)):V.mergePosition(V.tryParsePosition(e),V.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Lt.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return ri(ne.constructStyle(e,this.state,t))}toStyle(e,t){return ri(ne.constructStyle(e,this.state,t))}serialize(){return Lt.TransformStateSerializer.serialize(this.state)}clone(){return new Lt(Lt.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Lt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}resetTo(e){return this.state=e,this.locked=null,this.frozen=!1,this}};Lt.DefaultTransformState=new $({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new ut("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),Lt.TransformStateSerializer=new Xe({position:e=>V.serializePosition(V.tryParsePosition(e))},{position:e=>V.toCoord2D(e)});var re=Lt,Ie=class Ie{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Ie.defaultConfig,t||{});else{let[n,i]=[e,t||Ie.defaultOptions];this.sequences.push({props:n,options:i||Ie.defaultOptions}),this.config=Object.assign({},Ie.defaultConfig)}}static isPosition(e){return ut.isCommonPositionType(e)||yt.isCoord2DPosition(e)||Cn.isAlignPosition(e)}static immediate(e){return new Ie(e,{duration:0,ease:"linear"})}static left(e,t){return new Ie({position:ut.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Ie({position:ut.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Ie({position:ut.Positions.Center},{duration:e,ease:t})}static create(e){return new Ie([],e)}static positionToCSS(e,t,n,i){return e?V.isRawPosition(e)?V.D2PositionToCSS(V.rawPositionToCoord2D(e),n,t,i):V.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?V.toCoord2D(V.tryParsePosition(e||t)):V.mergePosition(V.tryParsePosition(e),V.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...Q(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,l=function(d,f,h){return typeof d>"u"?typeof h<"u"?f(h):"":f(d)},c=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${c}, ${u})`,l(t.rotation,d=>`rotate(${d}deg)`,0),l(t.scaleX,d=>`scaleX(${d*a})`,1),l(t.scaleY,d=>`scaleY(${d*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,l=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...Ie.positionToCSS(t.position,i,r,l),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?On(t.fontColor):void 0,transform:Ie.propToCSSTransform(e,t),...Ie.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:l}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:g})=>({el:m.current,project:g}))});if(a.length||t.logger.warn("Transform","No sequences to animate."),l.repeat!==void 0&&!Number.isFinite(l.repeat))throw new te("A transform applied with `transform()` (or `show`, `hide`, `pos`, ...) has to end, but this one repeats forever.\nUse `element.loop(transform)` for a motion that runs until it is stopped - the line does not wait for it, and `element.stopLoop()` ends it.");let c=!1,u=e.lock(),p=wa(a,l),d=()=>{e.overwrite(u,s.get()).unlock(u),p.complete(),c=!0},f=new v().registerSkipController(new B(d)),h=()=>{c||e.overwrite(u,s.get()).unlock(u),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),f.resolve()};return p.then(h,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{h()}catch{f.resolve()}})),p.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:s,sequences:a,options:l},this),f}startLoop(e,{gameState:t,ref:n,overwrites:i,companionRefs:r},s){if(!n.current)throw new Error("No ref found when looping.");this.commit();let{sequences:a,options:l}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(p=>!!p.ref.current).map(({ref:p,project:d})=>({el:p.current,project:d}))});a.length||t.logger.warn("Transform","No sequences to loop.");let c=[n.current,ri(e.toFramesDefinition(t,i)),{duration:0}],u=wa([c,...a],{...l,repeat:1/0,repeatType:s?.repeatType??l.repeatType??"loop",repeatDelay:s?.repeatDelay!==void 0?this.toSeconds(s.repeatDelay,void 0):l.repeatDelay});return u.play(),t.logger.debug("Transform","Loop started.",{sequences:a,options:l},this),{stop:()=>{u.stop()}}}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Ie.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i,companions:r}){let s=t.clone(),a=s.lock(),l=this.sequences.flatMap(({props:c,options:u})=>{let p=s.assign(a,c),d=p.toFramesDefinition(e,n),f=this.getOptions(u),h=[i,d,f];if(!r||!r.length)return[h];let m=p.get();return[h,...r.map(({el:g,project:b})=>[g,ri(b(m)),{...f,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:l,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t,repeatType:n}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0),repeatType:n}}copy(){return new Ie(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}lens(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new te("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new te("Invalid number in at definition.");let l=a/1e3;return r==="+"?`+${l}`:`-${l}`}};Ie.defaultConfig={sync:!0},Ie.defaultOptions={duration:0,ease:"linear"},Ie.CommonImagePositionMap=uu;var ne=Ie;var no=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var ka=Symbol("_Chained"),Pa;Pa=ka;var Ar=class Ar{constructor(e){this[Pa]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[ka]}static toActions(e){return e.flat(2).map(t=>Ar.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},Ke=Ar,Hn=class extends no{chain(e){let t=Ke.isChained(this)?this:this.proxy(this,new Ke(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var me=class extends Hn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Ht=class extends X{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",l=s.action?s.action.map(c=>c.stringify(e,t,n)).join(";"):"null";return`(${a}) {${l}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Ht.ActionTypes=ua;var ai=64;function Da(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function Cr(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function io(o,e=0,t=new Set){if(e>ai)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>io(n,e+1,t)):Da(o)?Object.values(o).every(n=>io(n,e+1,t)):!1}finally{t.delete(o)}}function La(o,e){let t=[],n=[];return{data:xr(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function xr(o,e,t,n,i,r,s){if(t>ai)throw new P(`A stored value nests deeper than ${ai} levels and cannot be saved
|
|
3
|
+
`).trim():""}function eo(o){return new Promise(e=>setTimeout(e,o))}var Zi=class Zi{constructor(e){this.abortHandler=e;this.events=new ee;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Zi.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Zi.EventTypes={"event:skipController.abort":"event:skipController.abort"};var B=Zi;var ri=class{constructor(){this.locked=!1;this.listeners=[];this.unlockListeners=[]}lock(){return this.locked=!0,this}unlock(){this.locked=!1;for(let e of this.listeners)e();for(let e of this.unlockListeners)e();return this.listeners=[],this}onUnlock(e){return this.unlockListeners.push(e),e}offUnlock(e){this.unlockListeners=this.unlockListeners.filter(t=>t!==e)}async nextUnlock(){if(this.locked)return new Promise(e=>{this.listeners.push(e)})}isLocked(){return this.locked}},Nn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new ri;return this.locks.push(t),t}off(e){this.locks=this.locks.filter(t=>t!==e)}async nextUnlock(){let e=this.locks.map(t=>t.nextUnlock());return Promise.all(e)}isLocked(){return this.locks.some(e=>e.isLocked())}};function Vn(o,e,t={}){return o?e:t}function ga(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var qi=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function ya(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function va(o,e){let n=await(await fetch(o,e)).blob();return{url:URL.createObjectURL(n),bytes:n.size}}var Gn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}get size(){return this.tasks.length}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),this.tasks.length!==0&&(await eo(this.delay),await e())};await e()}};function ct(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Sa(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var Xe=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function ba(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function Ta(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function si(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function br(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!br(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Qi=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function to(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function Aa(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Yi=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Xi=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var Ji=class{constructor(e){this.items=[];this.pushValidator=[];e&&(this.items=[...e])}addPushValidator(e){return this.pushValidator.push(e),this}removePushValidator(e){this.pushValidator=this.pushValidator.filter(t=>t!==e)}push(...e){for(let t of e)this.pushValidator.some(n=>!n(t))||this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}toArray(){return[...this.items]}forEach(e){this.items.forEach(e)}forEachReverse(e){for(let t=this.items.length-1;t>=0;t--)e(this.items[t])}map(e){return this.items.map(e)}get(e){return this.items[e]}};function xa(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function Ca(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,l=16777216,c=r*a>>>0,u=r*l+s*a>>>0,p=s*l+(u>>>0)>>>0;e=c,t=p}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var ai=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Sr(),this._id="",this._staticId=null}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}abandon(e){}getId(){return this._id}setId(e){this._id=e}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};ai.ActionTypes={action:"action"};var J=class extends ai{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new v(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var Te=class Te extends J{static handleSceneInit(e,t,n,i){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,async r=>{await Te.initBackgroundMusic(e,r,n),i.resolve(t),n.logger.debug("Scene Action","Scene init")}),i)}static async initBackgroundMusic(e,t,n){if(n?.isSceneSuspended(e))return;let i=e.state.backgroundMusic;i&&(n?.audioManager.isRunningFromLoad(i)||await t.setBackgroundMusic(i,e.config.backgroundMusicFade))}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new ne("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,i=t.findElementByScene(n);i&&t.removeElement(i);let r=t.fromElementSnapshot(e.element);if(t.addElement(r),t.setSceneSuspended(n,e.element.suspended===!0),t.restoreVideosOf(n,e.element.videos),t.restoreVfxOf(n,e.element.vfx),n.local.getNamespace(t.getStorable()).load(e.local),e.state){let[,s]=t.getLiveGame().constructMaps();n.fromData(e.state,s)}e.background&&n.background.fromData(e.background)}applyStageTransition(e,t,n,i){let r=new v().registerSkipController(new B(()=>(e.logger.info("Stage Transition","Skipped"),super.executeAction(e,i)))),s=()=>{r.isSettled()||r.resolve(super.executeAction(e,i))},a=e.stageTransition.apply(t,{from:this.callee,to:n},s),l=e.timelines.attachTimeline(r).attachChild(a);return a.onCancelled(s),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:l},()=>{r.isSettled()||r.abort(),a.abort()}),r}static unloadScene(e,t){t.settlePendingLines(e),t.getStorable().removeNamespace(e.local.getNamespaceName()),t.offSrcManager(e.srcManager).removeScene(e),e.state.backgroundImage.reset()}static unwindCallStack(e){let t=e.getSuspendedScenes(),n=t.map(i=>[i,Te.createSceneSnapshot(i,e)]);return t.forEach(i=>{i.events.emit("event:scene.preUnmount"),Te.unloadScene(i,e)}),n}static rewindCallStack(e,t){e.forEach(([n,i])=>{let r=new v(s=>s);t.timelines.attachTimeline(r),Te.handleSceneInit(n,{type:W.callTo,node:null},t,r),Te.restoreSceneSnapshot(i,t),t.setSceneSuspended(n,!0)})}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}abandon(e){if(this.type!==W.resume)return;let t=this.contentNode.getContent()[0],n=this.callee,i=n.state.backgroundMusic;e.isSceneActive(t)&&(t.events.emit("event:scene.preUnmount"),Te.unloadScene(t,e)),e.setSceneSuspended(n,!1),i&&e.audioManager.isManaged(i)&&e.audioManager.resume(i,n.config.backgroundMusicFade)}applyNvlVisibility(e,t,n,i){e.setNvlVisibility(t,n);let r=Math.max(0,n?.duration||0);if(r===0)return super.executeAction(e,i);let s=super.executeAction(e,i),a=new v(c=>c),l=null;return a.registerSkipController(new B(()=>(l&&(clearTimeout(l),l=null),s))),l=e.setTimeout(()=>{l=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===W.action)return super.executeAction(e,t);if(this.is(Te,"scene:init")){let n=new v(s=>s),i=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{Te.unloadScene(this.callee,e)},[]);let r={type:this.type,node:this.contentNode.getChild()};return Te.handleSceneInit(this.callee,r,e,v.forward(n,r))}else if(this.type===W.exit){let n=Te.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new v(s=>s);e.timelines.attachTimeline(r),Te.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Te.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===W.jumpTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=e.getLiveGame().getStackModelForce().serialize(),s=Te.unwindCallStack(e);e.actionHistory.push({action:this,stackModel:t.stackModel},(l,c)=>{Te.rewindCallStack(c,e);let[u]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(l,u)},[r,s]);let a=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:a}),null}else if(this.type===W.preSuspend){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));if(e.isSceneActive(i))throw new ne(`Cannot call scene ${this.getSceneName(n)}: it is already on stage.
|
|
4
|
+
A returnable jump suspends the scene it leaves rather than unloading it, so a scene cannot be called from itself or from anything it has called.`,this);if(e.isSceneSuspended(this.callee))throw this._callerAlreadyParkedError(n);let r=e.getSuspendedScenes().length,s=e.game.config.maxSceneCallDepth;if(r>=s)throw new ne(`Scene call depth limit reached (${s}).
|
|
5
|
+
Each returnable jump keeps the scene it left mounted, so a chain of them holds every scene in the chain on the stage at once. Raise maxSceneCallDepth if the story really needs to go this deep.`,this);let a=this.callee.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{a&&e.audioManager.isManaged(a)&&e.audioManager.resume(a,0)},[]),a&&e.audioManager.isManaged(a)&&e.audioManager.pause(a,this.callee.config.backgroundMusicFade),super.executeAction(e,t)}else if(this.type===W.callTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=this.contentNode.getChild();if(!r?.action)throw new ke("A scene call has no return address. `scene:callTo` is only ever built with a `scene:resume` chained behind it (see Scene._callScene).");let s=this.callee;if(e.isSceneSuspended(s))throw this._callerAlreadyParkedError(n);let a=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{e.setSceneSuspended(s,!1);let[u]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(c,u)},[a]),e.setSceneSuspended(s,!0);let l=i.getSceneRoot().contentNode;return[{type:this.type,node:r},{type:this.type,node:l}]}else if(this.type===W.resume){let n=this.contentNode.getContent()[0],i=this.callee,r=i.state.backgroundMusic,s=Te.createSceneSnapshot(n,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let l=new v(c=>c);e.timelines.attachTimeline(l),Te.handleSceneInit(n,{type:this.type,node:this.contentNode.getChild()},e,l),Te.restoreSceneSnapshot(a,e),e.setSceneSuspended(i,!0),r&&e.audioManager.isManaged(r)&&e.audioManager.pause(r,0)},[s]),n.events.emit("event:scene.preUnmount"),Te.unloadScene(n,e),e.setSceneSuspended(i,!1),r&&e.audioManager.isManaged(r)&&e.audioManager.resume(r,i.config.backgroundMusicFade),super.executeAction(e,t)}else if(this.type===W.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{s.setBackgroundMusic(l,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===W.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===W.transitionToScene){let[n,i]=this.contentNode.getContent();return this.applyStageTransition(e,n,i,t)}else if(this.type===W.nvlBlock){let[n,i]=this.contentNode.getContent(),r=e.createNvlSnapshot();return e.enterNvlMode(i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{e.restoreNvlSnapshot(s)},[r]),n.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]}else if(this.type===W.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=v.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===W.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=v.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===W.nvlEnd){let[n]=this.contentNode.getContent(),i=e.createNvlSnapshot();return e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{e.restoreNvlSnapshot(r)},[i]),e.exitNvlMode(n||null),{type:this.type,node:null}}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===W.callTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=r.getSceneRoot()?.contentNode,a=this.contentNode.getChild()?.action;return[...s?.action?[s.action]:[],...a?[a]:[]]}if(this.type===W.jumpTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=e.getScene(i,!0).getSceneRoot()?.contentNode;return s?.action?[s.action]:[]}if(this.type===W.nvlBlock){let[i]=this.contentNode.getContent(),r=super.getFutureActions(e,t);return[...i??[],...r]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new ne(`Scene with name ${e} not found
|
|
6
|
+
Make sure you have registered the scene using story.register`,this)}_callerAlreadyParkedError(e){let t=this.getSceneName(this.callee);return new ne(`Cannot call scene ${this.getSceneName(e)} from ${t}: ${t} is already parked behind another call.
|
|
7
|
+
A returnable jump suspends the scene it is taken from, and a scene has one place on the stage, so two calls cannot be open from the same scene at the same time. Take the calls one after the other in a single branch rather than one per branch of a concurrent group.`,this)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===W.callTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`callTo {${i.stringify(e,t,n)}}`)}if(this.type===W.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};Te.ActionTypes=W;var re=Te;var Tr=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},x=class o extends Tr{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var no={center:"center",left:"left",right:"right"};import{animate as ka}from"motion/react";var Fn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(Fn||{}),wa={left:"33.33%",center:"50%",right:"66.66%"},gt=class gt{static isUnknown(e){return e===gt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},l=t?{right:s}:{left:s};return this.wrap({...a,...l})}static calc(e,t,n){if(e==null||e===""||gt.isUnknown(e))return"auto";let i=!(t===void 0||gt.isUnknown(t));if(typeof n=="number"&&n>0){let s=gt.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}let r=typeof e=="number"?`${e}px`:e;return i?`calc(${r} + ${t}px)`:`calc(${r} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(ut.isCommonPositionType(e))return yt.fromCommonPosition(e);if(yt.isCoord2DPosition(e))return e;if(xn.isAlignPosition(e))return yt.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return gt.isUnknown(e)||e===void 0?gt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return yt.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:gt.isUnknown(t.x)?0:t.x,y:gt.isUnknown(t.y)?0:t.y,xoffset:gt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:gt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(Fn).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof ut||e instanceof yt||e instanceof xn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return yt.fromCommonPosition(new ut(e));if(this.isRawAlignPosition(e))return yt.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new yt(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};gt.Unknown=Symbol("Unknown");var V=gt,io=class io{static isCommonPositionType(e){return e instanceof io}constructor(e){this.position=e}toCSS(){return{x:wa[this.position],y:"50%",xoffset:0,yoffset:0}}};io.Positions=Fn;var ut=io,yt=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:wa[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>typeof n!="number"||!Number.isFinite(n)?V.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:V.isUnknown(t.x)?e.x:t.x,y:V.isUnknown(t.y)?e.y:t.y,xoffset:V.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:V.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=V.orUnknown(e.x),this.y=V.orUnknown(e.y),this.xoffset=V.orUnknown(e.xoffset),this.yoffset=V.orUnknown(e.yoffset)):(this.x=V.orUnknown(e),this.y=V.orUnknown(t),this.xoffset=V.Unknown,this.yoffset=V.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},xn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=V.orUnknown(e.xalign),this.yalign=V.orUnknown(e.yalign),this.xoffset=V.orUnknown(e.xoffset),this.yoffset=V.orUnknown(e.yoffset)):(this.xalign=V.orUnknown(e),this.yalign=V.orUnknown(t),this.xoffset=V.Unknown,this.yoffset=V.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:V.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:V.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var $=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Ar(this.mergeWithDefaultConfig(e))}copy(){return new o(Q({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?Q({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},Ar=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(Q({},this.config))}join(e){let t=Sa(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var yu={[no.left]:"25.33%",[no.center]:"50%",[no.right]:"75.66%"},Lt=class Lt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Lt(Lt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?V.toCoord2D(V.tryParsePosition(e||t)):V.mergePosition(V.tryParsePosition(e),V.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Lt.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return si(ie.constructStyle(e,this.state,t))}toStyle(e,t){return si(ie.constructStyle(e,this.state,t))}serialize(){return Lt.TransformStateSerializer.serialize(this.state)}clone(){return new Lt(Lt.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Lt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}resetTo(e){return this.state=e,this.locked=null,this.frozen=!1,this}};Lt.DefaultTransformState=new $({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new ut("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),Lt.TransformStateSerializer=new Xe({position:e=>V.serializePosition(V.tryParsePosition(e))},{position:e=>V.toCoord2D(e)});var se=Lt,Ie=class Ie{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Ie.defaultConfig,t||{});else{let[n,i]=[e,t||Ie.defaultOptions];this.sequences.push({props:n,options:i||Ie.defaultOptions}),this.config=Object.assign({},Ie.defaultConfig)}}static isPosition(e){return ut.isCommonPositionType(e)||yt.isCoord2DPosition(e)||xn.isAlignPosition(e)}static immediate(e){return new Ie(e,{duration:0,ease:"linear"})}static left(e,t){return new Ie({position:ut.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Ie({position:ut.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Ie({position:ut.Positions.Center},{duration:e,ease:t})}static create(e){return new Ie([],e)}static positionToCSS(e,t,n,i){return e?V.isRawPosition(e)?V.D2PositionToCSS(V.rawPositionToCoord2D(e),n,t,i):V.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?V.toCoord2D(V.tryParsePosition(e||t)):V.mergePosition(V.tryParsePosition(e),V.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...Q(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,l=function(d,f,h){return typeof d>"u"?typeof h<"u"?f(h):"":f(d)},c=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${c}, ${u})`,l(t.rotation,d=>`rotate(${d}deg)`,0),l(t.scaleX,d=>`scaleX(${d*a})`,1),l(t.scaleY,d=>`scaleY(${d*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,l=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...Ie.positionToCSS(t.position,i,r,l),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?On(t.fontColor):void 0,transform:Ie.propToCSSTransform(e,t),...Ie.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:l}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:g})=>({el:m.current,project:g}))});if(a.length||t.logger.warn("Transform","No sequences to animate."),l.repeat!==void 0&&!Number.isFinite(l.repeat))throw new ne("A transform applied with `transform()` (or `show`, `hide`, `pos`, ...) has to end, but this one repeats forever.\nUse `element.loop(transform)` for a motion that runs until it is stopped - the line does not wait for it, and `element.stopLoop()` ends it.");let c=!1,u=e.lock(),p=ka(a,l),d=()=>{e.overwrite(u,s.get()).unlock(u),p.complete(),c=!0},f=new v().registerSkipController(new B(d)),h=()=>{c||e.overwrite(u,s.get()).unlock(u),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),f.resolve()};return p.then(h,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{h()}catch{f.resolve()}})),p.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:s,sequences:a,options:l},this),f}startLoop(e,{gameState:t,ref:n,overwrites:i,companionRefs:r},s){if(!n.current)throw new Error("No ref found when looping.");this.commit();let{sequences:a,options:l}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(p=>!!p.ref.current).map(({ref:p,project:d})=>({el:p.current,project:d}))});a.length||t.logger.warn("Transform","No sequences to loop.");let c=[n.current,si(e.toFramesDefinition(t,i)),{duration:0}],u=ka([c,...a],{...l,repeat:1/0,repeatType:s?.repeatType??l.repeatType??"loop",repeatDelay:s?.repeatDelay!==void 0?this.toSeconds(s.repeatDelay,void 0):l.repeatDelay});return u.play(),t.logger.debug("Transform","Loop started.",{sequences:a,options:l},this),{stop:()=>{u.stop()}}}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Ie.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i,companions:r}){let s=t.clone(),a=s.lock(),l=this.sequences.flatMap(({props:c,options:u})=>{let p=s.assign(a,c),d=p.toFramesDefinition(e,n),f=this.getOptions(u),h=[i,d,f];if(!r||!r.length)return[h];let m=p.get();return[h,...r.map(({el:g,project:b})=>[g,si(b(m)),{...f,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:l,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t,repeatType:n}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0),repeatType:n}}copy(){return new Ie(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}lens(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new ne("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new ne("Invalid number in at definition.");let l=a/1e3;return r==="+"?`+${l}`:`-${l}`}};Ie.defaultConfig={sync:!0},Ie.defaultOptions={duration:0,ease:"linear"},Ie.CommonImagePositionMap=yu;var ie=Ie;var oo=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var Pa=Symbol("_Chained"),Ea;Ea=Pa;var xr=class xr{constructor(e){this[Ea]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Pa]}static toActions(e){return e.flat(2).map(t=>xr.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},Ke=xr,Hn=class extends oo{chain(e){let t=Ke.isChained(this)?this:this.proxy(this,new Ke(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var fe=class extends Hn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Ht=class extends J{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",l=s.action?s.action.map(c=>c.stringify(e,t,n)).join(";"):"null";return`(${a}) {${l}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Ht.ActionTypes=pa;var li=64;function La(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function Cr(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function ro(o,e=0,t=new Set){if(e>li)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>ro(n,e+1,t)):La(o)?Object.values(o).every(n=>ro(n,e+1,t)):!1}finally{t.delete(o)}}function Ra(o,e){let t=[],n=[];return{data:wr(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function wr(o,e,t,n,i,r,s){if(t>li)throw new P(`A stored value nests deeper than ${li} levels and cannot be saved
|
|
8
8
|
at ${s}, ${Cr(e)}
|
|
9
9
|
A saved game this deep is almost always a data-structure bug. Flatten the value,
|
|
10
10
|
or keep the deep part outside the store and save an id for it.`);if(o===void 0)return r.push([...e]),null;if(o===null)return null;if(o instanceof Date)return i.push([...e]),o.toISOString();if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="object"){if(n.has(o))throw new P(`A stored value refers back to itself and cannot be saved
|
|
11
11
|
at ${s}, ${Cr(e)}
|
|
12
12
|
A saved game is a tree. Cutting the back-edge would save a different object graph
|
|
13
13
|
than the one you built, so this is refused rather than guessed at \u2014 break the
|
|
14
|
-
reference, or store an id in place of the object.`);if(Array.isArray(o)||
|
|
15
|
-
at ${s}, ${Cr(e)}`),null}function
|
|
16
|
-
at namespace "${this.name}"`),this.content[e]=t,this.reportChange(e,n,t),this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){let e=this.content;return this.content=Q({},this.defaultContent),new Set([...Object.keys(e),...Object.keys(this.content)]).forEach(n=>{this.reportChange(n,e[n],this.content[n])}),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content={},this.deserialize(e)}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n,t)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)}),this.owner?.reportRestore(this.key)}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e,t){let n=`namespace "${this.name}"`+(t===void 0?"":`, key "${t}"`),i={any:s=>{let a=
|
|
17
|
-
at namespace "${this.name}"`),e?.data)}attach(e){return this.owner=e,this}detach(e){return this.owner===e&&(this.owner=null),this}reportChange(e,t,n){!this.owner||
|
|
18
|
-
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new P("No listener provided when subscribing to storable changes");return this.events.on(un.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(un.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new Ut(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(un.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(un.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(un.EventTypes["event:storable.restore"],{namespaces:[e]})}};un.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var li=un;var ch={};var Un=class extends Hn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let l=a.getFutureActions(e,i).filter(c=>!r.has(c));s.push(...l)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var it=class extends X{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Vt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Vt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Vt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=v.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,l=>{l&&this.callee.fromData(l)},[s]),a}else if(this.type===Vt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Vt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Vt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Vt.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=v.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===Vt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};it.ActionTypes=Vt;var ot={bgm:"bgm",sound:"sound",voice:"voice"},oo=8,pn=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Bn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var ui=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=l=>{t.set(l.id,{id:l.id,parentId:l.parentId??null,volume:Bn(l.volume)})};Object.values(ot).forEach(l=>n({id:l}));let i=new Set;e.forEach(l=>{let c=l?.id;if(typeof c!="string"||c.trim().length===0)throw new pn(`Audio bus id must be a non-empty string, got ${JSON.stringify(c)}.`);if(i.has(c))throw new pn(`Audio bus "${c}" is declared more than once.`);i.add(c),n(l)}),o.assertResolvable(t);let r=[],s=new Map,a=l=>{let c=s.get(l);if(c)return c;let u=t.get(l),p=u.parentId===null?null:a(u.parentId),d={id:u.id,parentId:u.parentId,volume:u.volume,depth:p?p.depth+1:1};return s.set(l,d),r.push(d),d};return t.forEach(l=>a(l.id)),new o(r,s)}static isSeeded(e){return Object.values(ot).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new pn(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new pn(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>oo)throw new pn(`Audio bus "${t.id}" nests deeper than ${oo}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=oo;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},Pr=ui.resolve();function du(o){Pr=o}function Er(){return Pr}function ro(o,e){let t=Pr;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var Ma={[ot.bgm]:"bgmVolume",[ot.sound]:"soundVolume",[ot.voice]:"voiceVolume"};function Na(o){let e={};return Object.entries(Ma).forEach(([t,n])=>{e[t]={get:()=>Bn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var ci=class ci{constructor(e,t={}){this.declarations=e;this.events=new Z;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,Bn(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(ci.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=ui.resolve(this.declarations()??[]),du(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Bn(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?Bn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Bn(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(ci.EventTypes["event:audioBus.volumeChange"],e)}};ci.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var pi=ci;var Ga=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Ga||{}),Pe=class Pe extends me{static toSound(e){return e==null?null:typeof e=="string"?new Pe({src:e}):e}static isSound(e){return e instanceof Pe}static voice(e){let t=typeof e=="string"?{src:e}:e;return new Pe({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new Pe({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new Pe({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=Pe.DefaultUserConfig.create(t),[i]=n.extract(Pe.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e,t){return Er().isUnder(this.config.type,ot.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(it.ActionTypes.play,[{end:this.state.volume,duration:e||0,waitForEnd:t?.waitForEnd===!0}])}stop(e){return this.pushAction(it.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(it.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(it.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(it.ActionTypes.setRate,[e])}pause(e){return this.pushAction(it.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(it.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(it.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:Pe.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Pe.StateSerializer.deserialize(e.state),this}copy(){return new Pe(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Pe.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new it(this.chain(),e,new A().setContent(t)))}};Pe.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Pe.DefaultUserConfig=new $({src:Pe.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Pe.DefaultConfig=new $({src:Pe.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Pe.DefaultState=new $({volume:1,rate:1,paused:!1,muted:!1}),Pe.StateSerializer=new Xe;var Se=Pe;var xn=class xn{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===xn.SrcTypes.image?t.add(s):r===xn.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof O?O.getSrcURL(e):e.type==="image"?O.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(oe,z.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(k.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof Ae){let n=t;if(t.is(Ae,ht.setSrc)){let i=t.contentNode.getContent()[0];if(k.isImageSrc(i))return{type:"image",src:k.srcToURL(i),activeType:"scene"}}else{if(t.type===ht.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===ht.setAppearance){let i=t.contentNode.getContent()[0];if(O.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(O.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:O.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof Se){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof O||k.isStaticImageData(e)){if(e instanceof O){if(!k.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(O.getSrcURL(e)))return this}else if(this.isSrcRegistered(k.srcToURL(e.src)))return this;this.src.push({type:"image",src:k.isStaticImageData(e)?k.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof Se?t:new Se({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof Se?e.getSrc():e;return this.src.some(n=>n.type===xn.SrcTypes.audio?t===n.src.getSrc():n.type===xn.SrcTypes.image?t===O.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};xn.SrcTypes={image:"image",video:"video",audio:"audio"};var Me=xn;import*as Ja from"howler";var $e=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var pt=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};function Oa(o,e){let{render:t,data:n,...i}=e,r=Q(o,i);return"render"in e?r.render=e.render:"render"in o&&(r.render=o.render),"data"in e?r.data=e.data:"data"in o&&(r.data=o.data),r}var Ce=class Ce{static isWord(e){return e instanceof Ce}static color(e,t){return Ce.isWord(e)?e.copy().assign({color:t}):new Ce(e,{color:t})}static bold(e){return Ce.isWord(e)?e.copy().assign({bold:!0}):new Ce(e,{bold:!0})}static italic(e){return Ce.isWord(e)?e.copy().assign({italic:!0}):new Ce(e,{italic:!0})}static emphasis(e,t={}){return Ce.isWord(e)?e.copy().assign({emphasis:t}):new Ce(e,{emphasis:t})}static custom(e,t,n={}){let i={...n,render:t};return Ce.isWord(e)?e.copy().assign(i):new Ce(e,i)}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=Oa(Ce.defaultConfig,t)}evaluate(e){if($e.isPause(this.text))return[this];if(pt.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Ce.isWord(n)?n.inherit(this.config).evaluate(e):new Ce(n,this.config)).flat():Ce.isWord(t)?t.inherit(this.config).evaluate(e):[new Ce(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this.config.emphasis=this.config.emphasis??e.emphasis,this.config.fontScale=this.config.fontScale??e.fontScale,this}assign(e){return this.config=Oa(this.config,e),this}copy(){return new Ce(this.text,this.config)}isPause(){return $e.isPause(this.text)}isTextEvent(){return pt.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Ce.defaultConfig={},Ce.defaultColor="#000";var se=Ce;var dt=class dt{static isSentence(e){return e instanceof dt}static toSentence(e){return dt.isSentence(e)?e:new dt(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return se.isWord(e)?e:new se(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[se.isWord(e)?e:new se(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(dt.isSingleWord):dt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||se.isWord(e)||$e.isPause(e)||pt.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=dt.format(e),this.config=Q(dt.defaultConfig,{...t,voice:typeof t.voice=="string"?Se.voice(t.voice):Se.toSound(t.voice)}),this.state=fa(dt.defaultState)}toData(){return null}fromData(e){return this.state=Q(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...dt.formatStaticWord(i))}return t}copy(){return new dt([...this.text],this.config)}};dt.defaultConfig={voice:null,character:null,voiceId:null},dt.defaultState={};var ve=dt;var so=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 dn=class extends X{executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};dn.ActionTypes=pa;var Ee=class o extends me{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new dn(t,dn.ActionTypes.action,new A().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new dn(this.chain(),dn.ActionTypes.action,new A().setContent(e))]}};var mu={volume:1,limit:1/0},fu=class Va{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={...mu,...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 Va(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}}},Ha=!1;function hu(o){Ha=o}function en(o,e){Ha||(e!==void 0?console.warn(o,e):console.warn(o))}var gu=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.onSourceEnded=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){en("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){en("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=()=>{this.onSourceEnded?this.onSourceEnded():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)}setSourceEndedHandler(o){this.onSourceEnded=o}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){en("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){if(this.currentSource instanceof AudioBufferSourceNode)this.currentSource.start(o,e);else if(this.currentSource instanceof HTMLAudioElement){e>0&&(this.currentSource.currentTime=e);let t=this.currentSource.play();t&&typeof t.catch=="function"&&t.catch(n=>{en("Failed to start HTMLAudioElement playback.",n)})}}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},Fa=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}},yu=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 gu(o,this.gainNode),this.sourceController.setSourceEndedHandler(()=>this.emit("ended")),this.sourceController.setSource(e),this.applyRate(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,this._isPaused=!1;try{this.gainNode.disconnect()}catch(e){en("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){en("Failed to disconnect gain node on stop().",o)}}setRate(o){return o=Math.max(.001,o),this.rate=o,this.applyRate(this.sourceController.getSource()),this}applyRate(o){o instanceof HTMLAudioElement?o.playbackRate=this.rate:o instanceof AudioBufferSourceNode&&(o.playbackRate.value=this.rate)}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 Fa(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new Fa(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}},vu=class{constructor(o,e,t){this.owner=e,this.releaseDelay=t,this.references=0,this.playing=0,this.dropWhenIdle=!1,this.releaseTimer=null,this.audioBuffer=o}retain(){return this.references++,this.dropWhenIdle=!1,this.cancelPendingRelease(),this}release(){this.references>0&&this.references--,this.reconsider()}addRef(){this.playing++,this.cancelPendingRelease()}releaseRef(){this.playing>0&&this.playing--,this.reconsider()}getReferenceCount(){return this.references}getPlayingCount(){return this.playing}getRefCount(){return this.playing}async unload(){this.references=0,this.dropWhenIdle=!0,this.reconsider()}async forceUnload(){this.drop()}isAlive(){return this.audioBuffer!==null}raw(){if(!this.audioBuffer)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}byteLength(){return this.audioBuffer?this.audioBuffer.length*this.audioBuffer.numberOfChannels*4:0}isIdle(){return this.audioBuffer!==null&&this.references===0&&this.playing===0}reconsider(){if(this.isIdle()){if(this.releaseDelay>0&&!this.dropWhenIdle){this.releaseTimer||(this.releaseTimer=setTimeout(()=>{this.releaseTimer=null,this.isIdle()&&this.drop()},this.releaseDelay));return}this.drop()}}cancelPendingRelease(){this.releaseTimer&&(clearTimeout(this.releaseTimer),this.releaseTimer=null)}drop(){this.cancelPendingRelease(),this.audioBuffer&&(this.audioBuffer=null,this.references=0,this.playing=0,this.owner.evict(this))}},Su=class{constructor(o,e=0){this.cache=new Map,this.loadingPromises=new Map,this.generation=0,this.audioContext=o,this.releaseDelay=Math.max(0,e)}async load(o){return(await this.acquire(o)).retain()}async acquire(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.generation,i=this.doLoad(o);this.loadingPromises.set(o,i);try{let r=await i;return n!==this.generation?(await r.forceUnload(),r):(this.cache.set(o,r),r)}finally{this.loadingPromises.get(o)===i&&this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new vu(t,this,this.releaseDelay)}get(o){let e=this.cache.get(o);return e&&e.isAlive()?e:null}release(o){let e=this.cache.get(o);return e?(e.release(),!0):!1}async unload(o){let e=this.cache.get(o);return e?(await e.unload(),!0):!1}evict(o){for(let[e,t]of this.cache)if(t===o){this.cache.delete(e);return}}clear(){this.generation++;for(let o of Array.from(this.cache.values()))o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){let o=0;for(let e of this.cache.values())o+=e.byteLength();return{entries:this.cache.size,loading:this.loadingPromises.size,decodedBytes:o}}},bu=10*1024*1024,Tu={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1,cacheReleaseDelay:0},Ua=class Dr{constructor(e){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...Tu,...e},hu(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new Su(this.audioContext,this.options.cacheReleaseDelay),this.masterChannel=new fu("__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(e=>{let t=()=>{if(this.destroyed){this.clearUnlockHandler(),e();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,e())}).catch(n=>{en("Failed to resume AudioContext while unlocking.",n)})};this.unlockHandler=t,document.addEventListener("click",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",t)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let e=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",e),document.removeEventListener("touchstart",e),document.removeEventListener("keydown",e)}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(e,t,n){this.ensureNotDestroyed(),this.ensureReady();let{volume:i=1,rate:r=1,startTime:s=0,endTime:a,loopStart:l,load:c="auto",loop:u=!1}=t??{},p,d=null;if(typeof e=="string")if(await this.resolveLoadMode(e,c)==="stream")p=this.createStreamSource(e);else{d=await this.audioCache.acquire(e),d.addRef?.();let m=this.audioContext.createBufferSource();m.buffer=d.raw(),p=m}else{d=e,d.addRef?.();let m=this.audioContext.createBufferSource();m.buffer=e.raw(),p=m}let f=u&&a!==void 0&&a>s?{start:Dr.clampLoopStart(l,s,a),end:a}:null;p instanceof AudioBufferSourceNode?(p.loop=u,f&&(p.loopStart=f.start,p.loopEnd=f.end)):p instanceof HTMLAudioElement&&(p.loop=u);let h=new yu(this.audioContext,p,{volume:i,rate:r,startOffset:s,duration:!u&&a?a-s:0},n);if(d){let m=!1,g=()=>{m||(m=!0,d.releaseRef?.())};h.once("ended",g),h.once("stop",g)}return h}static clampLoopStart(e,t,n){return e===void 0||!Number.isFinite(e)?t:e>=t&&e<n?e:t}async resolveLoadMode(e,t){if(t==="stream"||t==="full")return t;let n=Dr.schemeOf(e);if(n==="data:"||n==="blob:")return"full";if(n!==null&&n!=="http:"&&n!=="https:")return"stream";try{let i=await fetch(e,{method:"HEAD"});if(!i.ok)return"stream";let r=i.headers.get("Content-Length");if(!r)return"stream";let s=parseInt(r,10);return isNaN(s)?"stream":s<bu?"full":"stream"}catch(i){return en("Failed to resolve load mode via HEAD request, falling back to 'stream'.",i),"stream"}}static schemeOf(e){try{let t=typeof location<"u"&&location?.href?location.href:void 0;return new URL(e,t).protocol}catch{return null}}createStreamSource(e){let t=new Audio(e);return t.crossOrigin="anonymous","preservesPitch"in t&&(t.preservesPitch=!1),t}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(e){this.registeredChannels.add(e)}unregisterChannel(e){this.registeredChannels.delete(e)}setVolume(e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(e),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(e){return this.ensureNotDestroyed(),this.ensureReady(),e===void 0?this.masterChannel.mute():this.masterChannel.mute(e),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(e,t){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(e,t)}getChannel(e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(e)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(e){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(e)}release(e){return this.ensureNotDestroyed(),this.audioCache.release(e)}async unload(e){return this.ensureNotDestroyed(),this.audioCache.unload(e)}getCached(e){return this.ensureNotDestroyed(),this.audioCache.get(e)}getCacheStats(){return this.audioCache.getStats()}async play(e,t){this.ensureNotDestroyed(),this.ensureReady();let n=this.masterChannel.getTokens();for(let i of n)try{i.stop()}catch{}return this.masterChannel.play(e,t)}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(e=>{en("Failed to close AudioContext during destroy().",e)}))}isDestroyed(){return this.destroyed}};var Ne=class Ne{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.retained=new Map;this.restoredByLoad=new Map;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 Ua({maxChannels:Ne.MaxChannels,cacheReleaseDelay:Ne.CacheGrace});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=Ne.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,Ne.BusRampTimeConstant),r.setValueAtTime(s,a+Ne.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 "${ot.sound}" instead.`)),this.channels.get(ot.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=Ne.defaultFade(e)){let n=new v;return this.restoredByLoad.delete(e),this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let r=await this.channelFor(e).play(e.config.src,{volume:0,...this.playOptionsOf(e)}),s=e.state.muted??!1;r.mute(s),e.state.muted=s,this.state.set(e,{token:r,originalVolume:t.end}),t.duration>0?await r.fade(0,t.end,t.duration).finished:r.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,!e.config.loop&&t.waitForEnd!==!1&&await new Promise(a=>{r.once("ended",()=>a())}),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=Ne.defaultFade(e)){this.restoredByLoad.delete(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 n.play(e.config.src,{volume:0,...this.playOptionsOf(e)}),r=e.state.muted??!1;return i.mute(r),e.state.muted=r,this.state.set(e,{token:i,originalVolume:t.end}),t.duration>0?i.fade(0,t.end,t.duration):i.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,i}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 v;if(this.restoredByLoad.delete(e),!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return this.arm(e,i),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 v;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 v;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}arm(e,t){let n=(t.transport??0)+1;return t.transport=n,()=>this.state.get(e)===t&&t.transport===n}pause(e,t=0){let n=new v;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);e.markDirty();let r=this.arm(e,i);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(()=>{if(!r()){n.resolve();return}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 v;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);e.markDirty();let r=this.arm(e,i);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(),e.state.paused=!1,i.token.fade(0,i.originalVolume,t).finished.then(()=>{if(!r()){n.resolve();return}e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return v.resolve(void 0);let n=this.state.get(e),i=Ne.clampToRegion(t,Ne.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),v.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}}playOptionsOf(e){return{...Ne.clipRegionOf(e),loop:e.config.loop,rate:e.state.rate,load:this.loadModeOf(e)}}loadModeOf(e){let{src:t,streaming:n,loop:i,endTime:r}=e.config;return t.startsWith("data:")||t.startsWith("blob:")?"full":n?"stream":this.gameState.game.config.audioStreaming==="declared"?"full":i&&r===void 0?"stream":"full"}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,v.resolve(void 0)):v.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(),...e.state.paused?{paused:!0}:{}}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return this.restoredByLoad.clear(),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.restoredByLoad.set(e,t.isPlaying&&!(t.paused??e.state.paused??!1)),this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=Ne.clipRegionOf(e),r=i.endTime!==void 0&&e.config.loop,s=await n.play(e.config.src,{volume:e.state.volume,...this.playOptionsOf(e),startTime:r?i.startTime:t.position});r&&Math.abs(t.position-i.startTime)>.01&&s.seek(Ne.clampToRegion(t.position,i)),this.state.set(e,{token:s,originalVolume:e.state.volume});let a=e.state.muted??!1;s.mute(a),e.state.muted=a;let l=t.paused??e.state.paused??!1;e.state.paused=l,l?s.pause():t.isPlaying||s.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}isRunningFromLoad(e){return this.restoredByLoad.get(e)===!0}preload(e){let t=e.config.src;if(this.loadModeOf(e)==="stream"||this.retained.has(t))return Promise.resolve();let n=this.ready.then(()=>this.sound.load(t)).then(()=>!0).catch(i=>(this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${t}")`,i),!1));return this.retained.set(t,n),n.then(()=>{})}retainOnly(e){let t=new Set(e.map(n=>n.config.src));for(let n of[...this.retained.keys()])t.has(n)||this.releaseSource(n);for(let n of e)this.preload(n)}getCacheStats(){return this.isReady?this.sound.getCacheStats():{entries:0,loading:0,decodedBytes:0}}releaseSource(e){let t=this.retained.get(e);t&&(this.retained.delete(e),t.then(n=>{n&&this.isReady&&this.sound.release(e)}))}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.restoredByLoad.clear(),this.retainOnly([]),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.retained.clear(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};Ne.MaxChannels=1024,Ne.BusRampTimeConstant=.02,Ne.BusRampSettle=Ne.BusRampTimeConstant*5,Ne.CacheGrace=5e3;var ao=Ne;function Ba(o){if(typeof MessageChannel>"u"){let n=setTimeout(o,0);return()=>clearTimeout(n)}let e=!1,t=new MessageChannel;return t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e||o()},t.port2.postMessage(void 0),()=>{e=!0}}var lo=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};import*as Pu from"html-to-image";var De=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),ct(()=>{this.preventAttach()})}static proxy(e){let t=new v,n=new v,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new P("Cannot create an 'any' timeline with no awaitables.");let t=new v,n=new v,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new P("Cannot create an 'all' timeline with no awaitables.");let t=new v,n=new v,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let l=e[a];i.attachChild(l),l.then(c=>{r[a]=c,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new v,s=()=>{if(i){let a;i.onSkipControllerRegister(l=>{a=l.onAbort(()=>{r.abort()})}),i.then(l=>{a?.cancel(),n=l,i=e(l),i?ct(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new B(()=>(i&&i.abort(),t))),i=e(t),i?ct(()=>s()):ct(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?ct(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.isSettled()||this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new P(`Attaching to this timeline violates the timeline's state.
|
|
14
|
+
reference, or store an id in place of the object.`);if(Array.isArray(o)||La(o)){n.add(o);try{if(Array.isArray(o))return o.map((l,c)=>wr(l,[...e,c],t+1,n,i,r,s));let a={};return Object.entries(o).forEach(([l,c])=>{a[l]=wr(c,[...e,l],t+1,n,i,r,s)}),a}finally{n.delete(o)}}}return console.warn(`Value of type "${vu(o)}" cannot be saved and was stored as null
|
|
15
|
+
at ${s}, ${Cr(e)}`),null}function vu(o){return typeof o!="object"||o===null?typeof o:o.constructor?.name??"object"}function Ia(o,e,t){let n=Da(o,e,kr);return n=Da(n,t,()=>{}),n}function Da(o,e,t){if(!Array.isArray(e)||!e.length)return o;let n=(r,s)=>Object.prototype.hasOwnProperty.call(r,s),i=o;for(let r of e){if(!Array.isArray(r))continue;if(!r.length){i=t(i);continue}let s=i;for(let l=0;l<r.length-1&&s!==null&&typeof s=="object";l++)s=n(s,r[l])?s[r[l]]:void 0;if(s===null||typeof s!="object")continue;let a=r[r.length-1];Object.defineProperty(s,a,{value:t(n(s,a)?s[a]:void 0),writable:!0,enumerable:!0,configurable:!0})}return i}function kr(o){return o instanceof Date?o:typeof o=="string"||typeof o=="number"?new Date(o):new Date(NaN)}function Ma(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function Pr(o,e,t=0){if(Object.is(o,e))return!0;if(t>li)return!1;if(o instanceof Date||e instanceof Date)return o instanceof Date&&e instanceof Date&&o.getTime()===e.getTime();if(Array.isArray(o)||Array.isArray(e))return Array.isArray(o)&&Array.isArray(e)&&o.length===e.length&&o.every((n,i)=>Pr(n,e[i],t+1));if(Ma(o)&&Ma(e)){let n=Object.keys(o);return n.length===Object.keys(e).length&&n.every(i=>Object.prototype.hasOwnProperty.call(e,i)&&Pr(o[i],e[i],t+1))}return!1}var Ut=class o{constructor(e,t,n){this.owner=null;this.name=e,this.key=n||e,this.content=Q({},t),this.defaultContent=t}static isSerializable(e){return ro(e)}set(e,t){let n=this.content[e];return o.isSerializable(t)?(this.content[e]=t,this.reportChange(e,n,t),this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
|
|
16
|
+
at namespace "${this.name}"`),this.content[e]=t,this.reportChange(e,n,t),this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){let e=this.content;return this.content=Q({},this.defaultContent),new Set([...Object.keys(e),...Object.keys(this.content)]).forEach(n=>{this.reportChange(n,e[n],this.content[n])}),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content={},this.deserialize(e)}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n,t)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)}),this.owner?.reportRestore(this.key)}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e,t){let n=`namespace "${this.name}"`+(t===void 0?"":`, key "${t}"`),i={any:s=>{let a=Ra(s,n),l={type:"any",data:a.data};return a.dates.length&&(l.dates=a.dates),a.undefineds.length&&(l.undefineds=a.undefineds),l},date:s=>({type:"date",data:s.toISOString()})},r=this.toTypeName(e);return i[r](e)}unwrap(e){let n={any:i=>Ia(i.data,i.dates,i.undefineds),date:i=>kr(i.data)}[e?.type];return n?n(e):(console.warn(`Unknown stored value type "${e?.type}", reading it as-is
|
|
17
|
+
at namespace "${this.name}"`),e?.data)}attach(e){return this.owner=e,this}detach(e){return this.owner===e&&(this.owner=null),this}reportChange(e,t,n){!this.owner||Pr(t,n)||this.owner.reportChange({namespace:this.key,key:String(e),previous:t,next:n})}},un=class un{constructor(){this.events=new ee;this.namespaces={};this.restoreBatch=null;this.events.setMaxListeners(64)}static createNamespace(e,t,n){return new Ut(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,e.attach(this),this}getNamespace(e){if(!this.namespaces[e])throw new P(`Namespace ${e} is not initialized, did you forget to register it?
|
|
18
|
+
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new P("No listener provided when subscribing to storable changes");return this.events.on(un.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(un.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new Ut(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(un.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(un.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(un.EventTypes["event:storable.restore"],{namespaces:[e]})}};un.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var ci=un;var mh={};var Un=class extends Hn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let l=a.getFutureActions(e,i).filter(c=>!r.has(c));s.push(...l)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var it=class extends J{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ft.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=v.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,l=>{l&&this.callee.fromData(l)},[s]),a}else if(this.type===Ft.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=v.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===Ft.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};it.ActionTypes=Ft;var ot={bgm:"bgm",sound:"sound",voice:"voice"},so=8,pn=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Bn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var pi=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=l=>{t.set(l.id,{id:l.id,parentId:l.parentId??null,volume:Bn(l.volume)})};Object.values(ot).forEach(l=>n({id:l}));let i=new Set;e.forEach(l=>{let c=l?.id;if(typeof c!="string"||c.trim().length===0)throw new pn(`Audio bus id must be a non-empty string, got ${JSON.stringify(c)}.`);if(i.has(c))throw new pn(`Audio bus "${c}" is declared more than once.`);i.add(c),n(l)}),o.assertResolvable(t);let r=[],s=new Map,a=l=>{let c=s.get(l);if(c)return c;let u=t.get(l),p=u.parentId===null?null:a(u.parentId),d={id:u.id,parentId:u.parentId,volume:u.volume,depth:p?p.depth+1:1};return s.set(l,d),r.push(d),d};return t.forEach(l=>a(l.id)),new o(r,s)}static isSeeded(e){return Object.values(ot).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new pn(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new pn(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>so)throw new pn(`Audio bus "${t.id}" nests deeper than ${so}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=so;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},Er=pi.resolve();function Su(o){Er=o}function Dr(){return Er}function ao(o,e){let t=Er;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var Na={[ot.bgm]:"bgmVolume",[ot.sound]:"soundVolume",[ot.voice]:"voiceVolume"};function Ga(o){let e={};return Object.entries(Na).forEach(([t,n])=>{e[t]={get:()=>Bn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var ui=class ui{constructor(e,t={}){this.declarations=e;this.events=new ee;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,Bn(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(ui.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=pi.resolve(this.declarations()??[]),Su(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Bn(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?Bn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Bn(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(ui.EventTypes["event:audioBus.volumeChange"],e)}};ui.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var di=ui;var Oa=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Oa||{}),Pe=class Pe extends fe{static toSound(e){return e==null?null:typeof e=="string"?new Pe({src:e}):e}static isSound(e){return e instanceof Pe}static voice(e){let t=typeof e=="string"?{src:e}:e;return new Pe({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new Pe({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new Pe({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=Pe.DefaultUserConfig.create(t),[i]=n.extract(Pe.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e,t){return Dr().isUnder(this.config.type,ot.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(it.ActionTypes.play,[{end:this.state.volume,duration:e||0,waitForEnd:t?.waitForEnd===!0}])}stop(e){return this.pushAction(it.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(it.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(it.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(it.ActionTypes.setRate,[e])}pause(e){return this.pushAction(it.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(it.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(it.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:Pe.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Pe.StateSerializer.deserialize(e.state),this}copy(){return new Pe(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Pe.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new it(this.chain(),e,new x().setContent(t)))}};Pe.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Pe.DefaultUserConfig=new $({src:Pe.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Pe.DefaultConfig=new $({src:Pe.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Pe.DefaultState=new $({volume:1,rate:1,paused:!1,muted:!1}),Pe.StateSerializer=new Xe;var Se=Pe;var Cn=class Cn{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===Cn.SrcTypes.image?t.add(s):r===Cn.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof O?O.getSrcURL(e):e.type==="image"?O.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(re,W.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(w.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof Ae){let n=t;if(t.is(Ae,ht.setSrc)){let i=t.contentNode.getContent()[0];if(w.isImageSrc(i))return{type:"image",src:w.srcToURL(i),activeType:"scene"}}else{if(t.type===ht.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===ht.setAppearance){let i=t.contentNode.getContent()[0];if(O.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(O.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:O.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof Se){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof O||w.isStaticImageData(e)){if(e instanceof O){if(!w.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(O.getSrcURL(e)))return this}else if(this.isSrcRegistered(w.srcToURL(e.src)))return this;this.src.push({type:"image",src:w.isStaticImageData(e)?w.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof Se?t:new Se({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof Se?e.getSrc():e;return this.src.some(n=>n.type===Cn.SrcTypes.audio?t===n.src.getSrc():n.type===Cn.SrcTypes.image?t===O.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};Cn.SrcTypes={image:"image",video:"video",audio:"audio"};var Me=Cn;import*as el from"howler";var $e=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var pt=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};function Va(o,e){let{render:t,data:n,...i}=e,r=Q(o,i);return"render"in e?r.render=e.render:"render"in o&&(r.render=o.render),"data"in e?r.data=e.data:"data"in o&&(r.data=o.data),r}var xe=class xe{static isWord(e){return e instanceof xe}static color(e,t){return xe.isWord(e)?e.copy().assign({color:t}):new xe(e,{color:t})}static bold(e){return xe.isWord(e)?e.copy().assign({bold:!0}):new xe(e,{bold:!0})}static italic(e){return xe.isWord(e)?e.copy().assign({italic:!0}):new xe(e,{italic:!0})}static emphasis(e,t={}){return xe.isWord(e)?e.copy().assign({emphasis:t}):new xe(e,{emphasis:t})}static custom(e,t,n={}){let i={...n,render:t};return xe.isWord(e)?e.copy().assign(i):new xe(e,i)}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=Va(xe.defaultConfig,t)}evaluate(e){if($e.isPause(this.text))return[this];if(pt.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>xe.isWord(n)?n.inherit(this.config).evaluate(e):new xe(n,this.config)).flat():xe.isWord(t)?t.inherit(this.config).evaluate(e):[new xe(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this.config.emphasis=this.config.emphasis??e.emphasis,this.config.fontScale=this.config.fontScale??e.fontScale,this}assign(e){return this.config=Va(this.config,e),this}copy(){return new xe(this.text,this.config)}isPause(){return $e.isPause(this.text)}isTextEvent(){return pt.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};xe.defaultConfig={},xe.defaultColor="#000";var ae=xe;var dt=class dt{static isSentence(e){return e instanceof dt}static toSentence(e){return dt.isSentence(e)?e:new dt(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return ae.isWord(e)?e:new ae(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[ae.isWord(e)?e:new ae(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(dt.isSingleWord):dt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||ae.isWord(e)||$e.isPause(e)||pt.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=dt.format(e),this.config=Q(dt.defaultConfig,{...t,voice:typeof t.voice=="string"?Se.voice(t.voice):Se.toSound(t.voice)}),this.state=ha(dt.defaultState)}toData(){return null}fromData(e){return this.state=Q(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...dt.formatStaticWord(i))}return t}copy(){return new dt([...this.text],this.config)}};dt.defaultConfig={voice:null,character:null,voiceId:null},dt.defaultState={};var ve=dt;var lo=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 dn=class extends J{executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};dn.ActionTypes=da;var Ee=class o extends fe{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new dn(t,dn.ActionTypes.action,new x().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new dn(this.chain(),dn.ActionTypes.action,new x().setContent(e))]}};var bu={volume:1,limit:1/0},Tu=class Ha{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={...bu,...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 Ha(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}}},Ua=!1;function Au(o){Ua=o}function en(o,e){Ua||(e!==void 0?console.warn(o,e):console.warn(o))}var xu=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.onSourceEnded=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){en("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){en("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=()=>{this.onSourceEnded?this.onSourceEnded():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)}setSourceEndedHandler(o){this.onSourceEnded=o}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){en("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){if(this.currentSource instanceof AudioBufferSourceNode)this.currentSource.start(o,e);else if(this.currentSource instanceof HTMLAudioElement){e>0&&(this.currentSource.currentTime=e);let t=this.currentSource.play();t&&typeof t.catch=="function"&&t.catch(n=>{en("Failed to start HTMLAudioElement playback.",n)})}}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},Fa=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}},Cu=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 xu(o,this.gainNode),this.sourceController.setSourceEndedHandler(()=>this.emit("ended")),this.sourceController.setSource(e),this.applyRate(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,this._isPaused=!1;try{this.gainNode.disconnect()}catch(e){en("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){en("Failed to disconnect gain node on stop().",o)}}setRate(o){return o=Math.max(.001,o),this.rate=o,this.applyRate(this.sourceController.getSource()),this}applyRate(o){o instanceof HTMLAudioElement?o.playbackRate=this.rate:o instanceof AudioBufferSourceNode&&(o.playbackRate.value=this.rate)}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 Fa(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new Fa(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}},wu=class{constructor(o,e,t){this.owner=e,this.releaseDelay=t,this.references=0,this.playing=0,this.dropWhenIdle=!1,this.releaseTimer=null,this.audioBuffer=o}retain(){return this.references++,this.dropWhenIdle=!1,this.cancelPendingRelease(),this}release(){this.references>0&&this.references--,this.reconsider()}addRef(){this.playing++,this.cancelPendingRelease()}releaseRef(){this.playing>0&&this.playing--,this.reconsider()}getReferenceCount(){return this.references}getPlayingCount(){return this.playing}getRefCount(){return this.playing}async unload(){this.references=0,this.dropWhenIdle=!0,this.reconsider()}async forceUnload(){this.drop()}isAlive(){return this.audioBuffer!==null}raw(){if(!this.audioBuffer)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}byteLength(){return this.audioBuffer?this.audioBuffer.length*this.audioBuffer.numberOfChannels*4:0}isIdle(){return this.audioBuffer!==null&&this.references===0&&this.playing===0}reconsider(){if(this.isIdle()){if(this.releaseDelay>0&&!this.dropWhenIdle){this.releaseTimer||(this.releaseTimer=setTimeout(()=>{this.releaseTimer=null,this.isIdle()&&this.drop()},this.releaseDelay));return}this.drop()}}cancelPendingRelease(){this.releaseTimer&&(clearTimeout(this.releaseTimer),this.releaseTimer=null)}drop(){this.cancelPendingRelease(),this.audioBuffer&&(this.audioBuffer=null,this.references=0,this.playing=0,this.owner.evict(this))}},ku=class{constructor(o,e=0){this.cache=new Map,this.loadingPromises=new Map,this.generation=0,this.audioContext=o,this.releaseDelay=Math.max(0,e)}async load(o){return(await this.acquire(o)).retain()}async acquire(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.generation,i=this.doLoad(o);this.loadingPromises.set(o,i);try{let r=await i;return n!==this.generation?(await r.forceUnload(),r):(this.cache.set(o,r),r)}finally{this.loadingPromises.get(o)===i&&this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new wu(t,this,this.releaseDelay)}get(o){let e=this.cache.get(o);return e&&e.isAlive()?e:null}release(o){let e=this.cache.get(o);return e?(e.release(),!0):!1}async unload(o){let e=this.cache.get(o);return e?(await e.unload(),!0):!1}evict(o){for(let[e,t]of this.cache)if(t===o){this.cache.delete(e);return}}clear(){this.generation++;for(let o of Array.from(this.cache.values()))o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){let o=0;for(let e of this.cache.values())o+=e.byteLength();return{entries:this.cache.size,loading:this.loadingPromises.size,decodedBytes:o}}},Pu=10*1024*1024,Eu={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1,cacheReleaseDelay:0},Ba=class Lr{constructor(e){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...Eu,...e},Au(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new ku(this.audioContext,this.options.cacheReleaseDelay),this.masterChannel=new Tu("__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(e=>{let t=()=>{if(this.destroyed){this.clearUnlockHandler(),e();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,e())}).catch(n=>{en("Failed to resume AudioContext while unlocking.",n)})};this.unlockHandler=t,document.addEventListener("click",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",t)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let e=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",e),document.removeEventListener("touchstart",e),document.removeEventListener("keydown",e)}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(e,t,n){this.ensureNotDestroyed(),this.ensureReady();let{volume:i=1,rate:r=1,startTime:s=0,endTime:a,loopStart:l,load:c="auto",loop:u=!1}=t??{},p,d=null;if(typeof e=="string")if(await this.resolveLoadMode(e,c)==="stream")p=this.createStreamSource(e);else{d=await this.audioCache.acquire(e),d.addRef?.();let m=this.audioContext.createBufferSource();m.buffer=d.raw(),p=m}else{d=e,d.addRef?.();let m=this.audioContext.createBufferSource();m.buffer=e.raw(),p=m}let f=u&&a!==void 0&&a>s?{start:Lr.clampLoopStart(l,s,a),end:a}:null;p instanceof AudioBufferSourceNode?(p.loop=u,f&&(p.loopStart=f.start,p.loopEnd=f.end)):p instanceof HTMLAudioElement&&(p.loop=u);let h=new Cu(this.audioContext,p,{volume:i,rate:r,startOffset:s,duration:!u&&a?a-s:0},n);if(d){let m=!1,g=()=>{m||(m=!0,d.releaseRef?.())};h.once("ended",g),h.once("stop",g)}return h}static clampLoopStart(e,t,n){return e===void 0||!Number.isFinite(e)?t:e>=t&&e<n?e:t}async resolveLoadMode(e,t){if(t==="stream"||t==="full")return t;let n=Lr.schemeOf(e);if(n==="data:"||n==="blob:")return"full";if(n!==null&&n!=="http:"&&n!=="https:")return"stream";try{let i=await fetch(e,{method:"HEAD"});if(!i.ok)return"stream";let r=i.headers.get("Content-Length");if(!r)return"stream";let s=parseInt(r,10);return isNaN(s)?"stream":s<Pu?"full":"stream"}catch(i){return en("Failed to resolve load mode via HEAD request, falling back to 'stream'.",i),"stream"}}static schemeOf(e){try{let t=typeof location<"u"&&location?.href?location.href:void 0;return new URL(e,t).protocol}catch{return null}}createStreamSource(e){let t=new Audio(e);return t.crossOrigin="anonymous","preservesPitch"in t&&(t.preservesPitch=!1),t}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(e){this.registeredChannels.add(e)}unregisterChannel(e){this.registeredChannels.delete(e)}setVolume(e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(e),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(e){return this.ensureNotDestroyed(),this.ensureReady(),e===void 0?this.masterChannel.mute():this.masterChannel.mute(e),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(e,t){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(e,t)}getChannel(e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(e)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(e){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(e)}release(e){return this.ensureNotDestroyed(),this.audioCache.release(e)}async unload(e){return this.ensureNotDestroyed(),this.audioCache.unload(e)}getCached(e){return this.ensureNotDestroyed(),this.audioCache.get(e)}getCacheStats(){return this.audioCache.getStats()}async play(e,t){this.ensureNotDestroyed(),this.ensureReady();let n=this.masterChannel.getTokens();for(let i of n)try{i.stop()}catch{}return this.masterChannel.play(e,t)}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(e=>{en("Failed to close AudioContext during destroy().",e)}))}isDestroyed(){return this.destroyed}};var Ne=class Ne{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.retained=new Map;this.restoredByLoad=new Map;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 Ba({maxChannels:Ne.MaxChannels,cacheReleaseDelay:Ne.CacheGrace});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=Ne.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,Ne.BusRampTimeConstant),r.setValueAtTime(s,a+Ne.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 "${ot.sound}" instead.`)),this.channels.get(ot.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=Ne.defaultFade(e)){let n=new v;return this.restoredByLoad.delete(e),this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let r=await this.channelFor(e).play(e.config.src,{volume:0,...this.playOptionsOf(e)}),s=e.state.muted??!1;r.mute(s),e.state.muted=s,this.state.set(e,{token:r,originalVolume:t.end}),t.duration>0?await r.fade(0,t.end,t.duration).finished:r.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,!e.config.loop&&t.waitForEnd!==!1&&await new Promise(a=>{r.once("ended",()=>a())}),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=Ne.defaultFade(e)){this.restoredByLoad.delete(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 n.play(e.config.src,{volume:0,...this.playOptionsOf(e)}),r=e.state.muted??!1;return i.mute(r),e.state.muted=r,this.state.set(e,{token:i,originalVolume:t.end}),t.duration>0?i.fade(0,t.end,t.duration):i.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,i}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 v;if(this.restoredByLoad.delete(e),!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return this.arm(e,i),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 v;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 v;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}arm(e,t){let n=(t.transport??0)+1;return t.transport=n,()=>this.state.get(e)===t&&t.transport===n}pause(e,t=0){let n=new v;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);e.markDirty();let r=this.arm(e,i);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(()=>{if(!r()){n.resolve();return}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 v;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);e.markDirty();let r=this.arm(e,i);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(),e.state.paused=!1,i.token.fade(0,i.originalVolume,t).finished.then(()=>{if(!r()){n.resolve();return}e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return v.resolve(void 0);let n=this.state.get(e),i=Ne.clampToRegion(t,Ne.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),v.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}}playOptionsOf(e){return{...Ne.clipRegionOf(e),loop:e.config.loop,rate:e.state.rate,load:this.loadModeOf(e)}}loadModeOf(e){let{src:t,streaming:n,loop:i,endTime:r}=e.config;return t.startsWith("data:")||t.startsWith("blob:")?"full":n?"stream":this.gameState.game.config.audioStreaming==="declared"?"full":i&&r===void 0?"stream":"full"}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,v.resolve(void 0)):v.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(),...e.state.paused?{paused:!0}:{}}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return this.restoredByLoad.clear(),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.restoredByLoad.set(e,t.isPlaying&&!(t.paused??e.state.paused??!1)),this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=Ne.clipRegionOf(e),r=i.endTime!==void 0&&e.config.loop,s=await n.play(e.config.src,{volume:e.state.volume,...this.playOptionsOf(e),startTime:r?i.startTime:t.position});r&&Math.abs(t.position-i.startTime)>.01&&s.seek(Ne.clampToRegion(t.position,i)),this.state.set(e,{token:s,originalVolume:e.state.volume});let a=e.state.muted??!1;s.mute(a),e.state.muted=a;let l=t.paused??e.state.paused??!1;e.state.paused=l,l?s.pause():t.isPlaying||s.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}isRunningFromLoad(e){return this.restoredByLoad.get(e)===!0}preload(e){let t=e.config.src;if(this.loadModeOf(e)==="stream"||this.retained.has(t))return Promise.resolve();let n=this.ready.then(()=>this.sound.load(t)).then(()=>!0).catch(i=>(this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${t}")`,i),!1));return this.retained.set(t,n),n.then(()=>{})}retainOnly(e){let t=new Set(e.map(n=>n.config.src));for(let n of[...this.retained.keys()])t.has(n)||this.releaseSource(n);for(let n of e)this.preload(n)}getCacheStats(){return this.isReady?this.sound.getCacheStats():{entries:0,loading:0,decodedBytes:0}}releaseSource(e){let t=this.retained.get(e);t&&(this.retained.delete(e),t.then(n=>{n&&this.isReady&&this.sound.release(e)}))}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.restoredByLoad.clear(),this.retainOnly([]),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.retained.clear(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};Ne.MaxChannels=1024,Ne.BusRampTimeConstant=.02,Ne.BusRampSettle=Ne.BusRampTimeConstant*5,Ne.CacheGrace=5e3;var co=Ne;function Wa(o){if(typeof MessageChannel>"u"){let n=setTimeout(o,0);return()=>clearTimeout(n)}let e=!1,t=new MessageChannel;return t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e||o()},t.port2.postMessage(void 0),()=>{e=!0}}var uo=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};import*as Mu from"html-to-image";var De=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),ct(()=>{this.preventAttach()})}static proxy(e){let t=new v,n=new v,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new P("Cannot create an 'any' timeline with no awaitables.");let t=new v,n=new v,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new P("Cannot create an 'all' timeline with no awaitables.");let t=new v,n=new v,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let l=e[a];i.attachChild(l),l.then(c=>{r[a]=c,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new v,s=()=>{if(i){let a;i.onSkipControllerRegister(l=>{a=l.onAbort(()=>{r.abort()})}),i.then(l=>{a?.cancel(),n=l,i=e(l),i?ct(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new B(()=>(i&&i.abort(),t))),i=e(t),i?ct(()=>s()):ct(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?ct(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.isSettled()||this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new P(`Attaching to this timeline violates the timeline's state.
|
|
19
19
|
Timeline attaching is only allowed synchronously after the timeline is created.
|
|
20
|
-
Current _ableToAttach: `+this._ableToAttach);let t=v.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){if(this.isSettled())return;let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved?this.children.every(t=>t.isSettled())&&this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},co=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof De?e:new De(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var uo=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new Z}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 v,n=new De(t);return t.registerSkipController(new B(()=>{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 po(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 Au=4e3,Ka={zIndex:0,visibility:"visible"},Cu={...Ka,zIndex:1},za={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function mn(){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 mo(){return{...mn(),visibility:"hidden"}}var fo=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.companions=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?(this.sceneElements.set(e.getId(),t),this.gameState.isSceneSuspended(e)&&Object.assign(t.style,mo()),this.companions.get(e.getId())?.forEach(n=>this.copyPose(e,n))):this.sceneElements.delete(e.getId())}bindCompanion(e,t){let n=e.getId(),i=this.companions.get(n);return i||(i=new Set,this.companions.set(n,i)),i.add(t),this.copyPose(e,t),()=>{let r=this.companions.get(n);r?.delete(t)&&(r.size||this.companions.delete(n),Object.assign(t.style,mn()))}}paintedBy(e){let t=this.sceneElements.get(e),n=this.companions.get(e);return[...t?[t]:[],...n?[...n]:[]]}copyPose(e,t){let n=this.sceneElements.get(e.getId());if(!n){Object.assign(t.style,this.gameState.isSceneSuspended(e)?mo():mn());return}let i=mn(),r=n.style,s=t.style;Object.keys(i).forEach(a=>{s[a]=r[a]})}syncScenePose(e,t){if(this.running&&(this.running.roles.from===e||this.running.roles.to===e))return;let n=t?mo():mn();this.paintedBy(e.getId()).forEach(i=>Object.assign(i.style,n))}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 v().registerSkipController(new B(s.cancel)),l=new De(a),c=[],u=r.resolve.map(f=>{if(typeof f=="function"){let m=this.createOverlay();return c.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(f.key==="target"?t.to:t.from).getId(),role:f.key}}),p={task:r,controller:s,roles:t,targets:u,overlays:c,cancelLoadGate:()=>{},stale:!1};this.running=p,s.onUpdate(f=>this.applyFrame(p,f)),s.onComplete(()=>{this.settle(p,[[t.to,mn()],[t.from,mo()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(p,[[t.from,mn()],[t.to,mn()]]),l.abort()}),this.applyFrame(p,r.animations.map(f=>f.start));let d=this.waitForSceneReady(t.to);return p.cancelLoadGate=d.cancel,d.promise.then(()=>{p.stale||s.start()}),l}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?[r.element]:this.paintedBy(r.sceneId);if(!s.length)return;let a=typeof n=="function"?n:n.resolver,l=r.kind==="overlay"?za:r.role==="target"?Cu:Ka,c=Q({style:l},a(...t));s.forEach(u=>po(u,c,xu))})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{this.paintedBy(n.getId()).forEach(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,za),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()},Au)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(wu)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},_a=["src","width","height"];function xu(o){if(!_a.some(t=>t in o))return o;let e={...o};return _a.forEach(t=>delete e[t]),e}function wu(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 ho=class{constructor(e){this.options=e;this.planned=new Set;this.desired=[];this.admitted=[];this.pending=null;this.pendingTimer=null}retain(e){this.planned=new Set(e),this.desired=e.filter(i=>!this.options.isDeclared(i));let t=!1,n=[];for(let i of this.admitted)this.desired.includes(i)?n.push(i):t=!0;this.admitted=n,this.pending&&!this.admitted.includes(this.pending)&&this.clearPending(),(this.admit()||t)&&this.options.onChange()}noteReady(e){!this.pending||this.pending!==e||(this.clearPending(),this.admit()&&this.options.onChange())}forget(e){let t=this.admitted.indexOf(e);t>=0&&this.admitted.splice(t,1),this.desired=this.desired.filter(n=>n!==e),this.pending===e&&this.clearPending(),this.admit()&&this.options.onChange()}getAdmitted(){return this.admitted}isPlanned(e){return this.planned.has(e)}clear(){this.clearPending(),this.planned=new Set,this.desired=[],this.admitted.length&&(this.admitted=[],this.options.onChange())}admit(){if(this.pending||this.admitted.length>=3)return!1;let e=this.desired.find(t=>!this.admitted.includes(t));return e?(this.admitted.push(e),this.pending=e,this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,this.pending=null,this.admit()&&this.options.onChange()},5e3),!0):!1}clearPending(){this.pendingTimer!==null&&(clearTimeout(this.pendingTimer),this.pendingTimer=null),this.pending=null}};var go=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=Zi(6),{action:r,timeline:s,stackModel:a}=e,l=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:l,stackModel:a}),this.history.length>this.maxHistorySize){let c=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(c))}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 yo=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??Zi(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1,this.resumingAtCursor=this.cursor>=0}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 tn=class tn extends X{executeAction(e,t){if(this.type===fe.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===fe.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===fe.applyLoop){let[n,i]=this.contentNode.getContent();return this.applyLoop(e,this.callee,n,i,t)}else if(this.type===fe.stopLoop){let[n]=this.contentNode.getContent();return this.stopLoop(e,this.callee,n,t)}else if(this.type===fe.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}else if(this.type===fe.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new v().registerSkipController(new B(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t),c=t.transformState.clone(),u=t._getLoop(),p=t._getLoopActionId();u&&(t._setLoop(null,{},null),t.markDirty());let d=l.applyTransform(n,a),f=e.timelines.attachTimeline(s).attachChild(d);return d.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:f},(h,m,g)=>{s.isSettled()||s.abort(),d.abort(),t.transformState.forceOverwrite(h.state),tn.restoreLoop(e,t,m,g)},[c,u,p]),s}applyLoop(e,t,n,i,r){let s=t._getLoop(),a=t._getLoopActionId(),l=i??{};t._setLoop(n,l,this.getId()),t.markDirty(),e.getExposedState(t)?.applyLoop(n,l),e.actionHistory.push({action:this,stackModel:r.stackModel},(u,p)=>{tn.restoreLoop(e,t,u,p)},[s,a]);let c=new v;return c.resolve(super.executeAction(e,r)),c}stopLoop(e,t,n,i){let r=t._getLoop(),s=t._getLoopActionId();t._setLoop(null,{},null),t.markDirty();let a=new v().registerSkipController(new B(()=>(e.logger.info("Displayable Loop","Skipped"),super.executeAction(e,i)))),l=()=>{a.isSettled()||a.resolve(super.executeAction(e,i))},c=e.getExposedState(t);if(!c||!r)return e.actionHistory.push({action:this,stackModel:i.stackModel},(d,f)=>{tn.restoreLoop(e,t,d,f)},[r,s]),l(),a;let u=c.stopLoop(n,l),p=e.timelines.attachTimeline(a).attachChild(u);return u.onCancelled(l),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:p},(d,f)=>{a.isSettled()||a.abort(),u.abort(),tn.restoreLoop(e,t,d,f)},[r,s]),a}static restoreLoop(e,t,n,i){if(!n&&!t._getLoop())return;t._setLoop(n?.transform??null,n?.options??{},i),t.markDirty();let r=e.getExposedState(t);r&&(n?r.applyLoop(n.transform,n.options):r.stopLoop(void 0,()=>{}))}applyTransition(e,t,n,i,r){let s=new v().registerSkipController(new B(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(c);return c.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),c.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let c=e.findElementByDisplayable(this.callee,i);c&&e.disposeDisplayable(n,c.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new v().registerSkipController(new B(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,c=>{c.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let l=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:l},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&tn.getLayerElements(i,t);if(!r)throw new P(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let c=e.findElementByDisplayable(t),u=c&&tn.getLayerElements(c,t);if(!u)return;let p=u.indexOf(t);p!==l&&(u.splice(p,1),u.splice(l,0,t),e.flush())},[s]);let a=new v;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};tn.ActionTypes=fe;var xe=tn;var je=class o extends me{constructor(){super(...arguments);this.srcManager=new Me;this.loopTransform=null;this.loopOptions={};this.loopActionId=null}_getLoop(){return this.loopTransform?{transform:this.loopTransform,options:this.loopOptions}:null}_setLoop(t,n,i){return this.loopTransform=t,this.loopOptions=t?n:{},this.loopActionId=t?i:null,this}_getLoopActionId(){return this.loopActionId}_serializeLoop(){return this.loopActionId?{actionId:this.loopActionId,options:{...this.loopOptions}}:null}_deserializeLoop(t){return this.loopTransform=null,this.loopOptions=t?{...t.options}:{},this.loopActionId=t?t.actionId:null,this}_rebindLoop(t){if(!this.loopActionId||this.loopTransform)return this;let i=t.get(this.loopActionId)?.contentNode?.getContent(),r=Array.isArray(i)?i[0]:void 0;return r instanceof ne?(this.loopTransform=r,this):this._setLoop(null,{},null)}reset(){super.reset(),this._setLoop(null,{},null)}pos(t,n,i){return this.transform(new ne({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new ne({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new ne({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new ne({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new ne({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new ne({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new ne({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new ne(t,n))}mask(t,n={}){let i=k.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:l,...c}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:l},c)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:l="easeInOut",...c}=t,u={duration:a,ease:l,...c},p=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Ve,d=>d.transform(p).clearClip({duration:0})):this.transform(p)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:l="easeInOut",...c}=t,u={duration:a,ease:l,...c},p=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Ve,d=>d.transform(p).clearClip({duration:0})):this.transform(p)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...l}=t,c={duration:s,ease:a,...l},u=o.wipeClipPath(n,100),p=o.wipeClipPath(n,0),d=o.createClipPathTransform([[i?p:u,{duration:0}],[i?u:p,c]]);return r?this.combineActions(new Ve,f=>f.transform(d).clearClip({duration:0})):this.transform(d)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new xe(n,fe.applyTransform,new A().setContent([t.copy()]));return n.chain(i)}loop(t,n){let i=this.chain(),r=new xe(i,fe.applyLoop,new A().setContent([t.copy(),n]));return i.chain(r)}stopLoop(t){let n=this.chain(),i=new xe(n,fe.stopLoop,new A().setContent([t]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new xe(t,fe.bringToFront,new A().setContent([]));return t.chain(n)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new ne(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof ne?t.copy():new ne({opacity:1},t),r=new xe(n,fe.applyTransform,new A().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof ne?t.copy():new ne({opacity:0},t),r=new xe(n,fe.applyTransform,new A().setContent([i]));return n.chain(r)}};var fn=class fn extends me{constructor(e,t={}){super(),this.config=Q(fn.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(l=>typeof l=="string")&&[t,...n].length>0&&[t,...n].every(l=>ve.isSingleWord(l))){let l=e,c=ve.format([t,...n]),u=new ve(ga(l,c),{character:this}),p=new rt(this.chain(),rt.ActionTypes.say,new A().setContent(u));return this.chain(p)}let i=t||{},r=e,s=Array.isArray(r)?new ve(r,{...i,character:this}):(ve.isSentence(r)?r:new ve(r,{...i,character:this})).copy();s.setCharacter(this);let a=new rt(this.chain(),rt.ActionTypes.say,new A().setContent(s));return this.chain(a)}setName(e){let t=new rt(this.chain(),rt.ActionTypes.setName,new A().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&ve.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ve.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:fn.StateSerializer.serialize(this.state)}}fromData(e){return this.state=fn.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};fn.defaultCharacterColor="#000",fn.defaultConfig={portraits:[]},fn.StateSerializer=new Xe;var vo=fn,nn=new vo(null);var J=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},Lr=class o extends me{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new He(`ELSE condition already set
|
|
21
|
-
You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:
|
|
22
|
-
You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(Ht,[this,Ht.ActionTypes.action,new A().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,l=r[s+1]?.contentNode;l&&a.setChild(l),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return Ke.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=J.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new Ht(i,Ht.ActionTypes.action,new A().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?nn.say(n).getActions():Ke.toActions([n]))}};var wn=class extends X{executeAction(e,t){let n=new v().registerSkipController(new B(()=>{l.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,l=e.createMenu(r,u=>{let p=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[p]}}),a=()=>{p.reset()},e.gameHistory.updateByToken(c,d=>{d&&d.element.type==="menu"&&(d.element.selected=u.evaluated,d.isPending=!1)})}),{id:c}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{l.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:c,action:this,element:{type:"menu",text:l.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(l=>l.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};wn.ActionTypes=da;var kn=class kn extends me{constructor(t,n={}){super();this.choices=[];this.prompt=ve.isSentence(t)?t:t===null?null:new ve(t),this.config=Q(kn.defaultConfig,n)}static prompt(t,n={}){return new kn(t!==void 0?t:null,n)}static choose(t,n){return new kn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return ve.isSentence(t)&&n?i.choices.push({prompt:ve.toSentence(t),action:this.narrativeToActions(n),config:{}}):(se.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:ve.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:ve.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?J.from(t.config.disabled):void 0,hidden:t.config?.hidden?J.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new He("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=J.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new He("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=J.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:J.not(J.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:J.not(J.from(t))}})}fromChained(t){return[new wn(this.chain(),wn.ActionTypes.action,new A().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?nn.say(n).getActions():Ke.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??{}}))}};kn.defaultConfig={},kn.targetAction=wn;var Rr=kn;var di=class di extends X{executeAction(e,t){let n=this;if(n.is(di,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let l=s.get(i);s.set(i,r(l))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{s.set(i,l)},[a]),super.executeAction(e,t)}else if(n.is(di,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(l=>{s[l]=r.get(l),r.set(l,a[l])}),e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{Object.keys(l).forEach(c=>{r.set(c,l[c])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};di.ActionTypes=ii;var So=di;var bo=class bo extends me{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new Ut(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(ii.set,[e,t]))}assign(e){return this.chain(this.createAction(ii.assign,[e]))}equals(e,t){return new J(n=>{let i=n.storable.getNamespace(this.namespace),r=J.isLambda(t)||J.isLambdaHandler(t)?J.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new J(n=>{let i=n.storable.getNamespace(this.namespace),r=J.isLambda(t)||J.isLambdaHandler(t)?J.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new J(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new J(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new J(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new se(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new se(i=>J.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new J(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=bo.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new So(this.chain(),e,A.create(t))}};bo.NamespacePrefix="persistent";var Wn=bo,To=class To extends Wn{constructor(e){super(e,{}),this.namespace=this.prefix(e,To.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new Ut(this.namespace,this.defaultContent))}};To.LocalNamespacePrefix="local";var zn=To;var vt={shutter:0,shutterColor:"#000",vignette:0,vignetteColor:"#000",vignetteInner:"44%",vignetteOuter:"78%"};function Ir(o){return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(1,o))}function mi(o,e){return typeof o=="string"&&o.length>0?o:e}function $a(o){let e=Ir(o.shutter);return{backgroundColor:mi(o.shutterColor,vt.shutterColor),clipPath:`inset(0 0 ${100-50*e}% 0)`}}function ja(o){let e=Ir(o.shutter);return{backgroundColor:mi(o.shutterColor,vt.shutterColor),clipPath:`inset(${100-50*e}% 0 0 0)`}}function qa(o){let e=mi(o.vignetteInner,vt.vignetteInner),t=mi(o.vignetteOuter,vt.vignetteOuter),n=`radial-gradient(circle at center, transparent ${e}, black ${t})`;return{backgroundColor:mi(o.vignetteColor,vt.vignetteColor),opacity:Ir(o.vignette),maskImage:n,WebkitMaskImage:n,maskSize:"100% 100%",WebkitMaskSize:"100% 100%",maskPosition:"50% 50%",WebkitMaskPosition:"50% 50%",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat",maskMode:"alpha"}}var mt=class mt extends je{static get DefaultUserConfig(){return mt._defaultUserConfig??(mt._defaultUserConfig=new $({...re.DefaultTransformState.getDefaultConfig(),opacity:1,...vt}))}constructor(e={}){super();let t=mt.DefaultUserConfig.create(e),n=mt.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}shutter(e,t,n){return this.lens({shutter:mt.clampLens(e)},{duration:t,ease:n})}vignette(e,t,n){return this.lens({vignette:mt.clampLens(e)},{duration:t,ease:n})}lens(e,t){return this.transform(new ne(e,t))}resetCamera(e,t){return this.transform(new ne([{props:{filter:"none"},options:{duration:0}},{props:{position:new ut("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,shutter:vt.shutter,vignette:vt.vignette},options:{duration:e,ease:t}},{props:{shutterColor:vt.shutterColor,vignetteColor:vt.vignetteColor,vignetteInner:vt.vignetteInner,vignetteOuter:vt.vignetteOuter},options:{duration:0}}]))}static clampLens(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}bringToFront(){throw new P(`A camera cannot be brought to front. It is not an element inside a layer, it is what the layers are viewed through, so it has nothing to be in front of \u2014 waiting for it to be added to the stage will not help. Use a camera transform such as Camera.zoom or Camera.pan to change what is in view. (camera: ${this.config.name})`)}reset(){return super.reset(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.transformState.resetTo(re.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}copy(){return new mt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(mt.DefaultUserConfig.keys());return new re(mt.DefaultUserConfig.create(e.get()).get())}};mt._defaultUserConfig=null,mt.DefaultConfig=new $({name:"(camera)"});var fi=mt;var hn=class hn extends Un{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.hashCache=new Map;this.name=t;let{camera:i,...r}=n;this.config=Q(hn.defaultConfig,r),this._camera=i??new fi}static empty(){return new hn("empty").entry(new Je("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 Wn(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 He(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){let n=this.hashCache.get(t);if(n!==void 0)return n;let i=Ca(this.stringify(t));return this.hashCache.set(t,i),i}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,i)=>{if(!n.serialize||typeof n.serialize!="function")return;let r=n.serialize();if(r!==null){{if(r instanceof Promise)throw new te(`Service ${i} serialize method should not return a promise`);if(!Sr(r))throw new te(`Service ${i} serialize method should return a pure object.
|
|
20
|
+
Current _ableToAttach: `+this._ableToAttach);let t=v.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){if(this.isSettled())return;let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved?this.children.every(t=>t.isSettled())&&this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},po=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof De?e:new De(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var mo=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new ee}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 v,n=new De(t);return t.registerSkipController(new B(()=>{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 mi(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 Du=4e3,ja={zIndex:0,visibility:"visible"},Lu={...ja,zIndex:1},_a={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function mn(){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 fo(){return{...mn(),visibility:"hidden"}}var ho=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.companions=new Map;this.ownZIndex=new WeakSet;this.overlayHost=null;this.running=null}registerScene(e,t){t?(this.sceneElements.set(e.getId(),t),this.gameState.isSceneSuspended(e)&&Object.assign(t.style,fo()),this.companions.get(e.getId())?.forEach(n=>this.copyPose(e,n))):this.sceneElements.delete(e.getId())}bindCompanion(e,t,n={}){let i=e.getId(),r=this.companions.get(i);return r||(r=new Set,this.companions.set(i,r)),r.add(t),n.keepZIndex?this.ownZIndex.add(t):this.ownZIndex.delete(t),this.copyPose(e,t),()=>{let s=this.companions.get(i);s?.delete(t)&&(s.size||this.companions.delete(i),this.writePose(t,mn()))}}writePose(e,t){if(this.ownZIndex.has(e)&&"zIndex"in t){let n={...t};delete n.zIndex,Object.assign(e.style,n);return}Object.assign(e.style,t)}paintedBy(e){let t=this.sceneElements.get(e),n=this.companions.get(e);return[...t?[t]:[],...n?[...n]:[]]}copyPose(e,t){let n=this.sceneElements.get(e.getId());if(!n){this.writePose(t,this.gameState.isSceneSuspended(e)?fo():mn());return}let i=mn(),r=n.style,s=t.style,a=this.ownZIndex.has(t);Object.keys(i).forEach(l=>{a&&l==="zIndex"||(s[l]=r[l])})}syncScenePose(e,t){if(this.running&&(this.running.roles.from===e||this.running.roles.to===e))return;let n=t?fo():mn();this.paintedBy(e.getId()).forEach(i=>this.writePose(i,n))}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 v().registerSkipController(new B(s.cancel)),l=new De(a),c=[],u=r.resolve.map(f=>{if(typeof f=="function"){let m=this.createOverlay();return c.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(f.key==="target"?t.to:t.from).getId(),role:f.key}}),p={task:r,controller:s,roles:t,targets:u,overlays:c,cancelLoadGate:()=>{},stale:!1};this.running=p,s.onUpdate(f=>this.applyFrame(p,f)),s.onComplete(()=>{this.settle(p,[[t.to,mn()],[t.from,fo()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(p,[[t.from,mn()],[t.to,mn()]]),l.abort()}),this.applyFrame(p,r.animations.map(f=>f.start));let d=this.waitForSceneReady(t.to);return p.cancelLoadGate=d.cancel,d.promise.then(()=>{p.stale||s.start()}),l}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?[r.element]:this.paintedBy(r.sceneId);if(!s.length)return;let a=typeof n=="function"?n:n.resolver,l=r.kind==="overlay"?_a:r.role==="target"?Lu:ja,c=Q({style:l},a(...t));s.forEach(u=>{if(this.ownZIndex.has(u)&&c.style&&"zIndex"in c.style){let p={...c.style};delete p.zIndex,mi(u,{...c,style:p},$a);return}mi(u,c,$a)})})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{this.paintedBy(n.getId()).forEach(r=>this.writePose(r,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,_a),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()},Du)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(Ru)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},Ka=["src","width","height"];function $a(o){if(!Ka.some(t=>t in o))return o;let e={...o};return Ka.forEach(t=>delete e[t]),e}function Ru(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 go=class{constructor(e){this.options=e;this.planned=new Set;this.desired=[];this.admitted=[];this.pending=null;this.pendingTimer=null}retain(e){this.planned=new Set(e),this.desired=e.filter(i=>!this.options.isDeclared(i));let t=!1,n=[];for(let i of this.admitted)this.desired.includes(i)?n.push(i):t=!0;this.admitted=n,this.pending&&!this.admitted.includes(this.pending)&&this.clearPending(),(this.admit()||t)&&this.options.onChange()}noteReady(e){!this.pending||this.pending!==e||(this.clearPending(),this.admit()&&this.options.onChange())}forget(e){let t=this.admitted.indexOf(e);t>=0&&this.admitted.splice(t,1),this.desired=this.desired.filter(n=>n!==e),this.pending===e&&this.clearPending(),this.admit()&&this.options.onChange()}getAdmitted(){return this.admitted}isPlanned(e){return this.planned.has(e)}clear(){this.clearPending(),this.planned=new Set,this.desired=[],this.admitted.length&&(this.admitted=[],this.options.onChange())}admit(){if(this.pending||this.admitted.length>=3)return!1;let e=this.desired.find(t=>!this.admitted.includes(t));return e?(this.admitted.push(e),this.pending=e,this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,this.pending=null,this.admit()&&this.options.onChange()},5e3),!0):!1}clearPending(){this.pendingTimer!==null&&(clearTimeout(this.pendingTimer),this.pendingTimer=null),this.pending=null}};var yo=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=to(6),{action:r,timeline:s,stackModel:a}=e,l=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:l,stackModel:a}),this.history.length>this.maxHistorySize){let c=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(c))}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 vo=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??to(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1,this.resumingAtCursor=this.cursor>=0}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 tn=class tn extends J{executeAction(e,t){if(this.type===he.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===he.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===he.applyLoop){let[n,i]=this.contentNode.getContent();return this.applyLoop(e,this.callee,n,i,t)}else if(this.type===he.stopLoop){let[n]=this.contentNode.getContent();return this.stopLoop(e,this.callee,n,t)}else if(this.type===he.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}else if(this.type===he.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new v().registerSkipController(new B(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t),c=t.transformState.clone(),u=t._getLoop(),p=t._getLoopActionId();u&&(t._setLoop(null,{},null),t.markDirty());let d=l.applyTransform(n,a),f=e.timelines.attachTimeline(s).attachChild(d);return d.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:f},(h,m,g)=>{s.isSettled()||s.abort(),d.abort(),t.transformState.forceOverwrite(h.state),tn.restoreLoop(e,t,m,g)},[c,u,p]),s}applyLoop(e,t,n,i,r){let s=t._getLoop(),a=t._getLoopActionId(),l=i??{};t._setLoop(n,l,this.getId()),t.markDirty(),e.getExposedState(t)?.applyLoop(n,l),e.actionHistory.push({action:this,stackModel:r.stackModel},(u,p)=>{tn.restoreLoop(e,t,u,p)},[s,a]);let c=new v;return c.resolve(super.executeAction(e,r)),c}stopLoop(e,t,n,i){let r=t._getLoop(),s=t._getLoopActionId();t._setLoop(null,{},null),t.markDirty();let a=new v().registerSkipController(new B(()=>(e.logger.info("Displayable Loop","Skipped"),super.executeAction(e,i)))),l=()=>{a.isSettled()||a.resolve(super.executeAction(e,i))},c=e.getExposedState(t);if(!c||!r)return e.actionHistory.push({action:this,stackModel:i.stackModel},(d,f)=>{tn.restoreLoop(e,t,d,f)},[r,s]),l(),a;let u=c.stopLoop(n,l),p=e.timelines.attachTimeline(a).attachChild(u);return u.onCancelled(l),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:p},(d,f)=>{a.isSettled()||a.abort(),u.abort(),tn.restoreLoop(e,t,d,f)},[r,s]),a}static restoreLoop(e,t,n,i){if(!n&&!t._getLoop())return;t._setLoop(n?.transform??null,n?.options??{},i),t.markDirty();let r=e.getExposedState(t);r&&(n?r.applyLoop(n.transform,n.options):r.stopLoop(void 0,()=>{}))}applyTransition(e,t,n,i,r){let s=new v().registerSkipController(new B(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(c);return c.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),c.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let c=e.findElementByDisplayable(this.callee,i);c&&e.disposeDisplayable(n,c.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new v().registerSkipController(new B(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,c=>{c.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let l=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:l},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&tn.getLayerElements(i,t);if(!r)throw new P(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let c=e.findElementByDisplayable(t),u=c&&tn.getLayerElements(c,t);if(!u)return;let p=u.indexOf(t);p!==l&&(u.splice(p,1),u.splice(l,0,t),e.flush())},[s]);let a=new v;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};tn.ActionTypes=he;var Ce=tn;var je=class o extends fe{constructor(){super(...arguments);this.srcManager=new Me;this.loopTransform=null;this.loopOptions={};this.loopActionId=null}_getLoop(){return this.loopTransform?{transform:this.loopTransform,options:this.loopOptions}:null}_setLoop(t,n,i){return this.loopTransform=t,this.loopOptions=t?n:{},this.loopActionId=t?i:null,this}_getLoopActionId(){return this.loopActionId}_serializeLoop(){return this.loopActionId?{actionId:this.loopActionId,options:{...this.loopOptions}}:null}_deserializeLoop(t){return this.loopTransform=null,this.loopOptions=t?{...t.options}:{},this.loopActionId=t?t.actionId:null,this}_rebindLoop(t){if(!this.loopActionId||this.loopTransform)return this;let i=t.get(this.loopActionId)?.contentNode?.getContent(),r=Array.isArray(i)?i[0]:void 0;return r instanceof ie?(this.loopTransform=r,this):this._setLoop(null,{},null)}reset(){super.reset(),this._setLoop(null,{},null)}pos(t,n,i){return this.transform(new ie({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new ie({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new ie({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new ie({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new ie({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new ie({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new ie({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new ie(t,n))}mask(t,n={}){let i=w.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:l,...c}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:l},c)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:l="easeInOut",...c}=t,u={duration:a,ease:l,...c},p=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Fe,d=>d.transform(p).clearClip({duration:0})):this.transform(p)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:l="easeInOut",...c}=t,u={duration:a,ease:l,...c},p=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Fe,d=>d.transform(p).clearClip({duration:0})):this.transform(p)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...l}=t,c={duration:s,ease:a,...l},u=o.wipeClipPath(n,100),p=o.wipeClipPath(n,0),d=o.createClipPathTransform([[i?p:u,{duration:0}],[i?u:p,c]]);return r?this.combineActions(new Fe,f=>f.transform(d).clearClip({duration:0})):this.transform(d)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new Ce(n,he.applyTransform,new x().setContent([t.copy()]));return n.chain(i)}loop(t,n){let i=this.chain(),r=new Ce(i,he.applyLoop,new x().setContent([t.copy(),n]));return i.chain(r)}stopLoop(t){let n=this.chain(),i=new Ce(n,he.stopLoop,new x().setContent([t]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new Ce(t,he.bringToFront,new x().setContent([]));return t.chain(n)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new ie(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof ie?t.copy():new ie({opacity:1},t),r=new Ce(n,he.applyTransform,new x().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof ie?t.copy():new ie({opacity:0},t),r=new Ce(n,he.applyTransform,new x().setContent([i]));return n.chain(r)}};var fn=class fn extends fe{constructor(e,t={}){super(),this.config=Q(fn.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(l=>typeof l=="string")&&[t,...n].length>0&&[t,...n].every(l=>ve.isSingleWord(l))){let l=e,c=ve.format([t,...n]),u=new ve(ya(l,c),{character:this}),p=new rt(this.chain(),rt.ActionTypes.say,new x().setContent(u));return this.chain(p)}let i=t||{},r=e,s=Array.isArray(r)?new ve(r,{...i,character:this}):(ve.isSentence(r)?r:new ve(r,{...i,character:this})).copy();s.setCharacter(this);let a=new rt(this.chain(),rt.ActionTypes.say,new x().setContent(s));return this.chain(a)}setName(e){let t=new rt(this.chain(),rt.ActionTypes.setName,new x().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&ve.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ve.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:fn.StateSerializer.serialize(this.state)}}fromData(e){return this.state=fn.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};fn.defaultCharacterColor="#000",fn.defaultConfig={portraits:[]},fn.StateSerializer=new Xe;var So=fn,nn=new So(null);var Z=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},Rr=class o extends fe{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new He(`ELSE condition already set
|
|
21
|
+
You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:Z.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new He(`ELSE condition already set
|
|
22
|
+
You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(Ht,[this,Ht.ActionTypes.action,new x().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,l=r[s+1]?.contentNode;l&&a.setChild(l),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return Ke.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=Z.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new Ht(i,Ht.ActionTypes.action,new x().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?nn.say(n).getActions():Ke.toActions([n]))}};var wn=class extends J{executeAction(e,t){let n=new v().registerSkipController(new B(()=>{l.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,l=e.createMenu(r,u=>{let p=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[p]}}),a=()=>{p.reset()},e.gameHistory.updateByToken(c,d=>{d&&d.element.type==="menu"&&(d.element.selected=u.evaluated,d.isPending=!1)})}),{id:c}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{l.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:c,action:this,element:{type:"menu",text:l.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(l=>l.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};wn.ActionTypes=ma;var kn=class kn extends fe{constructor(t,n={}){super();this.choices=[];this.prompt=ve.isSentence(t)?t:t===null?null:new ve(t),this.config=Q(kn.defaultConfig,n)}static prompt(t,n={}){return new kn(t!==void 0?t:null,n)}static choose(t,n){return new kn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return ve.isSentence(t)&&n?i.choices.push({prompt:ve.toSentence(t),action:this.narrativeToActions(n),config:{}}):(ae.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:ve.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:ve.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?Z.from(t.config.disabled):void 0,hidden:t.config?.hidden?Z.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new He("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=Z.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new He("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=Z.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:Z.not(Z.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:Z.not(Z.from(t))}})}fromChained(t){return[new wn(this.chain(),wn.ActionTypes.action,new x().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?nn.say(n).getActions():Ke.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??{}}))}};kn.defaultConfig={},kn.targetAction=wn;var Ir=kn;var fi=class fi extends J{executeAction(e,t){let n=this;if(n.is(fi,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let l=s.get(i);s.set(i,r(l))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{s.set(i,l)},[a]),super.executeAction(e,t)}else if(n.is(fi,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(l=>{s[l]=r.get(l),r.set(l,a[l])}),e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{Object.keys(l).forEach(c=>{r.set(c,l[c])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};fi.ActionTypes=oi;var bo=fi;var To=class To extends fe{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new Ut(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(oi.set,[e,t]))}assign(e){return this.chain(this.createAction(oi.assign,[e]))}equals(e,t){return new Z(n=>{let i=n.storable.getNamespace(this.namespace),r=Z.isLambda(t)||Z.isLambdaHandler(t)?Z.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new Z(n=>{let i=n.storable.getNamespace(this.namespace),r=Z.isLambda(t)||Z.isLambdaHandler(t)?Z.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new Z(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new Z(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new Z(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new ae(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new ae(i=>Z.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new Z(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=To.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new bo(this.chain(),e,x.create(t))}};To.NamespacePrefix="persistent";var Wn=To,Ao=class Ao extends Wn{constructor(e){super(e,{}),this.namespace=this.prefix(e,Ao.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new Ut(this.namespace,this.defaultContent))}};Ao.LocalNamespacePrefix="local";var zn=Ao;var vt={shutter:0,shutterColor:"#000",vignette:0,vignetteColor:"#000",vignetteInner:"44%",vignetteOuter:"78%"};function Mr(o){return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(1,o))}function hi(o,e){return typeof o=="string"&&o.length>0?o:e}function qa(o){let e=Mr(o.shutter);return{backgroundColor:hi(o.shutterColor,vt.shutterColor),clipPath:`inset(0 0 ${100-50*e}% 0)`}}function Qa(o){let e=Mr(o.shutter);return{backgroundColor:hi(o.shutterColor,vt.shutterColor),clipPath:`inset(${100-50*e}% 0 0 0)`}}function Ya(o){let e=hi(o.vignetteInner,vt.vignetteInner),t=hi(o.vignetteOuter,vt.vignetteOuter),n=`radial-gradient(circle at center, transparent ${e}, black ${t})`;return{backgroundColor:hi(o.vignetteColor,vt.vignetteColor),opacity:Mr(o.vignette),maskImage:n,WebkitMaskImage:n,maskSize:"100% 100%",WebkitMaskSize:"100% 100%",maskPosition:"50% 50%",WebkitMaskPosition:"50% 50%",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat",maskMode:"alpha"}}var mt=class mt extends je{static get DefaultUserConfig(){return mt._defaultUserConfig??(mt._defaultUserConfig=new $({...se.DefaultTransformState.getDefaultConfig(),opacity:1,...vt}))}constructor(e={}){super();let t=mt.DefaultUserConfig.create(e),n=mt.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}shutter(e,t,n){return this.lens({shutter:mt.clampLens(e)},{duration:t,ease:n})}vignette(e,t,n){return this.lens({vignette:mt.clampLens(e)},{duration:t,ease:n})}lens(e,t){return this.transform(new ie(e,t))}resetCamera(e,t){return this.transform(new ie([{props:{filter:"none"},options:{duration:0}},{props:{position:new ut("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,shutter:vt.shutter,vignette:vt.vignette},options:{duration:e,ease:t}},{props:{shutterColor:vt.shutterColor,vignetteColor:vt.vignetteColor,vignetteInner:vt.vignetteInner,vignetteOuter:vt.vignetteOuter},options:{duration:0}}]))}static clampLens(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}bringToFront(){throw new P(`A camera cannot be brought to front. It is not an element inside a layer, it is what the layers are viewed through, so it has nothing to be in front of \u2014 waiting for it to be added to the stage will not help. Use a camera transform such as Camera.zoom or Camera.pan to change what is in view. (camera: ${this.config.name})`)}reset(){return super.reset(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.transformState.resetTo(se.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}copy(){return new mt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(mt.DefaultUserConfig.keys());return new se(mt.DefaultUserConfig.create(e.get()).get())}};mt._defaultUserConfig=null,mt.DefaultConfig=new $({name:"(camera)"});var gi=mt;var hn=class hn extends Un{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.hashCache=new Map;this.name=t;let{camera:i,...r}=n;this.config=Q(hn.defaultConfig,r),this._camera=i??new gi}static empty(){return new hn("empty").entry(new Je("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 Wn(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 He(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){let n=this.hashCache.get(t);if(n!==void 0)return n;let i=Ca(this.stringify(t));return this.hashCache.set(t,i),i}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(!br(r))throw new ne(`Service ${i} serialize method should return a pure object.
|
|
23
23
|
A pure object should:
|
|
24
24
|
1. be an object literal
|
|
25
25
|
2. not have any prototype
|
|
26
26
|
3. no circular reference
|
|
27
27
|
4. sub objects should also be pure objects or serializable data
|
|
28
28
|
Return null if nothing needs to be saved. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description
|
|
29
|
-
Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(Je.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||
|
|
30
|
-
This should not happen, please report this issue to the developers`);return this._element.state}};var Co=class o extends
|
|
29
|
+
Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(Je.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||ne,[`Scene with name ${t} not found`]);return r}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.hashCache.clear(),this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this.captureElementBaseline(),this.scheduleHashWarmUp(),this}scheduleHashWarmUp(){let t=globalThis.requestIdleCallback;typeof t=="function"&&t(()=>{try{this.hash()}catch{}})}captureElementBaseline(){let t=new Map;this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).forEach(n=>{let i=n.toData();i&&t.set(n.getId(),JSON.stringify(i))}),this.elementBaseline=t}getAllElementStates(){let t=this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]),n=this.elementBaseline,i=[];for(let r of t){if(n&&!r.isDirty())continue;let s=r.toData();s&&(n&&JSON.stringify(s)===n.get(r.getId())||i.push({id:r.getId(),data:s}))}return i}findUnmarkedElements(){let t=this.elementBaseline;return t?this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).filter(n=>{if(n.isDirty())return!1;let i=n.toData();return!!i&&JSON.stringify(i)!==t.get(n.getId())}):[]}constructSceneRoots(t){let n=new Set,i=[],r=0;for(t.constructSceneRoot(this),i.push(t.getSceneRoot());i.length;){if(r++,r>hn.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${hn.MAX_DEPTH})`);let s=i.shift();if(Je.isScene(s.callee)){if(n.has(s.callee))continue;s.callee.isSceneRootConstructed()||s.callee.constructSceneRoot(this),n.add(s.callee)}let a=s.getFutureActions(this,{allowFutureScene:!0});i.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new xo(t).run(this)}};hn.defaultConfig={origin:"bottom left"},hn.MAX_DEPTH=32767;var yi=hn;var gn=class extends J{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===ji.setText){let i=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.text=r},[i]),super.executeAction(e,t)}else if(this.type===ji.setFontSize){let i=this.callee.state.fontSize;this.callee.state.fontSize=this.contentNode.getContent()[0];let r=e.getExposedStateForce(this.callee);return r.flush(),r.updateStyleSync(),e.actionHistory.push(n,s=>{this.callee.state.fontSize=s},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};gn.ActionTypes=ji;var St=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(St||{});import{animate as Iu}from"motion/react";var Bt=class{requestAnimations(e){let t=e.map(m=>m.start),n=[],i=0,r=!1,s=!1,a=!1,l=[],c=[],u=[],p=()=>{e.forEach((m,g)=>{t[g]=m.end}),i=e.length,l.forEach(m=>m(t)),c.forEach(m=>m())};return{onUpdate:m=>(l.push(m),{cancel:()=>{let g=l.indexOf(m);g!==-1&&l.splice(g,1)}}),onComplete:m=>(c.push(m),{cancel:()=>{let g=c.indexOf(m);g!==-1&&c.splice(g,1)}}),onCanceled:m=>(u.push(m),{cancel:()=>{let g=u.indexOf(m);g!==-1&&u.splice(g,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(m=>m.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){p();return}e.forEach((m,g)=>{n.push(this.requestMotion(m,{onComplete:()=>{t[g]=m.end,l.forEach(b=>b(t)),i++,i===e.length&&c.forEach(b=>b())},onUpdate:b=>{t[g]=b,l.forEach(y=>y(t))}}))})}},cancel:()=>{s=!0,n.forEach(m=>m.cancel()),u.forEach(m=>m())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return Iu(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Bt.AnimationType=St;var vi=class extends Bt{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new P(`Trying to access text state, but element is not set
|
|
30
|
+
This should not happen, please report this issue to the developers`);return this._element.state}};var Co=class o extends vi{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var Le=class Le extends je{static get DefaultUserConfig(){return Le._defaultUserConfig??(Le._defaultUserConfig=new $({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...se.DefaultTransformState.getDefaultConfig()},{position:e=>V.tryParsePosition(e)}))}static get DefaultTextTransformState(){return Le._defaultTextTransformState??(Le._defaultTextTransformState=new $({fontColor:"#000000",...se.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=Le.DefaultUserConfig.create(n),r=Le.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new gn(t,gn.ActionTypes.setText,new x().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new ie({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Fe,i=>{if(t){let s=new Co({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new gn(i,gn.ActionTypes.setFontSize,new x().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:Le.StateSerializer.serialize(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.state=Le.StateSerializer.deserialize(e.state),this.transformState.resetTo(se.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_init(e){return new Ce(this.chain(),he.init,new x().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}getInitialTransformState(e){let[t]=e.extract(Le.DefaultTextTransformState.keys());return new se(Le.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Ce(e,he.applyTransition,new x().setContent([t,n=>n._setElement(this)]))}getInitialState(){return Le.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};Le._defaultUserConfig=null,Le.DefaultTextConfig=new $({alignX:"center",alignY:"center",className:"",layer:void 0}),Le.DefaultTextState=new $({fontSize:16,display:!1,text:""}),Le._defaultTextTransformState=null,Le.StateSerializer=new Xe;var Pn=Le;var wo=class extends J{executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(Ee.getCtx({gameState:e}),n,i);return v.isAwaitable(r)?v.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var Nr=class extends fe{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let i=this.chain();return i.chain(this._createAction(i,t,n))}triggerAction(t,n,i){let r=this._handlers[n];if(!r){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(Ta(r)){let s=[],a=new v().registerSkipController(new B(()=>{for(let c of s)c?.()}));return r({...t,onAbort:c=>{s.push(c)}},...i).then(()=>a.resolve()),a}r({...t,onAbort:()=>{}},...i)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,i){return new wo(t,"service:action",new x().setContent([n,i]))}},Gr=class extends Nr{},Si=class extends Gr{};var _n=class extends J{executeAction(e,t){if(this.type===An.action)return super.executeAction(e,t);if(this.type===An.setZIndex){let[n]=this.contentNode.getContent(),i=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.zIndex=r},[i]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};_n.ActionTypes=An;var st=class st extends je{static get DefaultUserConfig(){return st._defaultUserConfig??(st._defaultUserConfig=new $({zIndex:0,...se.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e,t={}){super();let n=st.DefaultUserConfig.create(t),i=st.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState()}include(e){return(Array.isArray(e)?e:[e]).forEach(n=>{n.useLayer(this)}),this}setZIndex(e){return this.chain(new _n(this.chain(),An.setZIndex,new x().setContent([e])))}bringToFront(){throw new P(`A layer cannot be brought to front. Layers are ordered by z-index, not by the order they were added in \u2014 use Layer.setZIndex to raise one. (layer: ${this.config.name})`)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{state:st.StateSerializer.serialize(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.state=st.StateSerializer.deserialize(e.state),this.transformState.resetTo(se.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}copy(){return new st(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new _n(this.chain(),An.action,new x),new Ce(this.chain(),he.init,new x().setContent([e,null,!1]))]}getInitialState(){return st.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(se.DefaultTransformState.keys());return new se(se.DefaultTransformState.create(e.get()).get())}};st._defaultUserConfig=null,st.DefaultConfig=new $({name:"(anonymous)",zIndex:0}),st.StateSerializer=new Xe,st.DefaultState=new $({zIndex:0});var Kn=st;var bt=class bt extends J{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(bt,"video:preload"))return e.isVideoAdded(i)?v.resolve(super.executeAction(e,t)):(e.addVideo(i),e.stage.update(),e.actionHistory.push(r,()=>{e.isVideoAdded(i)&&(e.removeVideo(i),e.stage.update())}),v.resolve(super.executeAction(e,t)));if(n.is(bt,"video:play"))return e.reportUnwarmedVideo(i),this.changeStateAsync(e,s=>s.play(),t);if(n.is(bt,"video:pause"))return e.isVideoOnStage(i)?this.changeState(e,s=>s.pause(),t):this.skipOffStage(e,t,"Pausing");if(n.is(bt,"video:stop"))return e.isVideoOnStage(i)?this.changeState(e,s=>s.stop(),t):this.skipOffStage(e,t,"Stopping");if(n.is(bt,"video:seek"))return e.isVideoOnStage(i)?this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t):this.skipOffStage(e,t,"Seeking");if(n.is(bt,"video:show")){let[s]=n.contentNode.getContent(),a=i.state.display,l=e.getVideoOwner(i);if(e.reportUnwarmedVideo(i),!e.isVideoAdded(i))e.addVideo(i),e.stage.update();else{let u=e.getLastScene();u&&u!==l&&(e.setVideoOwner(i,u),e.stage.update())}let c=u=>{i.state.display=u,l&&e.getVideoOwner(i)!==l&&(e.setVideoOwner(i,l),e.stage.update())};return bt.fades(s)?(e.actionHistory.push(r,c,[a]),this.changeStateFading(e,async u=>{i.state.display=!0,await u.show(s)},t)):(i.state.display=!0,e.actionHistory.push(r,c,[a]),this.changeState(e,u=>u.show(),t))}else if(n.is(bt,"video:hide")){if(!e.isVideoOnStage(i))return e.logger.weakWarn("NarraLeaf-React: Video","Hiding a video that is not on the stage, ignored. (src: "+i.config.src+")"),v.resolve(super.executeAction(e,t));let[s]=n.contentNode.getContent(),a=i.state.display,l=e.isVideoAdded(i),c=e.getVideoOwner(i),u=()=>{i.state.display=!1,e.actionHistory.push(r,p=>{i.state.display=p,l&&!e.isVideoAdded(i)&&(e.addVideoFor(i,c??e.getLastScene()),e.stage.update())},[a])};return bt.fades(s)?this.changeStateFading(e,async(p,d)=>{await p.hide(s),!d.aborted&&(u(),e.removeVideo(i),e.stage.update())},t):this.changeState(e,p=>{u(),p.hide(),e.removeVideo(i),e.stage.update()},t)}else if(n.is(bt,"video:resume"))return e.isVideoOnStage(i)?this.changeState(e,s=>s.resume(),t):this.skipOffStage(e,t,"Resuming");throw this.unknownTypeError()}skipOffStage(e,t,n){return e.logger.weakWarn("NarraLeaf-React: Video",n+" a video that is not on the stage, ignored. (src: "+this.callee.config.src+")"),v.resolve(super.executeAction(e,t))}changeStateBase(e,t,n){if(!e.isVideoOnStage(this.callee))throw new P(`Video is being used before it is added to the game
|
|
31
31
|
Use video.show() to add the video to the game`);let i=this.callee,r=new v,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new B(s.cancel)),r}changeStateFading(e,t,n){if(!e.isVideoOnStage(this.callee))throw new P(`Video is being used before it is added to the game
|
|
32
|
-
Use video.show() to add the video to the game`);let i=this.callee,r=new v,s={aborted:!1},a=null,l=e.getExposedStateAsync(i,async c=>{a=c,await t(c,s),s.aborted||r.resolve(super.executeAction(e,n))});return r.registerSkipController(new B(()=>{s.aborted=!0,l.cancel(),a?.cancelFade()})),r}static fades(e){return typeof e?.duration=="number"&&e.duration>0}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};bt.ActionTypes=Dt;var
|
|
33
|
-
Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new v,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Vfx Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new B(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VfxAction")}};on.ActionTypes=Zt;var ko=on;var jn=class jn extends me{constructor(e){super();let t=jn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new te("Vfx must have a src")}preload(){return this.chain(this.createAction(Zt.preload,[]))}show(e){return this.chain(this.createAction(Zt.show,[e]))}hide(e){return this.chain(this.createAction(Zt.hide,[e]))}pause(){return this.chain(this.createAction(Zt.pause,[]))}resume(){return this.chain(this.createAction(Zt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Zt.setRate,[e]))}toData(){return{state:{display:this.state.display,paused:this.state.paused}}}fromData(e){let{state:t}=e;return this.state={display:t.display,paused:t.paused},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return jn.DefaultVfxState.create().get()}createAction(e,t){return new ko(this.chain(),e,A.create(t))}};jn.DefaultVfxConfig=new $({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),jn.DefaultVfxState=new $({display:!1,paused:!1});var Or=jn;var vi=class extends X{executeAction(e,t){if(this.type===nt.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===nt.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===nt.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===nt.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===nt.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===nt.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let l=new v().registerSkipController(new B(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{l.isSettled()||l.resolve(super.executeAction(e,t))});let c=e.timelines.attachTimeline(l);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:c},()=>{l.isSettled()||l.abort()}),l}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};vi.ActionTypes=nt;var Ue=class Ue extends je{constructor(t){super();this.events=new Z;this.instance=null;this.status="unmounted";let n=Ue.DefaultUserConfig.create(t),i=Ue.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new te("Puppet must have a backend name");if(!this.config.src)throw new te("Puppet must have a src")}static get DefaultUserConfig(){return Ue._defaultUserConfig??(Ue._defaultUserConfig=new $({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...re.DefaultTransformState.getDefaultConfig()},{position:t=>V.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:Ue.copyParams(n.params),slots:Ue.copySlots(n.slots)}}static mergeState(t,n){return Ue.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(nt.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(nt.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(nt.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(nt.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(nt.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(nt.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:Ue.normalizeState(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(t){return this.state=Ue.normalizeState(t.state),this.transformState.resetTo(re.deserialize(t.transformState).get()),this._deserializeLoop(t.loop),this}_init(t){return new xe(this.chain(),fe.init,new A().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=Ue.normalizeState(this.state);return this.state=Ue.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(Ue.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new vi(this.chain(),t,A.create(n))}getInitialTransformState(t){let[n]=t.extract(re.DefaultTransformState.keys());return new re(re.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return Ue.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};Ue._defaultUserConfig=null,Ue.DefaultPuppetConfig=new $({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var Rt=Ue;var Si=class extends me{constructor(e){super(),this.scene=e}show(e){let t=new oe(this.scene.chain(),z.nvlShow,new A().setContent([e]));return this.chain(t)}hide(e){let t=new oe(this.scene.chain(),z.nvlHide,new A().setContent([e]));return this.chain(t)}end(){let e=new oe(this.scene.chain(),z.nvlEnd,new A().setContent([]));return this.chain(e)}};function Vr(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function Ya(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return Qa(o);let i=Fr(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=Fr(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=Fr(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function Fr(o,e){if(o===!1||typeof o>"u")return{resolved:!1,source:null};if(typeof o=="function"){let t=o(e);return{resolved:typeof t<"u",source:t??null}}return{resolved:!0,source:o}}function Qa(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function Xa(o,e){let t=[],n=i=>{i&&typeof i!="function"&&k.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(Vr(i).avatar);return t}var pe=class pe{constructor(e,t){this.state={sounds:[],videos:[],vfx:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new oi;this.videoOwners=new Map;this.videoMissingReporter=null;this.reportedUnwarmedVideos=new Set;this.htmlToImage=Pu;this.imageCache=null;this.pageRouter=null;this.stageClickBuffer=null;this.advanceSuspensions=new Set;this.nvlAdvanceWaiters=new Map;this.advDialogState=null;this._fastForwarding=!1;this.stage=t,this.game=e,this.events=new Z,this.logger=new so(e,"NarraLeaf-React"),this.audioManager=new ao(this),this.guard=new lo(e.config.app.guard).observe(this),this.timelines=new co(this.guard),this.notificationMgr=new uo(this,[]),this.idManager=new qi,this.actionHistory=new go(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new yo(this.actionHistory),this.stageTransition=new fo(this),this.videoWarmQueue=new ho({isDeclared:n=>this.state.videos.includes(n),onChange:()=>this.stage.update()}),this.events.on(pe.EventTypes["event.state.onExpose"],n=>{this.videoWarmQueue.noteReady(n)}),this.events.on(pe.EventTypes["event:state.player.skip"],()=>{this.game.config.allowSkipSceneTransition&&this.stageTransition.skip()})}get deps(){return this.flushDep}addVideo(e){return this.addVideoFor(e,this.getLastScene())}addVideoFor(e,t){return this.state.videos.push(e),t&&this.videoOwners.set(e,t),this.videoWarmQueue.forget(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this.videoOwners.delete(e),this)}getVideoOwner(e){return this.videoOwners.get(e)??null}setVideoOwner(e,t){return this.isVideoAdded(e)&&this.videoOwners.set(e,t),this}getVideosOf(e){return this.state.videos.filter(t=>this.videoOwners.get(t)===e)}isVideoAdded(e){return this.state.videos.includes(e)}isVideoOnStage(e){return this.state.videos.includes(e)||this.videoWarmQueue.getAdmitted().includes(e)}getVideos(){let e=this.videoWarmQueue.getAdmitted();return e.length?[...this.state.videos,...e.filter(t=>!this.state.videos.includes(t))]:this.state.videos}retainWarmVideos(e){return this.videoWarmQueue.retain(e),this}useVideoMissingReporter(e){return this.videoMissingReporter=e,this}reportUnwarmedVideo(e){let t=e.config.src;return!this.videoMissingReporter||!t||this.reportedUnwarmedVideos.has(t)?this:this.videoWarmQueue.isPlanned(e)||this.isVideoOnStage(e)?this:(this.reportedUnwarmedVideos.add(t),this.videoMissingReporter({type:"video",src:t}),this)}addVfx(e){return this.state.vfx.push(e),this}removeVfx(e){let t=this.state.vfx.indexOf(e);return t===-1?(this.logger.weakWarn("Vfx not found when removing",e.getId()),this):(this.state.vfx.splice(t,1),this)}isVfxAdded(e){return this.state.vfx.includes(e)}getVfx(){return this.state.vfx}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=Je.isScene(e)?e:e.entryScene;if(!t)throw new P("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(pe.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}getImageCache(){return this.imageCache}setImageCache(e){return this.imageCache=e,this}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}settlePendingLines(e){let t=this.findElementByScene(e);return!t||!t.texts.length?this:([...t.texts].forEach(n=>n.onClick()),this)}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){for(let e=this.state.elements.length-1;e>=0;e--){let t=this.state.elements[e];if(!t.suspended)return t.scene}return null}setSceneSuspended(e,t){let n=this.findElementByScene(e);return n?(n.suspended=t,this.stageTransition.syncScenePose(e,t),this.logger.debug("GameState",t?"Suspending scene":"Resuming scene",e.getId()),this.stage.update(),this):(this.logger.weakWarn("Scene not found when suspending",e.getId()),this)}isSceneSuspended(e){return this.findElementByScene(e)?.suspended===!0}getSuspendedScenes(){return this.state.elements.filter(e=>e.suspended).map(e=>e.scene)}getCurrentScene(){return this.state.elements[0]?.scene||null}isFastForwarding(){return this._fastForwarding}setFastForwarding(e){this._fastForwarding=e}hasActiveMenu(){let e=this.getLastScene();return e?(this.findElementByScene(e)?.menus.length??0)>0:!1}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map(Vr);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let l=s[a];for(let c=l.length-1;c>=0;c--){let u=l[c],p=r.get(u);if(p&&this.isDisplayableVisible(u))return p}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(Ee.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Wt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:se.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let l=r.indexOf(a);l!==-1&&r.splice(l,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let l=r.indexOf(a);l!==-1&&r.splice(l,1)},text:se.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(Ee.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(Wt.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?se.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(pe.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(pe.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(pe.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(pe.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(pe.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(pe.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(pe.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>oe.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(pe.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(pe.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(pe.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(pe.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{oe.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this.rebindLoops(),this}rebindLoops(){let[e,t]=this.getLiveGame().constructMaps();return t.forEach(n=>{n instanceof je&&n._rebindLoop(e)}),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(pe.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(pe.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}beginAdvDialog(e,t){return this.advDialogState={dialogId:e,actionId:t,ended:!1},this.events.emit(pe.EventTypes["event:state.dialog.change"]),this}completeAdvDialogTyping(e){return!e||!this.advDialogState||this.advDialogState.dialogId!==e?this:(this.advDialogState.ended||(this.advDialogState.ended=!0,this.events.emit(pe.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(pe.EventTypes["event:state.dialog.change"])),this}getAdvDialogState(){return this.advDialogState}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}suspendAdvance(){let e=Symbol("advance-suspension");return this.advanceSuspensions.add(e),()=>{this.advanceSuspensions.delete(e)}}isAdvanceSuspended(){return this.advanceSuspensions.size>0}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new P(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.videoOwners=new Map,this.videoWarmQueue.clear(),this.reportedUnwarmedVideos.clear(),this.state.vfx=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Ja.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new P("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=De.proxy(v.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof je&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(ne.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync(),"flush"in r&&r.flush()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new ke("State already mounted");if(!e)throw new ke("Invalid state key");return this.exposedState.set(e,t),this.events.emit(pe.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new P("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=null,i=!1,r=null,s=()=>{if(n=null,i)return;let l=this.getExposedState(e);l&&(i=!0,r?.cancel(),t(l))},a=()=>{n?.(),n=Ba(s)};return this.getExposedState(e)&&a(),r=this.events.on(pe.EventTypes["event.state.onExpose"],l=>{l===e&&!i&&a()}),{cancel:()=>{r?.cancel(),n?.()}}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>{let t=this.getVideosOf(e.scene).map(n=>n.getId());return{sceneId:e.scene.getId(),...e.suspended?{suspended:!0}:{},elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([n,i])=>[n.getId(),i.map(r=>r.getId())])),...t.length?{videos:t}:{}}}}),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),vfx:this.state.vfx.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e,a=new Set(r.sounds.map(([c])=>c)),l=new Map;if(i.forEach(({sceneId:c,elements:u,suspended:p})=>{this.logger.debug("Loading scene: "+c);let d=t.get(c);if(!d)throw new P("Scene not found, id: "+c+`
|
|
34
|
-
NarraLeaf cannot find the element with the id from the saved game`);(
|
|
35
|
-
NarraLeaf cannot find the element with the id from the saved game`);return
|
|
32
|
+
Use video.show() to add the video to the game`);let i=this.callee,r=new v,s={aborted:!1},a=null,l=e.getExposedStateAsync(i,async c=>{a=c,await t(c,s),s.aborted||r.resolve(super.executeAction(e,n))});return r.registerSkipController(new B(()=>{s.aborted=!0,l.cancel(),a?.cancelFade()})),r}static fades(e){return typeof e?.duration=="number"&&e.duration>0}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};bt.ActionTypes=Dt;var ko=bt;var $n=class $n extends fe{constructor(e){super();let t=$n.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ne("Video must have a src")}preload(){return this.chain(this.createAction(Dt.preload,[]))}show(e){return this.chain(this.createAction(Dt.show,[e]))}hide(e){return this.chain(this.createAction(Dt.hide,[e]))}play(){return this.chain(this.createAction(Dt.play,[]))}pause(){return this.chain(this.createAction(Dt.pause,[]))}resume(){return this.chain(this.createAction(Dt.resume,[]))}stop(){return this.chain(this.createAction(Dt.stop,[]))}seek(e){return this.chain(this.createAction(Dt.seek,[e]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return $n.DefaultVideoState.create().get()}createAction(e,t){return new ko(this.chain(),e,x.create(t))}};$n.DefaultVideoConfig=new $({src:"",muted:!1}),$n.DefaultVideoState=new $({display:!1});var Or=$n;var on=class on extends J{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(on,"vfx:preload"))return e.isVfxAdded(i)?v.resolve(super.executeAction(e,t)):(e.addVfx(i),e.stage.update(),e.actionHistory.push(r,()=>{e.isVfxAdded(i)&&(e.removeVfx(i),e.stage.update())}),v.resolve(super.executeAction(e,t)));if(n.is(on,"vfx:show")){let[s]=n.contentNode.getContent(),a=i.state.display,l=e.getVfxOwner(i);if(!e.isVfxAdded(i))e.addVfx(i),e.stage.update();else{let c=e.getLastScene();c&&c!==l&&(e.setVfxOwner(i,c),e.stage.update())}return i.state.display=!0,e.actionHistory.push(r,c=>{i.state.display=c,l&&e.getVfxOwner(i)!==l&&(e.setVfxOwner(i,l),e.stage.update())},[a]),this.changeStateAsync(e,c=>c.show(s),t)}else if(n.is(on,"vfx:hide")){if(!e.isVfxAdded(i)||!i.state.display)return e.logger.weakWarn("NarraLeaf-React: Vfx","Hiding a Vfx that is not shown, ignored. (src: "+i.config.src+")"),v.resolve(super.executeAction(e,t));let[s]=n.contentNode.getContent(),a=i.state.display;return this.changeStateAsync(e,async l=>{await l.hide(s),i.state.display=!1,e.actionHistory.push(r,c=>{i.state.display=c},[a])},t)}else{if(n.is(on,"vfx:pause"))return e.isVfxAdded(i)?this.changeState(e,s=>{i.state.paused=!0,s.pause()},t):this.skipOffStage(e,t,"Pausing");if(n.is(on,"vfx:resume"))return e.isVfxAdded(i)?this.changeState(e,s=>{i.state.paused=!1,s.resume()},t):this.skipOffStage(e,t,"Resuming");if(n.is(on,"vfx:setRate"))return e.isVfxAdded(i)?this.changeState(e,s=>s.setRate(n.contentNode.getContent()[0]),t):this.skipOffStage(e,t,"Setting the rate of")}throw this.unknownTypeError()}skipOffStage(e,t,n){return e.logger.weakWarn("NarraLeaf-React: Vfx",n+" a Vfx that is not on the stage, ignored. (src: "+this.callee.config.src+")"),v.resolve(super.executeAction(e,t))}changeStateBase(e,t,n){if(!e.isVfxAdded(this.callee))throw new P(`Vfx is being used before it is added to the game
|
|
33
|
+
Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new v,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Vfx Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new B(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VfxAction")}};on.ActionTypes=Zt;var Po=on;var jn=class jn extends fe{constructor(e){super();let t=jn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ne("Vfx must have a src")}preload(){return this.chain(this.createAction(Zt.preload,[]))}show(e){return this.chain(this.createAction(Zt.show,[e]))}hide(e){return this.chain(this.createAction(Zt.hide,[e]))}pause(){return this.chain(this.createAction(Zt.pause,[]))}resume(){return this.chain(this.createAction(Zt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Zt.setRate,[e]))}toData(){return{state:{display:this.state.display,paused:this.state.paused}}}fromData(e){let{state:t}=e;return this.state={display:t.display,paused:t.paused},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return jn.DefaultVfxState.create().get()}createAction(e,t){return new Po(this.chain(),e,x.create(t))}};jn.DefaultVfxConfig=new $({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),jn.DefaultVfxState=new $({display:!1,paused:!1});var Vr=jn;var bi=class extends J{executeAction(e,t){if(this.type===nt.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===nt.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===nt.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===nt.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===nt.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===nt.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let l=new v().registerSkipController(new B(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{l.isSettled()||l.resolve(super.executeAction(e,t))});let c=e.timelines.attachTimeline(l);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:c},()=>{l.isSettled()||l.abort()}),l}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};bi.ActionTypes=nt;var Ue=class Ue extends je{constructor(t){super();this.events=new ee;this.instance=null;this.status="unmounted";let n=Ue.DefaultUserConfig.create(t),i=Ue.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new ne("Puppet must have a backend name");if(!this.config.src)throw new ne("Puppet must have a src")}static get DefaultUserConfig(){return Ue._defaultUserConfig??(Ue._defaultUserConfig=new $({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...se.DefaultTransformState.getDefaultConfig()},{position:t=>V.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:Ue.copyParams(n.params),slots:Ue.copySlots(n.slots)}}static mergeState(t,n){return Ue.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(nt.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(nt.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(nt.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(nt.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(nt.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(nt.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:Ue.normalizeState(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(t){return this.state=Ue.normalizeState(t.state),this.transformState.resetTo(se.deserialize(t.transformState).get()),this._deserializeLoop(t.loop),this}_init(t){return new Ce(this.chain(),he.init,new x().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=Ue.normalizeState(this.state);return this.state=Ue.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(Ue.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new bi(this.chain(),t,x.create(n))}getInitialTransformState(t){let[n]=t.extract(se.DefaultTransformState.keys());return new se(se.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return Ue.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};Ue._defaultUserConfig=null,Ue.DefaultPuppetConfig=new $({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var Rt=Ue;var Ti=class extends fe{constructor(e){super(),this.scene=e}show(e){let t=new re(this.scene.chain(),W.nvlShow,new x().setContent([e]));return this.chain(t)}hide(e){let t=new re(this.scene.chain(),W.nvlHide,new x().setContent([e]));return this.chain(t)}end(){let e=new re(this.scene.chain(),W.nvlEnd,new x().setContent([]));return this.chain(e)}};function Hr(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function Ja(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return Xa(o);let i=Fr(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=Fr(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=Fr(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function Fr(o,e){if(o===!1||typeof o>"u")return{resolved:!1,source:null};if(typeof o=="function"){let t=o(e);return{resolved:typeof t<"u",source:t??null}}return{resolved:!0,source:o}}function Xa(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function Za(o,e){let t=[],n=i=>{i&&typeof i!="function"&&w.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(Hr(i).avatar);return t}var de=class de{constructor(e,t){this.state={sounds:[],videos:[],vfx:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new ri;this.videoOwners=new Map;this.vfxOwners=new Map;this.videoMissingReporter=null;this.reportedUnwarmedVideos=new Set;this.htmlToImage=Mu;this.imageCache=null;this.pageRouter=null;this.stageClickBuffer=null;this.advanceSuspensions=new Set;this.nvlAdvanceWaiters=new Map;this.advDialogState=null;this._fastForwarding=!1;this.stage=t,this.game=e,this.events=new ee,this.logger=new lo(e,"NarraLeaf-React"),this.audioManager=new co(this),this.guard=new uo(e.config.app.guard).observe(this),this.timelines=new po(this.guard),this.notificationMgr=new mo(this,[]),this.idManager=new Yi,this.actionHistory=new yo(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new vo(this.actionHistory),this.stageTransition=new ho(this),this.videoWarmQueue=new go({isDeclared:n=>this.state.videos.includes(n),onChange:()=>this.stage.update()}),this.events.on(de.EventTypes["event.state.onExpose"],n=>{this.videoWarmQueue.noteReady(n)}),this.events.on(de.EventTypes["event:state.player.skip"],()=>{this.game.config.allowSkipSceneTransition&&this.stageTransition.skip()})}get deps(){return this.flushDep}addVideo(e){return this.addVideoFor(e,this.getLastScene())}addVideoFor(e,t){return this.state.videos.push(e),t&&this.videoOwners.set(e,t),this.videoWarmQueue.forget(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this.videoOwners.delete(e),this)}getVideoOwner(e){return this.videoOwners.get(e)??null}setVideoOwner(e,t){return this.isVideoAdded(e)&&this.videoOwners.set(e,t),this}getVideosOf(e){return this.state.videos.filter(t=>this.videoOwners.get(t)===e)}isVideoAdded(e){return this.state.videos.includes(e)}isVideoOnStage(e){return this.state.videos.includes(e)||this.videoWarmQueue.getAdmitted().includes(e)}getVideos(){let e=this.videoWarmQueue.getAdmitted();return e.length?[...this.state.videos,...e.filter(t=>!this.state.videos.includes(t))]:this.state.videos}retainWarmVideos(e){return this.videoWarmQueue.retain(e),this}useVideoMissingReporter(e){return this.videoMissingReporter=e,this}reportUnwarmedVideo(e){let t=e.config.src;return!this.videoMissingReporter||!t||this.reportedUnwarmedVideos.has(t)?this:this.videoWarmQueue.isPlanned(e)||this.isVideoOnStage(e)?this:(this.reportedUnwarmedVideos.add(t),this.videoMissingReporter({type:"video",src:t}),this)}addVfx(e){return this.addVfxFor(e,this.getLastScene())}addVfxFor(e,t){return this.state.vfx.push(e),t&&this.vfxOwners.set(e,t),this}removeVfx(e){let t=this.state.vfx.indexOf(e);return t===-1?(this.logger.weakWarn("Vfx not found when removing",e.getId()),this):(this.state.vfx.splice(t,1),this.vfxOwners.delete(e),this)}getVfxOwner(e){return this.vfxOwners.get(e)??null}setVfxOwner(e,t){return this.isVfxAdded(e)&&this.vfxOwners.set(e,t),this}getVfxOf(e){return this.state.vfx.filter(t=>this.vfxOwners.get(t)===e)}isVfxAdded(e){return this.state.vfx.includes(e)}getVfx(){return this.state.vfx}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=Je.isScene(e)?e:e.entryScene;if(!t)throw new P("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(de.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}getImageCache(){return this.imageCache}setImageCache(e){return this.imageCache=e,this}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}settlePendingLines(e){let t=this.findElementByScene(e);return!t||!t.texts.length?this:([...t.texts].forEach(n=>n.onClick()),this)}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){for(let e=this.state.elements.length-1;e>=0;e--){let t=this.state.elements[e];if(!t.suspended)return t.scene}return null}setSceneSuspended(e,t){let n=this.findElementByScene(e);return n?(n.suspended=t,this.stageTransition.syncScenePose(e,t),this.logger.debug("GameState",t?"Suspending scene":"Resuming scene",e.getId()),this.stage.update(),this):(this.logger.weakWarn("Scene not found when suspending",e.getId()),this)}isSceneSuspended(e){return this.findElementByScene(e)?.suspended===!0}getSuspendedScenes(){return this.state.elements.filter(e=>e.suspended).map(e=>e.scene)}getCurrentScene(){return this.state.elements[0]?.scene||null}isFastForwarding(){return this._fastForwarding}setFastForwarding(e){this._fastForwarding=e}hasActiveMenu(){let e=this.getLastScene();return e?(this.findElementByScene(e)?.menus.length??0)>0:!1}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map(Hr);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let l=s[a];for(let c=l.length-1;c>=0;c--){let u=l[c],p=r.get(u);if(p&&this.isDisplayableVisible(u))return p}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(Ee.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Wt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:ae.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let l=r.indexOf(a);l!==-1&&r.splice(l,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let l=r.indexOf(a);l!==-1&&r.splice(l,1)},text:ae.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(Ee.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(Wt.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?ae.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(de.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(de.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(de.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(de.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>re.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(de.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(de.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{re.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this.rebindLoops(),this}rebindLoops(){let[e,t]=this.getLiveGame().constructMaps();return t.forEach(n=>{n instanceof je&&n._rebindLoop(e)}),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(de.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(de.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}beginAdvDialog(e,t){return this.advDialogState={dialogId:e,actionId:t,ended:!1},this.events.emit(de.EventTypes["event:state.dialog.change"]),this}completeAdvDialogTyping(e){return!e||!this.advDialogState||this.advDialogState.dialogId!==e?this:(this.advDialogState.ended||(this.advDialogState.ended=!0,this.events.emit(de.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(de.EventTypes["event:state.dialog.change"])),this}getAdvDialogState(){return this.advDialogState}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}suspendAdvance(){let e=Symbol("advance-suspension");return this.advanceSuspensions.add(e),()=>{this.advanceSuspensions.delete(e)}}isAdvanceSuspended(){return this.advanceSuspensions.size>0}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new P(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.videoOwners=new Map,this.videoWarmQueue.clear(),this.reportedUnwarmedVideos.clear(),this.state.vfx=[],this.vfxOwners=new Map,this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return el.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new P("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=De.proxy(v.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof je&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(ie.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync(),"flush"in r&&r.flush()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new ke("State already mounted");if(!e)throw new ke("Invalid state key");return this.exposedState.set(e,t),this.events.emit(de.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new P("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=null,i=!1,r=null,s=()=>{if(n=null,i)return;let l=this.getExposedState(e);l&&(i=!0,r?.cancel(),t(l))},a=()=>{n?.(),n=Wa(s)};return this.getExposedState(e)&&a(),r=this.events.on(de.EventTypes["event.state.onExpose"],l=>{l===e&&!i&&a()}),{cancel:()=>{r?.cancel(),n?.()}}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>{let t=this.getVideosOf(e.scene).map(i=>i.getId()),n=this.getVfxOf(e.scene).map(i=>i.getId());return{sceneId:e.scene.getId(),...e.suspended?{suspended:!0}:{},elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([i,r])=>[i.getId(),r.map(s=>s.getId())])),...t.length?{videos:t}:{},...n.length?{vfx:n}:{}}}}),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),vfx:this.state.vfx.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e,a=new Set(r.sounds.map(([u])=>u)),l=new Map,c=new Map;if(i.forEach(({sceneId:u,elements:p,suspended:d})=>{this.logger.debug("Loading scene: "+u);let f=t.get(u);if(!f)throw new P("Scene not found, id: "+u+`
|
|
34
|
+
NarraLeaf cannot find the element with the id from the saved game`);(p.videos??[]).forEach(m=>l.set(m,f)),(p.vfx??[]).forEach(m=>c.set(m,f));let h={scene:f,layers:this.constructLayerMap(p.layers,t),menus:[],texts:[],suspended:d===!0};this.state.elements.push(h),this.registerSrcManager(f.srcManager),h.suspended||this.getExposedStateAsync(f,m=>{let g=f.state.backgroundMusic;g&&a.has(g.getId())||re.initBackgroundMusic(f,m,this)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([u,p])=>{let d=t.get(u);if(!d)throw new P("Video not found, id: "+u+`
|
|
35
|
+
NarraLeaf cannot find the element with the id from the saved game`);return d.fromData(p),d}),this.videoOwners=new Map,this.state.videos.length){let u=this.getLastScene();this.state.videos.forEach(p=>{let d=l.get(p.getId())??u;d&&this.videoOwners.set(p,d)})}if(this.state.vfx=(e.vfx??[]).flatMap(([u,p])=>{let d=t.get(u);return d?(d.fromData(p),[d]):(this.logger.weakWarn("NarraLeaf-React: Vfx","Vfx not found when loading a saved game, skipped. (id: "+u+")"),[])}),this.vfxOwners=new Map,this.state.vfx.length){let u=this.getLastScene();this.state.vfx.forEach(p=>{let d=c.get(p.getId())??u;d&&this.vfxOwners.set(p,d)})}if(e.nvlState){let u=(e.nvlState.dialogs||[]).map(p=>{let d=p.characterId&&t.get(p.characterId)||null,f=p.text||"";return{id:p.id,actionId:p.actionId||p.id,character:d,sentence:new ve(f,{character:d}),text:f}});this.nvlState={active:e.nvlState.active,visible:e.nvlState.visible,sessionId:e.nvlState.sessionId,dialogs:u,options:e.nvlState.options||null,activeDialogId:e.nvlState.activeDialogId||null,phase:e.nvlState.phase||(e.nvlState.activeDialogId?"awaitAdvance":"idle"),pendingAdvance:e.nvlState.pendingAdvance||!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active&&this.events.emit(de.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(de.EventTypes["event:state.nvl.visibilityChange"],!0,this.nvlState.options?.showTransition),this.emitNvlStateChange()}}getLastSceneIfNot(e){let t=e||this.getLastScene();if(!t||!this.sceneExists(t))throw new P('Scene not found, please call "scene.activate()" first.');return t}createElementSnapshot(e){return{scene:e.scene,suspended:e.suspended===!0,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(i=>[i,i.toData()])])),videos:this.getVideosOf(e.scene).map(t=>[t,t.toData()]),vfx:this.getVfxOf(e.scene).map(t=>[t,t.toData()])}}fromElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(([i,r])=>(i.fromData(r),i))])),texts:[],menus:[]}}removeElements(e){let t=this.state.elements.findIndex(n=>n.scene===e);return t===-1?(this.logger.weakWarn("Scene not found when removing elements",e.getId()),this):(this.resetLayers(this.state.elements[t].layers),this.releaseVideosOf(e),this.releaseVfxOf(e),this.state.elements.splice(t,1),this.logger.debug("GameState","Removing elements",e.getId()),this)}resetLayers(e){let t=this.getLiveGame().story?.camera??null;e.forEach((n,i)=>{i.reset(),n.forEach(r=>{t&&r===t||r.reset()})})}releaseVideosOf(e){let t=this.getVideosOf(e);t.length&&t.forEach(n=>{this.removeVideo(n),n.reset()})}restoreVideosOf(e,t){return t?.length?(t.forEach(([n,i])=>{n.fromData(i),this.isVideoAdded(n)?this.videoOwners.set(n,e):this.addVideoFor(n,e)}),this):this}releaseVfxOf(e){let t=this.getVfxOf(e);t.length&&t.forEach(n=>{this.removeVfx(n),n.reset()})}restoreVfxOf(e,t){return t?.length?(t.forEach(([n,i])=>{n.fromData(i),this.isVfxAdded(n)?this.vfxOwners.set(n,e):this.addVfxFor(n,e)}),this):this}syncNvlDerivedState(){this.nvlState.isTyping=this.nvlState.phase==="typing",this.nvlState.activeDialogId||(this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.nvlState.isTyping=!1)}emitNvlStateChange(){this.syncNvlDerivedState(),this.events.emit(de.EventTypes["event:state.nvl.change"],this.getNvlState()),this.stage.update()}resolveNvlAdvance(e){let t=this.nvlAdvanceWaiters.get(e);return t?(this.nvlAdvanceWaiters.delete(e),this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),t(),!0):!1}isDisplayableVisible(e){return(e.transformState.get().opacity??0)>0}createWaitableAction(e,t){return{action:e,onClick:(i=>{t&&t(i)})}}sceneNotFound(){return new P("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new P("Layer not found, target layer may not be activated. You may forget to add the layer to the scene config")}constructLayerMap(e,t){return new Map(Object.entries(e).map(([n,i])=>{let r=t.get(n);if(!r)throw new P("Layer not found, id: "+n+`
|
|
36
36
|
NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new P("Displayable not found, id: "+s+`
|
|
37
37
|
NarraLeaf cannot find the element with the id from the saved game
|
|
38
|
-
This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};
|
|
39
|
-
To prevent unintended behavior and unexpected results, the sound have to be on the voice bus (or any bus beneath it). Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Re}static getOwnedSounds(t){let n=[],i=t.callee;if(Re.isScene(i)){let r=i.userConfig.get().backgroundMusic;r&&n.push(r)}if(t instanceof
|
|
38
|
+
This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};de.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.lineEnd":"event:state.player.lineEnd","event:state.dialog.change":"event:state.dialog.change","event:state.player.requestFlush":"event:state.player.requestFlush","event:state.player.stageClick":"event:state.player.stageClick","event:state.scene.mount":"event:state.scene.mount","event:state.scene.unmount":"event:state.scene.unmount","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes","event:state.nvl.enter":"event:state.nvl.enter","event:state.nvl.exit":"event:state.nvl.exit","event:state.nvl.dialogComplete":"event:state.nvl.dialogComplete","event:state.nvl.dialogAppend":"event:state.nvl.dialogAppend","event:state.nvl.visibilityChange":"event:state.nvl.visibilityChange","event:state.nvl.change":"event:state.nvl.change"};var I=de;var It=class It extends J{static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:i,voice:r}=t.config;return!i&&!r?null:Se.toSound(n.getVoice(i)||r)}static endVoiceWithPreference(e,t){let{voiceEndMode:n,voiceFadeDuration:i}=e.game.preference.getPreferences();if(n==="none")return null;let r=n==="fade"?Math.max(0,i):0;return e.audioManager.stop(t,r)}static cutTrailingVoice(e,t){let n=It.trailingVoice.get(e);n&&n!==t&&e.audioManager.isPlaying(n)&&e.timelines.attachTimeline(e.audioManager.stop(n,0)),t?It.trailingVoice.set(e,t):It.trailingVoice.delete(e)}executeAction(e,t){if(this.type===Jt.say){let n=null,i="",r=null,s=new v(g=>g).registerSkipController(new B(()=>{n?.()})),a=new De(s),l=this.contentNode.getContent(),c=e.isNvlMode(),u=e.getLiveGame(),p=e.createPresentationSnapshot(),d=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,f=It.getVoice(e,l);if(f){It.cutTrailingVoice(e,f);let g=e.audioManager.play(f);a.attachChild(g)}let h=f?e.events.on(I.EventTypes["event:state.player.lineEnd"],()=>{let g=It.endVoiceWithPreference(e,f);g&&e.timelines.attachTimeline(g),h?.cancel()}):null;if(c){let g=this.getId(),y=(e.getActiveNvlDialogForAction(g)||e.getLatestNvlDialogForAction(g))?.id||e.allocateNvlDialogId(g),S=l.evaluate(Ee.getCtx({gameState:e}));i=ae.getText(S),u.events.emit(Wt.EventTypes["event:character.prompt"],{character:l.config.character,sentence:l,text:i});let T=!1,E=()=>{T||(T=!0,e.events.emit(I.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:A}=e.ensureNvlDialog({id:y,actionId:g,character:this.callee,sentence:l,text:i});r=y;let C=e.consumeNvlTypingSuppression(),L=A&&!C?"typing":"awaitAdvance";e.activateNvlDialog(y,L,!A);let k=e.waitForNvlAdvance(y,()=>{e.settleNvlDialog(y),E()});n=()=>{k.cancel()}}else{let g=e.idManager.generateId(),b=e.createDialog(g,l,()=>{e.settleAdvDialog(g),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(g,this.getId()),i=b.text,n=()=>{e.settleAdvDialog(g),b.cancel()}}u.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:m}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(h?.cancel(),f&&e.audioManager.isPlaying(f)){let g=It.endVoiceWithPreference(e,f);g&&a.attachChild(g)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(p),d?u.setLastDialog(d.sentence,d.speaker):u.lastDialog=null});return e.gameHistory.push({token:m,action:this,element:{type:"say",text:i,voice:f?f.getSrc():null,voiceId:l.config.voiceId??null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),s}else if(this.type===Jt.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.name=i},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};It.ActionTypes=Jt,It.trailingVoice=new WeakMap;var rt=It;var Re=class Re extends Un{constructor(t,n){super();this.srcManager=new Me;this.events=new ee;this.actions=[];this.voiceCache=new Map;this._futureActions_=[];this.labelMap=new Map;let i=Re.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Re.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Re.DefaultUserConfig.create(n),a=Re.DefaultSceneConfig.create({...s.get(),name:t,layers:[...s.get().layers,i,r],defaultBackgroundLayer:i,defaultDisplayableLayer:r});this.userConfig=s,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new zn(t)}static get DefaultSceneConfig(){return Re._defaultSceneConfig??(Re._defaultSceneConfig=new $({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Kn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Kn("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=r=>typeof r=="object"&&r!==null,i=r=>typeof r=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(r=>{Se.isSound(r)&&Re.validateVoice(r)}),i(t))return t;throw new He(`Invalid voices config: ${t}`)}}))}static validateVoice(t){if(!ao(t.config.type,[ot.voice,ot.sound]))throw new He(`Voice must be a voice, but got ${t.config.type}.
|
|
39
|
+
To prevent unintended behavior and unexpected results, the sound have to be on the voice bus (or any bus beneath it). Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Re}static getOwnedSounds(t){let n=[],i=t.callee;if(Re.isScene(i)){let r=i.userConfig.get().backgroundMusic;r&&n.push(r)}if(t instanceof re&&t.type===W.setBackgroundMusic){let[r]=t.contentNode.getContent();r&&n.push(r)}return n}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t,n){return new Xe({backgroundImage:i=>i.toData(),backgroundMusic:i=>{let r=i?.toData();if(!r)return null;let s=i.getId();return s?{...r,id:s}:r}},{backgroundImage:i=>t.state.backgroundImage.fromData(i),backgroundMusic:i=>{if(!i)return null;let r=i.id?n?.get(i.id):void 0,s=r instanceof Se?r:t.state.backgroundMusic;return s?s.fromData(i):null}})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){return this.combineActions(new Fe,()=>this.background.char(t,n))}jumpTo(t,n={}){let i=Q({},n instanceof Bt?{transition:n}:n);return i.returnable?this._callScene(t,i.transition):this.combineActions(new Fe({allowFutureScene:!1}),r=>(r.chain(new re(r,"scene:preUnmount",new x().setContent([]))).chain(this._initScene(t))._transitionToScene(i.transition,t).chain(this._exit()),r))._jumpTo(t)}_callScene(t,n){return this.combineActions(new Fe({allowFutureScene:!1}),i=>(i.chain(this._preSuspend(t)).chain(this._initScene(t))._transitionToScene(n,t),i))._callTo(t)._resume(t)}setBackgroundMusic(t,n){return this.chain(new re(this.chain(),W.setBackgroundMusic,new x().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new Ti(this),a=typeof r=="function"?r(s):r,l=this.narrativeToActions(a),c={showTransition:i,hideTransition:i},u=new re(this.chain(),W.nvlEnd,new x().setContent([c])),p=[...l,u];super.constructNodes(p);let d=new re(this.chain(),W.nvlBlock,new x().setContent([p,c]));return this.chain(d)}action(t){return this.actions=t,this}preloadImage(t){if(!w.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(i=>{this.srcManager.register({type:"image",src:i})}),this}toData(){return{state:Re.getStateSerializer(this).serialize(this.state)}}fromData(t,n){return this.state=Re.getStateSerializer(this,n).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new re(this.chain(),"scene:action",new x);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>Ke.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[],l=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{Ke.isChained(m)||(m instanceof O?s.push(m):m instanceof Pn?a.push(m):m instanceof Rt&&l.push(m))});let c=[],u=[],p=new Map;s.forEach(m=>{m.config.isWearable?u.push(m):m.config.autoInit&&c.push(m);for(let g of m.config.wearables){if(p.get(g)&&p.get(g)!==m)throw new Error(`Wearable image cannot be used multiple times
|
|
40
40
|
Maybe you bind the same wearable image to multiple parent images
|
|
41
41
|
Parent Conflict (src: `+p.get(g)?.state.currentSrc+`)
|
|
42
|
-
Current Parent (src: `+m.state.currentSrc+")");p.set(g,m)}});let d=[...this._initScene(this),...c.map(m=>m._init(this)),...u.map(m=>{if(!p.has(m))throw new Error("Wearable image must have a parent image");return p.get(m)._initWearable(m)}),...a.map(m=>m._init()),...l.map(m=>m._init()),...r],f=super.constructNodes(d),h=new
|
|
43
|
-
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 O({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
|
|
42
|
+
Current Parent (src: `+m.state.currentSrc+")");p.set(g,m)}});let d=[...this._initScene(this),...c.map(m=>m._init(this)),...u.map(m=>{if(!p.has(m))throw new Error("Wearable image must have a parent image");return p.get(m)._initWearable(m)}),...a.map(m=>m._init()),...l.map(m=>m._init()),...r],f=super.constructNodes(d),h=new x(this.sceneRoot,void 0,f||void 0).setContent(this);return f?.setParent(h),this.sceneRoot?.setContentNode(h),this._futureActions_=d,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 ue&&r.type===ce.label){let[s]=r.contentNode.getContent();if(i.has(s))throw new He(`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 ue&&r.type===ce.jump){let[s]=r.contentNode.getContent(),a=i.get(s);if(!a)throw new He(`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"?nn.say(n).getActions():Ke.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 l=s.shift();if(!i.has(l)){if(i.add(l),l instanceof re){let c=l.callee;if(w.isImageSrc(c.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:w.srcToURL(c.state.backgroundImage.state.currentSrc)}),l.type===W.jumpTo||l.type===W.callTo){let p=l,d=p.contentNode.getContent()[0],f=Re.getScene(t,d);if(!f)throw l._sceneNotFoundError(l.getSceneName(d));let h=Me.getPreloadableSrc(t,l);if(h&&this.srcManager.register(h),!r.has(p)&&!n.has(f))r.add(p),a.add(f),n.add(f);else if(l.type===W.jumpTo)continue}}else if(l instanceof Ae){let c=Me.getPreloadableSrc(t,l);c&&this.srcManager.register(c)}else if(l instanceof it)this.srcManager.register(l.callee);else if(l instanceof rt){let c=l.type===Jt.say?l.contentNode.getContent():null;for(let u of Za(l.callee,c))this.srcManager.register({type:"image",src:w.srcToURL(u)})}else if(l instanceof ue){let u=l.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else l instanceof Ce&&this.srcManager.register(l.callee.srcManager.getSrc());s.push(...l.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(l=>{l.registerSrc(t,n),this.srcManager.registerFuture(l.srcManager)})}assignActionId(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}),i=new Set;n.forEach(a=>{let l=a.getStaticId();if(l){if(i.has(l))throw new He(`Duplicate static action id: ${l}`);i.add(l)}});let r=0,s=()=>{let a=`a-${r++}`;for(;i.has(a);)a=`a-${r++}`;return i.add(a),a};n.forEach(a=>{let l=a.getStaticId();a.resolveId(l||s())})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((s,a)=>{s.resolveId(`e-${a}`)});let i=new Set;this.getAllChildren(t,this.sceneRoot||[]).forEach(s=>{Re.getOwnedSounds(s).forEach(a=>i.add(a))});let r=0;i.forEach(s=>{s.getId()||s.resolveId(`s-${r}`),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):(Re.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=Se.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&&!ao(t.backgroundMusic.config.type,[ot.bgm]))throw new He(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
|
|
43
|
+
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 O({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new re(this.chain(),"scene:jumpTo",new x().setContent([t])))}_callTo(t){return this.chain(new re(this.chain(),"scene:callTo",new x().setContent([t])))}_resume(t){return this.chain(new re(this.chain(),"scene:resume",new x().setContent([t])))}_preSuspend(t){return new re(this.chain(),"scene:preSuspend",new x().setContent([t]))}_exit(){return new re(this.chain(),"scene:exit",new x().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new re(i,W.transitionToScene,new x().setContent([t,n]))):i}_init(t){return new re(this.chain(),"scene:init",new x().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};Re.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"},Re.DefaultUserConfig=new $({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Re._defaultSceneConfig=null;var Je=Re;var tl=3;var nl="scene:resume",il=32767,Nu=1e3,Ze=class o{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.executingWaitingAction=!1;this.loopConfig=null;this.loopBodyActions=[];this.loopCondition=null;this.loopStartTime=0;this.loopDebugCheckpoint=0;this.__tag=t,this.stack=new Ji().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new ke("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new ke("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(v.isAwaitable(i)&&!i.isSettled())throw new ke("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!v.isAwaitable(n))throw new ke("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof o}static createStackModel(e,t,n){let i=new o(e);return i.deserialize(t,n),i}static createCountLoop(e,t,n){let i=new o(e,"loop:count");return i.initLoop({type:"count",counter:0,limit:t,bodyActionIds:n.map(r=>r.getId()),broken:!1},n,null),i}static createConditionLoop(e,t,n,i){let r=new o(e,"loop:condition");return r.initLoop({type:"condition",counter:0,conditionActionId:n,bodyActionIds:i.map(s=>s.getId()),broken:!1},i,t),r}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!v.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?v.any(...t.map(n=>n.execute())):v.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}initLoop(e,t,n){this.loopConfig=e,this.loopBodyActions=t,this.loopCondition=n,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=0,this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody()}shouldContinueLoop(e){return!this.loopConfig||this.loopConfig.broken?!1:this.loopConfig.type==="count"?this.loopConfig.counter<(this.loopConfig.limit??0):this.loopCondition?this.loopCondition.evaluate({gameState:e}).value:!1}pushLoopBody(){if(this.loopBodyActions.length!==0)for(let e=this.loopBodyActions.length-1;e>=0;e--)this.stack.push(o.fromAction(this.loopBodyActions[e]))}onIterationComplete(){!this.loopConfig||this.loopConfig.broken||(this.loopConfig.counter++,this.liveGame.game.config.app.debug&&this.checkInfiniteLoop(),this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody())}checkInfiniteLoop(){if(!this.loopConfig)return;let e=this.loopConfig.counter;if(e>0&&e%il===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=il&&t<Nu){let i=new P(`[NarraLeaf] Potential infinite loop detected!
|
|
44
44
|
Loop has executed ${e} iterations in ${t}ms.
|
|
45
45
|
This is likely a bug in your game script. Check your loop conditions.
|
|
46
|
-
Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new P("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(v.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e;n.forEach(i=>{i.isEmpty()||i.abandon()})}this.waitingAction=null;let t=this.stack.pop();if(v.isAwaitable(t)){if(t.isFailed())throw t.error;let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=null,t=!1,n=new v().registerSkipController(new B(()=>{t=!0,e?.abort()}));return(async()=>{let r=0;for(;!t;){if(r++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){if(this.loopConfig&&!this.loopConfig.broken&&(this.onIterationComplete(),!this.stack.isEmpty()))continue;t=!0;break}let s=this.rollNext();if(s){if(v.isAwaitable(s)){if(s.isFailed())throw s.error;if(s.isSettled())continue;if(e=s,await new Promise(a=>{s.onSettled(a)}),s.isFailed())throw s.error;if(s.isAborted()){t=!0;break}}else if(o.isCalledActionResult(s))if(s.wait)e=o.executeStackModelGroup(s.wait.type,s.wait.stackModels),await e;else continue}}})().then(()=>n.resolve()).catch(r=>n.fail(r)),n}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&v.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):o.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getWaitingAwaitable(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&v.isAwaitable(e)&&!e.isSettled()?e:null}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(o.isCalledActionResult(n))return n;if(e)throw new ke("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}peekTopActionId(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t))return t.node?.action?.getId()??null}return null}peekExecutingActionId(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&o.isCalledActionResult(e)?e.node?.action?.getId()??null:null}snapshot(){let e=[];for(let n=this.stack.size()-1;n>=0;n--){let i=this.stack.get(n);if(!o.isCalledActionResult(i))continue;let r={actionId:i.node?.action?.getId()??null,actionType:i.node?.action?.type??null};i.wait?.stackModels&&(r.branchWaitType=i.wait.type,r.branches=i.wait.stackModels.map(s=>s.snapshot())),e.push(r)}let t={frames:e};return this.__tag&&(t.tag=this.__tag),this.loopConfig&&(t.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,broken:this.loopConfig.broken}),t}executeActions(e){if(!e.node?.action)return null;this.executingWaitingAction=!0;let t;try{t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this})}finally{this.executingWaitingAction=!1}let n=i=>i?v.isAwaitable(i)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",i),this.stack.push(i),i):i.node?.action||i.wait?.stackModels.length?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",i),this.stack.push(i),i):null:null;if(Array.isArray(t)){let i=null;for(let r of t){let s=n(r);s&&(i=s)}return i}else{let i=n(t);if(i)return i}return null}isWaiting(){let e=this.stack.peek();return e?v.isAwaitable(e)?!e.isSettled():o.isCalledActionResult(e)&&e.wait?o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=a=>{if(o.isCalledActionResult(a)){let l=a.node?.action?.getId()??null,c=a.node?.action?.type??null;return a.wait?.stackModels?{type:"link",actionType:c,action:l,stacks:a.wait.stackModels.map(u=>u.serialize()),stackWaitType:a.wait.type}:{type:"action",actionType:c,action:l}}return null},n=this.stack.map(t).filter(function(a){return a!==null}),i=this.stack.peek(),r=this.executingWaitingAction||v.isAwaitable(i);if(e&&this.waitingAction&&r){let a=t(this.waitingAction);a&&n.push(a)}let s={items:n};return this.loopConfig&&(s.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,conditionActionId:this.loopConfig.conditionActionId,bodyActionIds:this.loopConfig.bodyActionIds,broken:this.loopConfig.broken}),s}abandon(){let e=[];if(this.collectCallFrames(e),e.length){let t=this.liveGame.getGameStateForce();e.forEach(n=>n.abandon(t))}return this.reset(),this}collectCallFrames(e){let t=n=>{if(!o.isCalledActionResult(n))return;n.wait?.stackModels.forEach(r=>r.collectCallFrames(e));let i=n.node?.action;i&&i.type===el&&e.push(i)};t(this.waitingAction??void 0);for(let n=this.stack.size()-1;n>=0;n--)t(this.stack.get(n))}reset(){this.stack.forEach(e=>{o.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):v.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear(),this.loopConfig=null,this.loopBodyActions=[],this.loopCondition=null,this.loopStartTime=0,this.loopDebugCheckpoint=0}deserialize(e,t){this.reset();let n=e.items;for(let i of n){if(this.topIsGroupStillRunning()){this.liveGame.getGameStateForce?.().logger?.debug("StackModel","Dropping an item restored above a running group",i.action);break}if(i.type==="action"){if(!i.action)continue;let{actionType:r,action:s}=i,a=t.get(s);if(!a)throw new Error(`Action not found: ${s}`);this.stack.push({type:r,node:a.contentNode,wait:null})}else if(i.type==="link"){let{actionType:r,action:s,stacks:a,stackWaitType:l}=i;if(l==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:l,stackModels:a.map(c=>o.createStackModel(this.liveGame,c,t))}})}}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let l=t.get(a);if(!l)throw new Error(`Loop body action not found: ${a}`);r.push(l)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let l=a.contentNode.getContent();Array.isArray(l)&&l.length>=2&&J.isLambda(l[1])&&(s=l[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}topIsGroupStillRunning(){let e=this.stack.peek();return o.isCalledActionResult(e)&&!!e.wait&&o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels)}clearAboveCallFrame(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t)&&t.node?.action?.type===el){for(;this.stack.size()>e+1;){let n=this.stack.pop();v.isAwaitable(n)?n.abort():o.isCalledActionResult(n)&&n.wait?.stackModels.forEach(i=>i.reset())}return this.waitingAction=null,this}}return this.reset(),this}push(...e){return this.stack.push(...e),this}};var Ge=class Ge{constructor(e){this.events=new Z;this.story=null;this.gameLock=new Nn;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.elementAuditCountdown=0;this.lastDialog=null;this.mapCache=null;this._currentActionId=null;this.game=e,this._storable=new li,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new Ut(Ge.GameSpacesKey.game,Ge.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.story;if(!e)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");return{name:this.currentSavedGame.name,meta:{version:Za,created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:e.hash()},game:{...this.serializeGameState(),history:this.gameState.gameHistory.serialize()}}}serializeGameState(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates();this.auditElementDirtyMarks(t);let s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(l=>l.serialize());return{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}auditElementDirtyMarks(e){if(!this.game.config.app.debug||this.elementAuditCountdown-- >0)return;this.elementAuditCountdown=Ge.ElementAuditInterval;let t=e.findUnmarkedElements();t.length&&(t.forEach(n=>n.markDirty()),this.gameState?.logger.warn("LiveGame.auditElementDirtyMarks",`${t.length} element(s) had state that no longer matches the script but were never marked dirty, so the save just written left them out. They have been marked, so the next save will carry them - but something is writing element state outside the action dispatch: ${t.map(n=>n.getId()).join(", ")}`))}captureGameState(){try{return this.serializeGameState()}catch(e){return this.gameState?.logger.warn("LiveGame.captureGameState",e),null}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");this.game.hooks.trigger("beforeRestore",[]),t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:i,stage:r,elementStates:s,services:a,stackModel:l,asyncStackModels:c}}=e,[u,p]=this.constructMaps();this.initNamespaces(),this._storable.load(i),p.forEach(d=>d.reset()),s.forEach(({id:d,data:f})=>{t.logger.debug("restore element",d);let h=p.get(d);if(!h)throw new Error("Element not found, id: "+d+`
|
|
47
|
-
NarraLeaf cannot find the element with the id from the saved game`);h instanceof Je?h.fromData(f,p):h.fromData(f),h.markDirty()}),p.forEach(d=>{d instanceof je&&d._rebindLoop(u)}),this.currentSavedGame=e,t.loadData(r,p),this.stackModel.deserialize(l,u),c.forEach(d=>{let f=Ze.createStackModel(this,d,u);this.asyncStackModels.add(f),t.timelines.attachTimeline(this.executeAsyncStackModel(f))}),n.deserializeServices(a),t.gameHistory.load(e.game.history??[],u),this.game.hooks.trigger("afterRestore",[]),t.events.once(
|
|
46
|
+
Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new P("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(v.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e;n.forEach(i=>{i.isEmpty()||i.abandon()})}this.waitingAction=null;let t=this.stack.pop();if(v.isAwaitable(t)){if(t.isFailed())throw t.error;let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=null,t=!1,n=new v().registerSkipController(new B(()=>{t=!0,e?.abort()}));return(async()=>{let r=0;for(;!t;){if(r++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){if(this.loopConfig&&!this.loopConfig.broken&&(this.onIterationComplete(),!this.stack.isEmpty()))continue;t=!0;break}let s=this.rollNext();if(s){if(v.isAwaitable(s)){if(s.isFailed())throw s.error;if(s.isSettled())continue;if(e=s,await new Promise(a=>{s.onSettled(a)}),s.isFailed())throw s.error;if(s.isAborted()){t=!0;break}}else if(o.isCalledActionResult(s))if(s.wait)e=o.executeStackModelGroup(s.wait.type,s.wait.stackModels),await e;else continue}}})().then(()=>n.resolve()).catch(r=>n.fail(r)),n}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&v.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):o.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getWaitingAwaitable(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&v.isAwaitable(e)&&!e.isSettled()?e:null}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(o.isCalledActionResult(n))return n;if(e)throw new ke("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}peekTopActionId(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t))return t.node?.action?.getId()??null}return null}peekExecutingActionId(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&o.isCalledActionResult(e)?e.node?.action?.getId()??null:null}snapshot(){let e=[];for(let n=this.stack.size()-1;n>=0;n--){let i=this.stack.get(n);if(!o.isCalledActionResult(i))continue;let r={actionId:i.node?.action?.getId()??null,actionType:i.node?.action?.type??null};i.wait?.stackModels&&(r.branchWaitType=i.wait.type,r.branches=i.wait.stackModels.map(s=>s.snapshot())),e.push(r)}let t={frames:e};return this.__tag&&(t.tag=this.__tag),this.loopConfig&&(t.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,broken:this.loopConfig.broken}),t}executeActions(e){if(!e.node?.action)return null;this.executingWaitingAction=!0;let t;try{t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this})}finally{this.executingWaitingAction=!1}let n=i=>i?v.isAwaitable(i)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",i),this.stack.push(i),i):i.node?.action||i.wait?.stackModels.length?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",i),this.stack.push(i),i):null:null;if(Array.isArray(t)){let i=null;for(let r of t){let s=n(r);s&&(i=s)}return i}else{let i=n(t);if(i)return i}return null}isWaiting(){let e=this.stack.peek();return e?v.isAwaitable(e)?!e.isSettled():o.isCalledActionResult(e)&&e.wait?o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=a=>{if(o.isCalledActionResult(a)){let l=a.node?.action?.getId()??null,c=a.node?.action?.type??null;return a.wait?.stackModels?{type:"link",actionType:c,action:l,stacks:a.wait.stackModels.map(u=>u.serialize()),stackWaitType:a.wait.type}:{type:"action",actionType:c,action:l}}return null},n=this.stack.map(t).filter(function(a){return a!==null}),i=this.stack.peek(),r=this.executingWaitingAction||v.isAwaitable(i);if(e&&this.waitingAction&&r){let a=t(this.waitingAction);a&&n.push(a)}let s={items:n};return this.loopConfig&&(s.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,conditionActionId:this.loopConfig.conditionActionId,bodyActionIds:this.loopConfig.bodyActionIds,broken:this.loopConfig.broken}),s}abandon(){let e=[];if(this.collectCallFrames(e),e.length){let t=this.liveGame.getGameStateForce();e.forEach(n=>n.abandon(t))}return this.reset(),this}collectCallFrames(e){let t=n=>{if(!o.isCalledActionResult(n))return;n.wait?.stackModels.forEach(r=>r.collectCallFrames(e));let i=n.node?.action;i&&i.type===nl&&e.push(i)};t(this.waitingAction??void 0);for(let n=this.stack.size()-1;n>=0;n--)t(this.stack.get(n))}reset(){this.stack.forEach(e=>{o.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):v.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear(),this.loopConfig=null,this.loopBodyActions=[],this.loopCondition=null,this.loopStartTime=0,this.loopDebugCheckpoint=0}deserialize(e,t){this.reset();let n=e.items;for(let i of n){if(this.topIsGroupStillRunning()){this.liveGame.getGameStateForce?.().logger?.debug("StackModel","Dropping an item restored above a running group",i.action);break}if(i.type==="action"){if(!i.action)continue;let{actionType:r,action:s}=i,a=t.get(s);if(!a)throw new Error(`Action not found: ${s}`);this.stack.push({type:r,node:a.contentNode,wait:null})}else if(i.type==="link"){let{actionType:r,action:s,stacks:a,stackWaitType:l}=i;if(l==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:l,stackModels:a.map(c=>o.createStackModel(this.liveGame,c,t))}})}}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let l=t.get(a);if(!l)throw new Error(`Loop body action not found: ${a}`);r.push(l)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let l=a.contentNode.getContent();Array.isArray(l)&&l.length>=2&&Z.isLambda(l[1])&&(s=l[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}topIsGroupStillRunning(){let e=this.stack.peek();return o.isCalledActionResult(e)&&!!e.wait&&o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels)}clearAboveCallFrame(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t)&&t.node?.action?.type===nl){for(;this.stack.size()>e+1;){let n=this.stack.pop();v.isAwaitable(n)?n.abort():o.isCalledActionResult(n)&&n.wait?.stackModels.forEach(i=>i.reset())}return this.waitingAction=null,this}}return this.reset(),this}push(...e){return this.stack.push(...e),this}};var Ge=class Ge{constructor(e){this.events=new ee;this.story=null;this.gameLock=new Nn;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.elementAuditCountdown=0;this.lastDialog=null;this.mapCache=null;this._currentActionId=null;this.game=e,this._storable=new ci,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new Ut(Ge.GameSpacesKey.game,Ge.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.story;if(!e)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");return{name:this.currentSavedGame.name,meta:{version:tl,created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:e.hash()},game:{...this.serializeGameState(),history:this.gameState.gameHistory.serialize()}}}serializeGameState(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates();this.auditElementDirtyMarks(t);let s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(l=>l.serialize());return{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}auditElementDirtyMarks(e){if(!this.game.config.app.debug||this.elementAuditCountdown-- >0)return;this.elementAuditCountdown=Ge.ElementAuditInterval;let t=e.findUnmarkedElements();t.length&&(t.forEach(n=>n.markDirty()),this.gameState?.logger.warn("LiveGame.auditElementDirtyMarks",`${t.length} element(s) had state that no longer matches the script but were never marked dirty, so the save just written left them out. They have been marked, so the next save will carry them - but something is writing element state outside the action dispatch: ${t.map(n=>n.getId()).join(", ")}`))}captureGameState(){try{return this.serializeGameState()}catch(e){return this.gameState?.logger.warn("LiveGame.captureGameState",e),null}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");this.game.hooks.trigger("beforeRestore",[]),t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:i,stage:r,elementStates:s,services:a,stackModel:l,asyncStackModels:c}}=e,[u,p]=this.constructMaps();this.initNamespaces(),this._storable.load(i),p.forEach(d=>d.reset()),s.forEach(({id:d,data:f})=>{t.logger.debug("restore element",d);let h=p.get(d);if(!h)throw new Error("Element not found, id: "+d+`
|
|
47
|
+
NarraLeaf cannot find the element with the id from the saved game`);h instanceof Je?h.fromData(f,p):h.fromData(f),h.markDirty()}),p.forEach(d=>{d instanceof je&&d._rebindLoop(u)}),this.currentSavedGame=e,t.loadData(r,p),this.stackModel.deserialize(l,u),c.forEach(d=>{let f=Ze.createStackModel(this,d,u);this.asyncStackModels.add(f),t.timelines.attachTimeline(this.executeAsyncStackModel(f))}),n.deserializeServices(a),t.gameHistory.load(e.game.history??[],u),this.game.hooks.trigger("afterRestore",[]),t.events.once(I.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}getFuture(){return this.assertGameState(),this.gameState.gameHistory.getFuture()}canUndo(){return this.assertGameState(),this.gameState.gameHistory.canUndo()}canRedo(){return this.assertGameState(),this.gameState.gameHistory.canRedo()}undo(){this.assertGameState();let e=this.gameState.gameHistory;return e.canUndo()?this.restoreToIndex(e.getCursor()-1,"LiveGame.undo"):(this.gameState.logger.warn("LiveGame.undo","No line to step back to"),!1)}redo(){this.assertGameState();let e=this.gameState.gameHistory;return e.canRedo()?this.restoreToIndex(e.getCursor()+1,"LiveGame.redo"):(this.gameState.logger.warn("LiveGame.redo","No line to step forward to"),!1)}restoreToHistory(e){this.assertGameState();let t=this.gameState.gameHistory.indexOfToken(e);return t<0?(this.gameState.logger.warn("LiveGame.restoreToHistory","No history entry for token",e),!1):this.restoreToIndex(t,"LiveGame.restoreToHistory")}restoreToIndex(e,t){this.assertGameState();let n=this.gameState.gameHistory,i=n.getAt(e);if(!i)return this.gameState.logger.warn(t,"No history entry at",e),!1;if(e<n.getCursor()&&this.gameState.actionHistory.has(i.token)){let a=n.getCursor();if(n.setCursor(e),this.undoInPlace(i,t))return this.auditRestoredLine(i,t),!0;n.setCursor(a)}if(!i.snapshot)return this.gameState.logger.warn(t,"History entry has no restore snapshot",i.token),!1;let r=i.token,s={name:this.currentSavedGame?.name??"",meta:this.currentSavedGame?.meta??this.getNewSavedGame().meta,game:{...i.snapshot,history:n.serializeAll()}};return this.deserialize(s),this.gameState.gameHistory.setCursor(this.gameState.gameHistory.indexOfToken(r)),i.action.type===Jt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),!0}undoInPlace(e,t){this.assertGameState();let n=this.gameState.actionHistory;if(!n.has(e.token))return!1;let i=this.gameLock.register().lock();this.stackModel.abortStackTop();let r=n.undoUntil(e.token);if(!r)return this.gameLock.off(i.unlock()),!1;let[s]=this.constructMaps(),{rootStackSnapshot:a,stackModel:l}=r;return r.action.type===Jt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(a,s),l===this.stackModel&&this.stackModel.push(Ze.fromAction(r.action)),this.gameLock.off(i.unlock()),this.gameState.logger.debug(t,"Stepped back in place to",e.token),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0),!0}auditRestoredLine(e,t){if(!this.game.config.app.debug||!e.snapshot)return;let n=JSON.stringify([...e.snapshot.elementStates].sort((r,s)=>r.id.localeCompare(s.id))),i=JSON.stringify([...this.serializeGameState().elementStates].sort((r,s)=>r.id.localeCompare(s.id)));n!==i&&this.gameState?.logger.warn(t,`Stepping back in place did not reproduce the state this line's snapshot describes, so an action's undo does not fully reverse it. Restoring the snapshot would have been correct; this path was not.
|
|
48
48
|
expected: ${n}
|
|
49
|
-
actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=v.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new Se({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(L.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Ge.FastForwardStepTimeout,l=i!==null?{reachedTarget:!1}:{},c=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...l};if(this.stackModel.isEmpty())return{reason:"end",...l};let p=this.stackModel.getWaitingAwaitable();if(p){if(!await Ge.settleSuspendedStep(t,p,a))return{reason:"stalled",...l}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...l}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(c)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,l=p=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(p))};if(a=t.onSettled(()=>l(!0)),r){a?.cancel?.();return}let c=Date.now()+n,u=()=>{if(!r&&(e.events.emit(L.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=c){l(!1);return}s=setTimeout(u,Ge.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Ge.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Ge.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Ge.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Ze.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee);for(let r of Je.getOwnedSounds(i)){let s=r.getId();s&&n.set(s,r)}},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Ze(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new Ze(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Ge.EventTypes["event:action.current"])&&this.events.emit(Ge.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type}),t.callee?.markDirty();let i=t.executeAction(e,n);return v.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new ke("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Ze(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new ke("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[Ht].some(l=>i?.action&&i.action instanceof l)){i=null;continue}if(i.action&&i.action.is(oe,z.jumpTo)){let[l]=i.action.contentNode.getContent(),c=e.getScene(l);if(!c)throw i.action._sceneNotFoundError(i.action.getSceneName(l));if(a.has(c)){i=null;continue}a.add(c),i=c.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(ce,le.do)){let[l]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=l[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new ke("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new ke("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:Ta(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new P("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new P("Player Element Not Mounted")}};Ge.DefaultNamespaces={game:{}},Ge.GameSpacesKey={game:"game"},Ge.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Ge.ElementAuditInterval=50,Ge.FastForwardStepTimeout=1e4,Ge.FastForwardSkipInterval=16;var Wt=Ge;var bi=class bi{constructor(e){this.events=new Z;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(bi.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(bi.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};bi.EventTypes={"event:game.preference.change":"event:game.preference.change"};var Ti=bi;import"client-only";import uc,{useEffect as Id}from"react";import"client-only";import nl,{useContext as il,useState as Du}from"react";var Hr=nl.createContext(null);function ol({children:o,game:e}){"use client";let t=new Y({}),[n]=Du(e||t);return nl.createElement(Hr,{value:n},o)}function N(){let o=il(Hr);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function rl(){return il(Hr)}import Lu,{createContext as Ru,useContext as sl}from"react";var al="/",Po=class Po{constructor(e,t=Po.rootPath){this.events=new Z;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,l]=s.split("=");a&&(i[decodeURIComponent(a)]=l?decodeURIComponent(l):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let l=a.slice(1);n[l]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new P(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new P(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),ct(()=>{t()}))})}else ct(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};Po.rootPath=al;var yn=Po,Ur=Ru(null);function ll({children:o}){let e=N();return Lu.createElement(Ur,{value:{router:e.router}},o)}function zt(){if(!sl(Ur))throw new Error("useRouter must be used within a RouterProvider");return sl(Ur).router}import ul from"react";import Vu from"clsx";import Iu,{createContext as Mu,useContext as Nu,useLayoutEffect as Gu,useReducer as Ou,useState as Fu}from"react";var rn=class rn{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new Z().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(rn.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(rn.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(rn.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(rn.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(rn.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(rn.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};rn.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var Br=rn,Wr=Mu(null);function cl({children:o}){"use client";let[e]=Fu(()=>new Br);return Iu.createElement(Wr,{value:{ratio:e}},o)}function be(){let o=Nu(Wr),[,e]=Ou(n=>n+1,0);if(!Wr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return Gu(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function _t({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=be(),s=r.getStyle();return ul.createElement("div",{className:Vu("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},ul.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import Hu,{useEffect as Uu}from"react";function vn(o){let e=N(),[t,n]=Hu.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return Uu(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import zr from"react";import Eo from"react";import pl from"clsx";function Do({children:o,className:e,style:t,...n}){let{ratio:i}=be(),r=N();return Eo.createElement(_t,{className:pl("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},Eo.createElement("div",{className:"absolute inset-0 w-full h-full"},Eo.createElement("div",{className:"inset-0 w-full h-full"},Eo.createElement("div",{className:pl("pointer-events-auto-rest",e),style:t},o))))}function Bu({children:o,className:e,style:t}){return zr.createElement(zr.Fragment,null,zr.createElement(Do,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import dl from"clsx";import ml from"react";function Lo({className:o,children:e,...t}){let{ratio:n}=be();return ml.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:dl("w-full h-full")},ml.createElement("div",{className:dl("z-20",o),...t},e))}import xt,{useState as fl}from"react";import{motion as Wu}from"motion/react";function Ro({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let l=N(),[c,u]=fl(!1);if(!l.config.app.inspector)return xt.createElement(r,{...a,ref:s},o);let p={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:c?1e3:"auto"}};return xt.createElement(r,{...p,ref:s},n&&c&&xt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function zu({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=N(),[a,l]=fl(!1);if(!s.config.app.inspector)return xt.createElement(i,{...r});let c={...r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return xt.createElement("div",null,xt.createElement(i,{...c}),t&&a&&xt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function _u(o){return xt.createElement(Ro,{...o,as:"div"})}function Ku(o){return xt.createElement(Ro,{...o,as:"span"})}function $u(o){return xt.createElement(zu,{...o,as:"img"})}function ju(o){return xt.createElement(Ro,{...o,as:"button"})}function qu(o){return xt.createElement(Ro,{...o,as:Wu.div,ref:o.ref,layout:o.layout})}var Qu={Div:_u,Span:Ku,Button:ju,Img:$u,mDiv:qu},Kt=Qu;import Fo from"clsx";import Be,{useEffect as Ln,useMemo as gp,useRef as Ol,useState as is}from"react";import{useEffect as Yu,useState as Xu}from"react";function de(o){let[e,t]=Xu(0);Yu(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import hl from"react";var En=hl.createContext(null);function Mt(){let o=hl.useContext(En);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}function _r({active:o,forced:e}){return o?e?"forceSkip":"requestComplete":"ignore"}function gl(o,e){let t=_r(e);return t==="forceSkip"?(o.setIdle(!0),o.forceSkip()):t==="requestComplete"&&o.requestComplete(),t}import Io,{useCallback as Ju,useLayoutEffect as Ai,useMemo as yl,useRef as vl}from"react";import{useIsPresent as Zu}from"motion/react";var Nt=class Nt{constructor(e){this.events=new Z;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new $i,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e?this.state==="ended"&&(this._idle=!0):this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(Nt.Events.complete):this.safeEmit(Nt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Nt.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Nt.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",this.config.gameState.completeAdvDialogTyping(this.config.action.id),e.getPreference(Y.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Nt.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.releaseVoiceWait(),this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Nt.Events.onFlush),this}onFlush(e){return this.events.on(Nt.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;if(!this._active||!e.getPreference(Y.Preferences.autoForward)||this.state!=="ended")return;this.releaseVoiceWait();let t=this.getPlayingVoiceToken();if(!t){this.scheduleAutoForwardDelay();return}let n=()=>{this.releaseVoiceWait(),this.scheduleAutoForwardDelay()};t.once("ended",n),t.once("stop",n),this.voiceWaitDisposer=()=>{t.off("ended",n),t.off("stop",n)}}scheduleAutoForwardDelay(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(Y.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Nt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(Y.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=rt.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};Nt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Oe=Nt;function Ci({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=Zu(),s=i&&r,a=vl(!1),l=vl(o),c=l.current!==o,u=yl(()=>o.sentence?.evaluate(Ee.getCtx({gameState:n})),[o.sentence,n]),p=yl(()=>new Oe({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:c}),[o,n]),d=n.game.config.dialog,f=Ju(h=>{!s||a.current||(a.current=!0,e?.(h))},[s,e]);return Ai(()=>{a.current=!1},[p]),Ai(()=>{l.current=o},[o]),Ai(()=>(p.setActive(s),()=>{p.setActive(!1)}),[p,s]),Ai(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",p),p.events.on(Oe.Events.complete,h=>{n.logger.log("NarraLeaf-React: Say","Complete",p.isIdle()),s&&(p.isIdle()||h?f(!1):p.setIdle(!0))}).cancel),[p,f,n,s]),Ai(()=>{let h=b=>{gl(p,{active:s,forced:b===!0})},m=n.events.on(L.EventTypes["event:state.player.skip"],h),g=n.events.on(L.EventTypes["event:state.player.stageClick"],()=>h(!1));return()=>{m.cancel(),g.cancel()}},[p,n,s]),Io.createElement(Io.Fragment,null,Io.createElement(En,{value:p},Io.createElement(d,null)))}import{useCallback as np,useEffect as Mo,useState as ip}from"react";function Sl(o,e,{dialogId:t,active:n,forced:i}){let r=_r({active:n,forced:i});return r==="ignore"?"ignore":o.requestNvlAdvance(t)!=="typing"?"pageHandled":r==="forceSkip"?(e.forceSkip(),"forceSkip"):(e.requestComplete(),"requestComplete")}import{useEffect as ep,useState as tp}from"react";function Dn(o){let e=N(),[t,n]=tp(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return ep(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var qn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(qn||{});function No({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=N(),[s]=Dn("nextAction"),[a]=ip(()=>{let c=o.firedTextEvents??(o.firedTextEvents=new Set);return new Oe({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:c})}),l=np(c=>{Sl(e,a,{dialogId:o.id,active:n,forced:c})},[a,o.id,e,n]);return Mo(()=>{if(!n)return;let c=e.events.on(L.EventTypes["event:state.player.stageClick"],()=>l(!1)),u=e.events.on(L.EventTypes["event:state.player.skip"],p=>l(p===!0));return()=>{c.cancel(),u.cancel()}},[l,e,n]),Mo(()=>{if(!n)return;let c=p=>{p.repeat||r.keyMap.match("nextAction",p.key)&&l(!1)};if(r.config.useWindowListener){let p=r.getLiveGame().onWindowEvent("keydown",c);return()=>{p.cancel()}}let u=r.getLiveGame().onPlayerEvent("keydown",c);return()=>{u.cancel()}},[l,r,n,s]),Mo(()=>{let c=a.events.on(Oe.Events.complete,u=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!u&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),Mo(()=>{let c=a.events.on(Oe.Events.simulateClick,()=>l(!1));return()=>{c.cancel()}},[l,a]),a}function op(o,e){let{expression:t,sound:n}=o.config;if(t){let{image:i,appearance:r}=t;i._setAppearanceSync(r),e.stage.update();let s=e.getExposedState(i);s&&(O.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function Go(o,e,t){e.has(o)||(e.add(o),op(o,t))}function bl(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),Go(r,e,t)}return n}var Qn=new Map,Kr=new Set;function rp(o,e){return Qn.set(o,e),Kr.delete(o),()=>{Qn.get(o)===e&&Qn.delete(o)}}function sp(o){Qn.delete(o)}function ap(o){return Qn.get(o)??null}function $r(o){if(!o)return null;if(typeof o!="string")return o;let e=Qn.get(o);return e||(Kr.has(o)||(Kr.add(o),console.warn(`NarraLeaf-React: no word renderer is registered as "${o}"; the word is rendered as plain text. Call registerWordRenderer before the line plays.`)),null)}import{useCallback as lp,useLayoutEffect as Tl,useRef as jr,useState as cp}from"react";var Al=.5,up=.005,pp=12,Cl=.05,wl=12,Oo="--nl-text-scale",kl=`var(${Oo}, 1)`;function xi(o){return o==null||o===""?void 0:`calc(${typeof o=="number"?`${o}px`:String(o)} * ${kl})`}function Pl(){return`calc(1em * ${kl})`}function xl(o,e){let t=getComputedStyle(o);return e?o.clientWidth-parseFloat(t.paddingLeft||"0")-parseFloat(t.paddingRight||"0"):o.clientHeight-parseFloat(t.paddingTop||"0")-parseFloat(t.paddingBottom||"0")}function El({enabled:o,minFontSize:e,vertical:t,revealed:n}){let i=jr(null),[r,s]=cp(1),a=jr(1),l=jr(0);a.current=r;let c=lp(u=>{let p=i.current,d=p?.parentElement;if(!p||!d)return;let f=xl(d,t);if(!Number.isFinite(f)||f<=0)return;l.current=f;let h=()=>t?p.offsetWidth:p.offsetHeight,m=T=>{p.style.setProperty(Oo,String(T))},g=T=>(m(T),h()<=f+Al);if(g(u)){u!==a.current&&s(u);return}m(1);let b=parseFloat(getComputedStyle(p).fontSize)||0,y=b>0?Math.min(1,Math.max(Cl,e/b)):Cl,S;if(y>=u||!g(y))S=y;else{let T=y,C=u;for(let x=0;x<pp&&C-T>up;x++){let w=(T+C)/2;g(w)?T=w:C=w}S=T}m(S),s(S)},[e,t]);return Tl(()=>{if(!o){a.current!==1&&s(1);return}c(a.current)},[o,c,n]),Tl(()=>{let u=i.current?.parentElement;if(!o||!u||typeof ResizeObserver>"u")return;let p=new ResizeObserver(()=>{Math.abs(xl(u,t)-l.current)>Al&&c(1)});p.observe(u);let d=!1;return document.fonts?.ready.then(()=>{d||c(a.current)}),()=>{d=!0,p.disconnect()}},[o,c,t]),{containerRef:i,scale:r}}function Dl(o,e){return o.fontSize!==void 0?xi(o.fontSize):o.fontScale!==void 0?Rl(o.fontScale):xi(e)}function Ll(o,e){return o.fontSize!==void 0?o.fontSize:o.fontScale!==void 0?Rl(o.fontScale):e}function Rl(o){return`${o}em`}function qr(o){return o?{textEmphasis:`${o.fill??"filled"} ${o.mark??"dot"}`,textEmphasisPosition:`${o.position??"over"} right`}:{}}var Qr="--nl-reveal-duration",Ml="__narraleaf_text_reveal",Il={duration:0,inFlight:0};function Yr(o,e,t){if(typeof o!="number"||!Number.isFinite(o)||o<=0)return Il;let n=1e3/(Math.max(.01,e)*Math.max(.01,t)),i=Math.min(o,8*n);return i<=0?Il:{duration:i,inFlight:Math.ceil(i/n)+1}}function Xr(o,e,t,n,i=0){if(o.inFlight<=0||t<=0)return 0;let r=n-o.inFlight,s=Math.min(t,e+t-r);return Math.max(0,Math.min(s,t-Math.max(0,i)))}import Yn from"react";var dp=2;function wi(o){return o==="vertical-rl"||o==="vertical-lr"}function mp(o){return o===!1?0:typeof o=="number"?Number.isFinite(o)?Math.max(0,Math.round(o)):0:dp}function es(o,e){return wi(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var Jr=/[0-9A-Za-z]+(?:[.:\-/][0-9A-Za-z]+)*/g;function fp(o,e){if(e<=0)return[{text:o,combineUpright:!1}];let t=[],n=0;Jr.lastIndex=0;for(let i=Jr.exec(o);i;i=Jr.exec(o))i[0].length>e||(i.index>n&&t.push({text:o.slice(n,i.index),combineUpright:!1}),t.push({text:i[0],combineUpright:!0}),n=i.index+i[0].length);return(n<o.length||t.length===0)&&t.push({text:o.slice(n),combineUpright:!1}),t}function ts(){return{wordBreak:"normal",lineBreak:"strict",overflowWrap:"break-word"}}function Zr(o,e,t){let n=e?mp(t):0;return n<=0?[{text:o,combineUpright:!1}]:fp(o,n)}function Nl(o,e){return o.some(t=>t.combineUpright)?o.map((t,n)=>t.combineUpright?Yn.createElement("span",{key:`${e}${n}`,style:{textCombineUpright:"all"}},t.text):Yn.createElement(Yn.Fragment,{key:`${e}${n}`},t.text)):o.map(t=>t.text).join("")}function hp(o){let e=[];for(let t of o){if(t.combineUpright){e.push(t);continue}for(let n of t.text)e.push({text:n,combineUpright:!1})}return e}function ns(o,e,t,n=0){if(n<=0)return e?Nl(Zr(o,e,t),""):o;let i=hp(Zr(o,e,t)),r=i.length,s=n;for(;r>0&&s>0;)r--,s-=i[r].text.length;let a=[];if(r>0){let l=i.slice(0,r).map(c=>c.text).join("");a.push(Yn.createElement(Yn.Fragment,{key:"s"},Nl(Zr(l,e,t),"s")))}for(let l=r;l<i.length;l++){let c=i[l];a.push(Yn.createElement("span",{key:`r${l}`,className:Ml,style:c.combineUpright?{textCombineUpright:"all"}:void 0},c.text))}return a}function*rs(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if($e.isPause(n.text)){yield $e.from(n.text);continue}if(pt.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
|
|
49
|
+
actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=v.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new Se({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(I.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Ge.FastForwardStepTimeout,l=i!==null?{reachedTarget:!1}:{},c=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...l};if(this.stackModel.isEmpty())return{reason:"end",...l};let p=this.stackModel.getWaitingAwaitable();if(p){if(!await Ge.settleSuspendedStep(t,p,a))return{reason:"stalled",...l}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...l}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(c)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,l=p=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(p))};if(a=t.onSettled(()=>l(!0)),r){a?.cancel?.();return}let c=Date.now()+n,u=()=>{if(!r&&(e.events.emit(I.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=c){l(!1);return}s=setTimeout(u,Ge.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Ge.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Ge.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Ge.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Ze.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee);for(let r of Je.getOwnedSounds(i)){let s=r.getId();s&&n.set(s,r)}},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Ze(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new Ze(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Ge.EventTypes["event:action.current"])&&this.events.emit(Ge.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type}),t.callee?.markDirty();let i=t.executeAction(e,n);return v.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new ke("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Ze(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new ke("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[Ht].some(l=>i?.action&&i.action instanceof l)){i=null;continue}if(i.action&&i.action.is(re,W.jumpTo)){let[l]=i.action.contentNode.getContent(),c=e.getScene(l);if(!c)throw i.action._sceneNotFoundError(i.action.getSceneName(l));if(a.has(c)){i=null;continue}a.add(c),i=c.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(ue,ce.do)){let[l]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=l[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new ke("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new ke("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:Aa(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new P("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new P("Player Element Not Mounted")}};Ge.DefaultNamespaces={game:{}},Ge.GameSpacesKey={game:"game"},Ge.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Ge.ElementAuditInterval=50,Ge.FastForwardStepTimeout=1e4,Ge.FastForwardSkipInterval=16;var Wt=Ge;var Ai=class Ai{constructor(e){this.events=new ee;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(Ai.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(Ai.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};Ai.EventTypes={"event:game.preference.change":"event:game.preference.change"};var xi=Ai;import"client-only";import dc,{useEffect as Fd}from"react";import"client-only";import ol,{useContext as rl,useState as Gu}from"react";var Ur=ol.createContext(null);function sl({children:o,game:e}){"use client";let t=new Y({}),[n]=Gu(e||t);return ol.createElement(Ur,{value:n},o)}function G(){let o=rl(Ur);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function al(){return rl(Ur)}import Ou,{createContext as Vu,useContext as ll}from"react";var cl="/",Eo=class Eo{constructor(e,t=Eo.rootPath){this.events=new ee;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,l]=s.split("=");a&&(i[decodeURIComponent(a)]=l?decodeURIComponent(l):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let l=a.slice(1);n[l]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new P(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new P(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),ct(()=>{t()}))})}else ct(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};Eo.rootPath=cl;var yn=Eo,Br=Vu(null);function ul({children:o}){let e=G();return Ou.createElement(Br,{value:{router:e.router}},o)}function zt(){if(!ll(Br))throw new Error("useRouter must be used within a RouterProvider");return ll(Br).router}import dl from"react";import _u from"clsx";import Fu,{createContext as Hu,useContext as Uu,useLayoutEffect as Bu,useReducer as Wu,useState as zu}from"react";var rn=class rn{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new ee().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(rn.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(rn.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(rn.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(rn.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(rn.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(rn.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};rn.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var Wr=rn,zr=Hu(null);function pl({children:o}){"use client";let[e]=zu(()=>new Wr);return Fu.createElement(zr,{value:{ratio:e}},o)}function be(){let o=Uu(zr),[,e]=Wu(n=>n+1,0);if(!zr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return Bu(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function _t({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=be(),s=r.getStyle();return dl.createElement("div",{className:_u("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},dl.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import Ku,{useEffect as $u}from"react";function vn(o){let e=G(),[t,n]=Ku.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return $u(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import _r from"react";import Do from"react";import ml from"clsx";function Lo({children:o,className:e,style:t,...n}){let{ratio:i}=be(),r=G();return Do.createElement(_t,{className:ml("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},Do.createElement("div",{className:"absolute inset-0 w-full h-full"},Do.createElement("div",{className:"inset-0 w-full h-full"},Do.createElement("div",{className:ml("pointer-events-auto-rest",e),style:t},o))))}function ju({children:o,className:e,style:t}){return _r.createElement(_r.Fragment,null,_r.createElement(Lo,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import fl from"clsx";import hl from"react";function Ro({className:o,children:e,...t}){let{ratio:n}=be();return hl.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:fl("w-full h-full")},hl.createElement("div",{className:fl("z-20",o),...t},e))}import Ct,{useState as gl}from"react";import{motion as qu}from"motion/react";function Io({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let l=G(),[c,u]=gl(!1);if(!l.config.app.inspector)return Ct.createElement(r,{...a,ref:s},o);let p={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:c?1e3:"auto"}};return Ct.createElement(r,{...p,ref:s},n&&c&&Ct.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function Qu({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=G(),[a,l]=gl(!1);if(!s.config.app.inspector)return Ct.createElement(i,{...r});let c={...r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return Ct.createElement("div",null,Ct.createElement(i,{...c}),t&&a&&Ct.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function Yu(o){return Ct.createElement(Io,{...o,as:"div"})}function Xu(o){return Ct.createElement(Io,{...o,as:"span"})}function Ju(o){return Ct.createElement(Qu,{...o,as:"img"})}function Zu(o){return Ct.createElement(Io,{...o,as:"button"})}function ep(o){return Ct.createElement(Io,{...o,as:qu.div,ref:o.ref,layout:o.layout})}var tp={Div:Yu,Span:Xu,Button:Zu,Img:Ju,mDiv:ep},Kt=tp;import Fo from"clsx";import Be,{useEffect as Ln,useMemo as Ap,useRef as Fl,useState as os}from"react";import{useEffect as np,useState as ip}from"react";function me(o){let[e,t]=ip(0);np(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import yl from"react";var En=yl.createContext(null);function Mt(){let o=yl.useContext(En);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}function Kr({active:o,forced:e}){return o?e?"forceSkip":"requestComplete":"ignore"}function vl(o,e){let t=Kr(e);return t==="forceSkip"?(o.setIdle(!0),o.forceSkip()):t==="requestComplete"&&o.requestComplete(),t}import Mo,{useCallback as op,useLayoutEffect as Ci,useMemo as Sl,useRef as bl}from"react";import{useIsPresent as rp}from"motion/react";var Nt=class Nt{constructor(e){this.events=new ee;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new qi,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e?this.state==="ended"&&(this._idle=!0):this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(Nt.Events.complete):this.safeEmit(Nt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Nt.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Nt.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",this.config.gameState.completeAdvDialogTyping(this.config.action.id),e.getPreference(Y.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Nt.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.releaseVoiceWait(),this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Nt.Events.onFlush),this}onFlush(e){return this.events.on(Nt.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;if(!this._active||!e.getPreference(Y.Preferences.autoForward)||this.state!=="ended")return;this.releaseVoiceWait();let t=this.getPlayingVoiceToken();if(!t){this.scheduleAutoForwardDelay();return}let n=()=>{this.releaseVoiceWait(),this.scheduleAutoForwardDelay()};t.once("ended",n),t.once("stop",n),this.voiceWaitDisposer=()=>{t.off("ended",n),t.off("stop",n)}}scheduleAutoForwardDelay(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(Y.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Nt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(Y.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=rt.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};Nt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Oe=Nt;function wi({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=rp(),s=i&&r,a=bl(!1),l=bl(o),c=l.current!==o,u=Sl(()=>o.sentence?.evaluate(Ee.getCtx({gameState:n})),[o.sentence,n]),p=Sl(()=>new Oe({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:c}),[o,n]),d=n.game.config.dialog,f=op(h=>{!s||a.current||(a.current=!0,e?.(h))},[s,e]);return Ci(()=>{a.current=!1},[p]),Ci(()=>{l.current=o},[o]),Ci(()=>(p.setActive(s),()=>{p.setActive(!1)}),[p,s]),Ci(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",p),p.events.on(Oe.Events.complete,h=>{n.logger.log("NarraLeaf-React: Say","Complete",p.isIdle()),s&&(p.isIdle()||h?f(!1):p.setIdle(!0))}).cancel),[p,f,n,s]),Ci(()=>{let h=b=>{vl(p,{active:s,forced:b===!0})},m=n.events.on(I.EventTypes["event:state.player.skip"],h),g=n.events.on(I.EventTypes["event:state.player.stageClick"],()=>h(!1));return()=>{m.cancel(),g.cancel()}},[p,n,s]),Mo.createElement(Mo.Fragment,null,Mo.createElement(En,{value:p},Mo.createElement(d,null)))}import{useCallback as lp,useEffect as No,useState as cp}from"react";function Tl(o,e,{dialogId:t,active:n,forced:i}){let r=Kr({active:n,forced:i});return r==="ignore"?"ignore":o.requestNvlAdvance(t)!=="typing"?"pageHandled":r==="forceSkip"?(e.forceSkip(),"forceSkip"):(e.requestComplete(),"requestComplete")}import{useEffect as sp,useState as ap}from"react";function Dn(o){let e=G(),[t,n]=ap(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return sp(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var qn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(qn||{});function Go({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=G(),[s]=Dn("nextAction"),[a]=cp(()=>{let c=o.firedTextEvents??(o.firedTextEvents=new Set);return new Oe({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:c})}),l=lp(c=>{Tl(e,a,{dialogId:o.id,active:n,forced:c})},[a,o.id,e,n]);return No(()=>{if(!n)return;let c=e.events.on(I.EventTypes["event:state.player.stageClick"],()=>l(!1)),u=e.events.on(I.EventTypes["event:state.player.skip"],p=>l(p===!0));return()=>{c.cancel(),u.cancel()}},[l,e,n]),No(()=>{if(!n)return;let c=p=>{p.repeat||r.keyMap.match("nextAction",p.key)&&l(!1)};if(r.config.useWindowListener){let p=r.getLiveGame().onWindowEvent("keydown",c);return()=>{p.cancel()}}let u=r.getLiveGame().onPlayerEvent("keydown",c);return()=>{u.cancel()}},[l,r,n,s]),No(()=>{let c=a.events.on(Oe.Events.complete,u=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!u&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),No(()=>{let c=a.events.on(Oe.Events.simulateClick,()=>l(!1));return()=>{c.cancel()}},[l,a]),a}function up(o,e){let{expression:t,sound:n}=o.config;if(t){let{image:i,appearance:r}=t;i._setAppearanceSync(r),e.stage.update();let s=e.getExposedState(i);s&&(O.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function Oo(o,e,t){e.has(o)||(e.add(o),up(o,t))}function Al(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),Oo(r,e,t)}return n}var Qn=new Map,$r=new Set;function pp(o,e){return Qn.set(o,e),$r.delete(o),()=>{Qn.get(o)===e&&Qn.delete(o)}}function dp(o){Qn.delete(o)}function mp(o){return Qn.get(o)??null}function jr(o){if(!o)return null;if(typeof o!="string")return o;let e=Qn.get(o);return e||($r.has(o)||($r.add(o),console.warn(`NarraLeaf-React: no word renderer is registered as "${o}"; the word is rendered as plain text. Call registerWordRenderer before the line plays.`)),null)}import{useCallback as fp,useLayoutEffect as xl,useRef as qr,useState as hp}from"react";var Cl=.5,gp=.005,yp=12,wl=.05,Pl=12,Vo="--nl-text-scale",El=`var(${Vo}, 1)`;function ki(o){return o==null||o===""?void 0:`calc(${typeof o=="number"?`${o}px`:String(o)} * ${El})`}function Dl(){return`calc(1em * ${El})`}function kl(o,e){let t=getComputedStyle(o);return e?o.clientWidth-parseFloat(t.paddingLeft||"0")-parseFloat(t.paddingRight||"0"):o.clientHeight-parseFloat(t.paddingTop||"0")-parseFloat(t.paddingBottom||"0")}function Ll({enabled:o,minFontSize:e,vertical:t,revealed:n}){let i=qr(null),[r,s]=hp(1),a=qr(1),l=qr(0);a.current=r;let c=fp(u=>{let p=i.current,d=p?.parentElement;if(!p||!d)return;let f=kl(d,t);if(!Number.isFinite(f)||f<=0)return;l.current=f;let h=()=>t?p.offsetWidth:p.offsetHeight,m=T=>{p.style.setProperty(Vo,String(T))},g=T=>(m(T),h()<=f+Cl);if(g(u)){u!==a.current&&s(u);return}m(1);let b=parseFloat(getComputedStyle(p).fontSize)||0,y=b>0?Math.min(1,Math.max(wl,e/b)):wl,S;if(y>=u||!g(y))S=y;else{let T=y,E=u;for(let A=0;A<yp&&E-T>gp;A++){let C=(T+E)/2;g(C)?T=C:E=C}S=T}m(S),s(S)},[e,t]);return xl(()=>{if(!o){a.current!==1&&s(1);return}c(a.current)},[o,c,n]),xl(()=>{let u=i.current?.parentElement;if(!o||!u||typeof ResizeObserver>"u")return;let p=new ResizeObserver(()=>{Math.abs(kl(u,t)-l.current)>Cl&&c(1)});p.observe(u);let d=!1;return document.fonts?.ready.then(()=>{d||c(a.current)}),()=>{d=!0,p.disconnect()}},[o,c,t]),{containerRef:i,scale:r}}function Rl(o,e){return o.fontSize!==void 0?ki(o.fontSize):o.fontScale!==void 0?Ml(o.fontScale):ki(e)}function Il(o,e){return o.fontSize!==void 0?o.fontSize:o.fontScale!==void 0?Ml(o.fontScale):e}function Ml(o){return`${o}em`}function Qr(o){return o?{textEmphasis:`${o.fill??"filled"} ${o.mark??"dot"}`,textEmphasisPosition:`${o.position??"over"} right`}:{}}var Yr="--nl-reveal-duration",Gl="__narraleaf_text_reveal",Nl={duration:0,inFlight:0};function Xr(o,e,t){if(typeof o!="number"||!Number.isFinite(o)||o<=0)return Nl;let n=1e3/(Math.max(.01,e)*Math.max(.01,t)),i=Math.min(o,8*n);return i<=0?Nl:{duration:i,inFlight:Math.ceil(i/n)+1}}function Jr(o,e,t,n,i=0){if(o.inFlight<=0||t<=0)return 0;let r=n-o.inFlight,s=Math.min(t,e+t-r);return Math.max(0,Math.min(s,t-Math.max(0,i)))}import Yn from"react";var vp=2;function Pi(o){return o==="vertical-rl"||o==="vertical-lr"}function Sp(o){return o===!1?0:typeof o=="number"?Number.isFinite(o)?Math.max(0,Math.round(o)):0:vp}function ts(o,e){return Pi(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var Zr=/[0-9A-Za-z]+(?:[.:\-/][0-9A-Za-z]+)*/g;function bp(o,e){if(e<=0)return[{text:o,combineUpright:!1}];let t=[],n=0;Zr.lastIndex=0;for(let i=Zr.exec(o);i;i=Zr.exec(o))i[0].length>e||(i.index>n&&t.push({text:o.slice(n,i.index),combineUpright:!1}),t.push({text:i[0],combineUpright:!0}),n=i.index+i[0].length);return(n<o.length||t.length===0)&&t.push({text:o.slice(n),combineUpright:!1}),t}function ns(){return{wordBreak:"normal",lineBreak:"strict",overflowWrap:"break-word"}}function es(o,e,t){let n=e?Sp(t):0;return n<=0?[{text:o,combineUpright:!1}]:bp(o,n)}function Ol(o,e){return o.some(t=>t.combineUpright)?o.map((t,n)=>t.combineUpright?Yn.createElement("span",{key:`${e}${n}`,style:{textCombineUpright:"all"}},t.text):Yn.createElement(Yn.Fragment,{key:`${e}${n}`},t.text)):o.map(t=>t.text).join("")}function Tp(o){let e=[];for(let t of o){if(t.combineUpright){e.push(t);continue}for(let n of t.text)e.push({text:n,combineUpright:!1})}return e}function is(o,e,t,n=0){if(n<=0)return e?Ol(es(o,e,t),""):o;let i=Tp(es(o,e,t)),r=i.length,s=n;for(;r>0&&s>0;)r--,s-=i[r].text.length;let a=[];if(r>0){let l=i.slice(0,r).map(c=>c.text).join("");a.push(Yn.createElement(Yn.Fragment,{key:"s"},Ol(es(l,e,t),"s")))}for(let l=r;l<i.length;l++){let c=i[l];a.push(Yn.createElement("span",{key:`r${l}`,className:Gl,style:c.combineUpright?{textCombineUpright:"all"}:void 0},c.text))}return a}function*ss(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if($e.isPause(n.text)){yield $e.from(n.text);continue}if(pt.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
|
|
50
50
|
`?yield`
|
|
51
|
-
`:yield{text:r,full:n.text,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function
|
|
51
|
+
`:yield{text:r,full:n.text,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function rs(o){let e=ss(o),t=[];for(let n of e){if($e.isPause(n)||pt.isTextEvent(n))continue;let i=t[t.length-1];if(i&&i!==`
|
|
52
52
|
`&&n!==`
|
|
53
53
|
`&&i.tag===n.tag){let r=i.text+n.text;t[t.length-1]={...n,text:r,config:n.config,revealFrom:r.length};continue}t.push(n===`
|
|
54
|
-
`?n:{...n,revealFrom:n.text.length})}return t}function
|
|
55
|
-
`?1:n.text.length;return{offsets:e,revealed:t}}function
|
|
54
|
+
`?n:{...n,revealFrom:n.text.length})}return t}function Hl(o){let e=[],t=0;for(let n of o)e.push(t),t+=n===`
|
|
55
|
+
`?1:n.text.length;return{offsets:e,revealed:t}}function xp(o,e,t=!1){let n=o[o.length-1];if(n&&n!==`
|
|
56
56
|
`&&e!==`
|
|
57
57
|
`&&n.tag===e.tag){let i=n.text+e.text;return[...o.slice(0,-1),{...e,text:i,config:e.config,revealFrom:t?i.length:n.revealFrom}]}return e===`
|
|
58
|
-
`?[...o,e]:[...o,{...e,revealFrom:t?e.text.length:0}]}function
|
|
59
|
-
`?y(lt=>[...lt,tt]):typeof tt=="object"&&"text"in tt&&!
|
|
60
|
-
`&&
|
|
61
|
-
`)return Be.createElement("br",{key:
|
|
62
|
-
`?await ye(
|
|
63
|
-
`)return Be.createElement("br",{key:ie});let H=Ct(D);return Be.createElement("span",{key:ie,style:{...H,...ts()},className:Fo("inline-block",D.config.className)},Be.createElement(Ul,{word:D,vertical:M,tateChuYoko:y,done:!1,style:H,renderer:$r(D.config.render),revealTail:Xr(q,ue[ie]??0,D.text.length,ge,D.revealFrom??0)}))};return Be.createElement("div",{...T,className:Fo("whitespace-pre-wrap",u),style:{...Fn(q.duration>0,{[Qr]:`${q.duration}ms`}),...ee,...es(g,b),...p}},Qe.map(W))}function Bl(o){return Be.createElement(ss,{...o,key:o.dialog?.config.action.id})}function Ap({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=No({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Be.createElement(ss,{...r,dialog:s,key:s.config.action.id})}function Cp(o){let e=Mt();return Be.createElement(ss,{...o,dialog:e,key:e.config.action.id})}function Sn(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Be.createElement(Ap,{...o}):Be.createElement(Cp,{...o})}var xp=Sn;import Uo,{useEffect as wp,useLayoutEffect as kp,useMemo as zl,useRef as Pp,useState as Ep}from"react";import Ho from"react";var as=Ho.createContext(null);function ls(){let o=Ho.useContext(as);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var cs=Ho.createContext(null);function Wl(){let o=Ho.useContext(cs);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function Bo({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let l=Pp(null),{register:c,unregister:u,getIndex:p}=Wl(),[d,f]=Ep(-1),{choose:h,evaluated:m,gameState:g}=ls(),b=d===-1?null:m[d],y=zl(()=>Ee.getCtx({gameState:g}),[g]),{hidden:S,disabled:T}=zl(()=>{if(!b)return{hidden:!1,disabled:!1};let w=b.config.hidden?.evaluate(y)?.value??!1,G=!w&&(b.config.disabled?.evaluate(y)?.value??!1);return{hidden:w,disabled:G}},[b,y]);kp(()=>{if(!l.current)return;let w=l;c(w);let G=p(w);return f(G),l.current.dataset.index=G.toString(),()=>u(w)},[c,u,p]),wp(()=>{if(!t)return;let w=G=>{G.key.toLowerCase()===t.toLowerCase()&&!G.ctrlKey&&!G.metaKey&&(G.preventDefault(),G.stopPropagation(),C())};return window.addEventListener("keydown",w,!0),()=>{window.removeEventListener("keydown",w,!0)}},[t]);function C(){if(d===-1||!m[d]||S||T)return;let w=m[d];h({...w,evaluated:se.getText(w.words||[])})}let x=b&&!S;return Uo.createElement(Uo.Fragment,null,Uo.createElement("button",{className:o,style:{...e,display:x?e?.display??void 0:"none"},onClick:C,ref:l,disabled:T},x&&Uo.createElement(Bl,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Oe({useTypeEffect:!1,action:{sentence:b.prompt,words:b.words,character:null},gameState:g,evaluatedWords:b.words})})))}import Wo from"react";import{AnimatePresence as Dp}from"motion/react";function zo({children:o,...e}){let t=Dp;return Wo.createElement(Wo.Fragment,null,Wo.createElement("div",{...e},Wo.createElement(t,null,o)))}import _l from"react";function sn({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=_l.useContext(En),l=e??o?.character??a?.config.action.character??null,c=n??l?.config.color,u=i??t??l?.state.name;return _l.createElement("div",{...s,style:{color:c?On(c):void 0,...r}},u)}import Ip from"clsx";import Mp,{useRef as Np}from"react";import us,{createContext as Lp,useContext as $l,useState as Kl}from"react";var Rn=class Rn{constructor(){this.preloaded=[];this.events=new Z}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Rn.EventTypes["event:preloaded.add"],e),this.events.emit(Rn.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(i=>this.getSrc(i));return this.preloaded=this.preloaded.filter(i=>!n.includes(this.getSrc(i))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(Rn.EventTypes["event:preloaded.remove"],e),this.events.emit(Rn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Me.getSrc(e)}};Rn.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.complete":"event:preloaded.complete","event:preloaded.unmount":"event:preloaded.unmount"};var at=Rn;var _o=class o{constructor(e){this.game=e;this.entries=new Map;this.byUrl=new Map;this.preloadTasks=new Map;this.holds=new Map;this.pinned=new Set;this.seen=new Set;this.blobBytes=0;this.decodedBytes=0;this.acquisition=null;this.missingReporter=null;this.reportedMissing=new Set;this.game.addSideEffect(()=>{this.abortAll(),this.clear()})}static getImage(e,t,n){return ya(e,{...n,signal:t})}static async decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return null;let t=new window.Image;if(t.src=e,typeof t.decode!="function")return null;try{await t.decode()}catch{return null}return t}static estimateDecodedBytes(e){return(e.naturalWidth||0)*(e.naturalHeight||0)*4}static readBudget(e){return typeof e=="number"&&!Number.isNaN(e)?Math.max(0,e):1/0}useAcquisition(e){return this.acquisition=e??null,this}useMissingReporter(e){return this.missingReporter=e??null,this}reportMissing(e){return!this.missingReporter||this.reportedMissing.has(e)?!!this.missingReporter:(this.reportedMissing.add(e),this.missingReporter({type:"image",src:e}),!0)}has(e){return this.entries.has(e)}wasCached(e){return this.seen.has(e)}add(e,t){return this.insert(e,t,0),this}remove(e){let t=this.entries.get(e);return t&&this.drop(t),this}get(e){let t=this.entries.get(e);if(t)return this.touch(t),t.url}isDecoded(e){return!!this.entries.get(e)?.decoded}clear(){for(let e of[...this.entries.values()])this.drop(e);return this.seen.clear(),this}size(){return this.entries.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t,n){let i=n?.retainDecoded===!0,r=i||n?.decode!==!1,s=this.entries.get(t);if(s&&(!i||s.decoded))return this.touch(s),o.settledToken();let a=this.preloadTasks.get(t);if(a)return this.followTask(a,e,t,n);if(s)return this.touch(s),this.runTask(e,t,new AbortController,()=>this.decodeAgain(t,s.url));let l=t,c={};this.game.hooks.rawTrigger("preloadImage",()=>[l,(p,d)=>{l=p,c={...c,...d}}]);let u=new AbortController;return this.runTask(e,t,u,()=>this.acquireAndDecode(t,l,u.signal,c,i,r))}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.entries.values(),e=>e.url)}retain(e){let t=new Set(e);for(let n of[...this.entries.values()])n.stale=!t.has(n.name),n.stale&&!this.isPinned(n)&&this.drop(n);return this}pin(e){return this.pinned=new Set(e),this.enforce(),this}hold(e){this.holds.set(e,(this.holds.get(e)??0)+1)}release(e){let t=this.holds.get(e);if(t===void 0)return;if(t>1){this.holds.set(e,t-1);return}this.holds.delete(e);let n=this.byUrl.get(e);if(n){if(n.stale&&!this.isPinned(n)){this.drop(n);return}this.enforce()}}getStats(){let e=0,t=0;for(let n of this.entries.values())n.decoded&&e++,this.isPinned(n)&&t++;return{entries:this.entries.size,blobBytes:this.blobBytes,decodedEntries:e,decodedBytes:this.decodedBytes,pinned:t,budget:this.budget()}}budget(){return{blobBytes:o.readBudget(this.game.config?.imageCacheBudgetBytes),decodedBytes:o.readBudget(this.game.config?.decodedImageBudgetBytes)}}isPinned(e){return this.pinned.has(e.name)||this.holds.has(e.url)}touch(e){this.entries.delete(e.name),this.entries.set(e.name,e)}insert(e,t,n,i=null){let r=this.entries.get(e);if(r){if(r.url===t)return this.touch(r),r;this.drop(r)}let s={name:e,url:t,bytes:n,decoded:null,decodedBytes:0,stale:!1,release:i};return this.entries.set(e,s),this.byUrl.set(t,s),this.seen.add(e),this.blobBytes+=n,this.enforce(),s}drop(e){this.dropDecoded(e),this.handBack(e.url,e.release),this.blobBytes-=e.bytes,this.entries.delete(e.name),this.byUrl.get(e.url)===e&&this.byUrl.delete(e.url)}dropDecoded(e){e.decoded&&(this.decodedBytes-=e.decodedBytes,e.decoded=null,e.decodedBytes=0)}retainDecoded(e,t){this.dropDecoded(e),e.decoded=t,e.decodedBytes=o.estimateDecodedBytes(t),this.decodedBytes+=e.decodedBytes,this.enforce()}enforce(){let e=this.budget();if(this.blobBytes>e.blobBytes)for(let t of[...this.entries.values()]){if(this.blobBytes<=e.blobBytes)break;this.isPinned(t)||this.drop(t)}if(this.decodedBytes>e.decodedBytes)for(let t of this.entries.values()){if(this.decodedBytes<=e.decodedBytes)break;t.decoded&&!this.isPinned(t)&&this.dropDecoded(t)}}async acquireAndDecode(e,t,n,i,r,s){let a=await this.acquire(e,t,n,i);if(!a)return;let{url:l,bytes:c,release:u}=a;if(this.insert(e,l,c,u),this.entries.get(e)?.url!==l||!s)return;let p=await o.decodeImage(l),d=this.entries.get(e);if(!d||d.url!==l){this.handBack(l,u);return}p&&r&&this.retainDecoded(d,p)}async acquire(e,t,n,i){if(this.acquisition){let a=await this.acquisition({type:"image",src:e},n);return!a||!a.url?null:{url:a.url,bytes:a.bytes??0,release:a.release??null}}let{url:r,bytes:s}=await o.getImage(t,n,i);return r?{url:r,bytes:s,release:null}:null}handBack(e,t){if(t){t();return}e.startsWith("blob:")&&URL.revokeObjectURL(e)}async decodeAgain(e,t){let n=await o.decodeImage(t),i=this.entries.get(e);n&&i&&i.url===t&&!i.decoded&&this.retainDecoded(i,n)}runTask(e,t,n,i){let r={promise:Promise.resolve(),controller:n,errorHandlers:[],failed:!1};r.promise=Promise.resolve().then(i).then(()=>{this.preloadTasks.delete(t)}).catch(a=>{r.failed=!0,this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${a}`),r.errorHandlers.forEach(l=>l(a))}),this.preloadTasks.set(t,r);let s={abort:()=>{n.abort(),this.preloadTasks.delete(t)},onFinished:a=>(r.promise.then(a),s),onErrored:a=>(r.errorHandlers.push(a),s)};return s}followTask(e,t,n,i){let r={abort:()=>{},onFinished:s=>(e.promise.then(()=>{if(e.failed){s();return}this.preload(t,n,i).onFinished(s)}),r),onErrored:s=>(e.errorHandlers.push(s),r)};return r}static settledToken(){let e={abort:()=>{},onFinished:t=>(Promise.resolve().then(t),e),onErrored:()=>e};return e}};var Ko=Lp(null);function jl({children:o}){let e=N(),[t]=Kl(()=>new at),[n]=Kl(()=>new _o(e));return us.createElement(us.Fragment,null,us.createElement(Ko,{value:{preloaded:t,cacheManager:n}},o))}function $t(){if(!Ko)throw new Error("usePreloaded must be used within a PreloadedProvider");return $l(Ko)}function ql(){return $l(Ko)}import{useLayoutEffect as Ql,useRef as Rp}from"react";function $o(o){let e=ql()?.cacheManager??null,t=Rp(null),n=()=>{t.current?.release(),t.current=null};Ql(()=>{let i=o.current;if(t.current?.element===i||(n(),!i||!e||typeof MutationObserver>"u"))return;let r=null,s=()=>{let l=i.getAttribute("src");l!==r&&(r!==null&&e.release(r),r=l,r!==null&&e.hold(r))},a=new MutationObserver(s);t.current={element:i,release:()=>{a.disconnect(),r!==null&&(e.release(r),r=null)}},s(),a.observe(i,{attributes:!0,attributeFilter:["src"]})}),Ql(()=>n,[])}function Yl(){let o=Mt(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return Fp(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?O.getSrcURL(s):null,l=s&&O.isTagSrc(s)?[...s.state.currentSrc]:null,c=Ya({character:n,sentence:i,portrait:s,currentSrc:a,tags:l,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=Op(c.source);return{visible:!!u,src:u,character:c.character,portrait:c.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Gp({className:o,style:e,alt:t,...n}){let i=Yl(),{cacheManager:r}=$t(),s=Np(null);if($o(s),!i.visible||!i.src)return null;let a=r.get(i.src)||i.src;return Mp.createElement("img",{...n,ref:s,"data-element-type":"dialog-avatar",className:Ip("dialog-avatar",o),src:a,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function Op(o){return o?k.srcToURL(o):null}function Fp(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var ps=Gp;import{useEffect as Vp}from"react";function Hp(){let o=Mt(),[e]=de(o.deps),t=se.getText(o.config.evaluatedWords);return Vp(()=>o.events.on(Oe.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as jo,useEffect as ds,useMemo as Up,useRef as Bp,useState as Xl}from"react";function Wp(){let o=Mt(),[e]=de(o.deps),[t,n]=Xl(!0),[i,r]=Xl(!0),s=Bp(null),a=o.config.gameState,l=o.config.action.sentence,c=l?.config.voiceId??null;ds(()=>o.events.on(Oe.Events.onFlush,()=>{e()}).cancel,[o]);let u=Up(()=>{if(!l)return null;try{return rt.getVoice(a,l)}catch{return null}},[a,l,c,l?.config.voice]);ds(()=>{s.current=null,r(!0)},[l]),ds(()=>{let m=!1,g=null,b=null,y=null;if(!u){n(!0);return}n(!1);let S=()=>{m||n(!0)};g=a.audioManager.getToken(u),g&&(g.isPlaying()||n(!0),b=()=>S(),y=()=>S(),g.once("ended",b),g.once("stop",y));let T=a.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{S()});return()=>{m=!0,T.cancel(),g&&b&&g.off("ended",b),g&&y&&g.off("stop",y)}},[a,u]);let p=jo(async m=>{let g=m??u;if(!g)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let b=g instanceof URL?Se.voice(g.toString()):typeof g=="string"?Se.voice(g):g,y=await a.getLiveGame().playSound(b);s.current=y;let S=()=>{r(!0)};return y.once("ended",S),y.once("stop",S),y},[a,u]),d=jo(()=>u,[u]),f=jo(()=>c,[c]),h=jo(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:p,getVoice:d,getVoiceId:f,getVoiceSrc:h}}import ms,{createContext as ed,useContext as td,useEffect as ec,useRef as nd}from"react";import{useState as zp}from"react";function qo(o){let[e]=zp(o);return e}import{AnimatePresence as _p}from"motion/react";var Qo=_p;import Di,{createContext as Qp,useContext as Yp,useEffect as Xp,useRef as Jp}from"react";import{useEffect as ki,useLayoutEffect as Kp}from"react";function $p(){let o=zt(),[e]=de();return ki(()=>o.onChange(e).cancel,[]),o.getPathname()}function jp(){let{router:o,path:e}=Ei(),[t]=de();return ki(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function qp(){let o=zt(),[e]=de();return ki(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Yo(o,e){let t=zt();Kp(()=>t.onUpdate(()=>o(t)).cancel,e),ki(()=>{o(t)},[])}function Pi(){let o=zt(),[e]=de();return ki(()=>o.onChange(e).cancel,[]),e}var Jl=Qp(null);function Li({children:o,path:e,consumedBy:t}){let i={router:zt(),path:e,consumedBy:t};return Di.createElement(Jl,{value:i},o)}function Ei(){let o=Yp(Jl);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new P(`Invalid useLayout call: Trying to access layout without a parent.
|
|
64
|
-
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Zp({children:o,name:e,propagate:t}){let n=N(),[i]=de(),{path:r,router:s,consumedBy:a}=Ei(),l=s.joinPath(r,e),c=qo(()=>s.createToken(l+"@layout")),u=s.getCurrentPath(),p=Jp(!1),d=h=>{p.current=h,i()},f=s.matchPath(u,l);if(Pi(),Yo(h=>{let m=h.matchPath(h.getCurrentPath(),l);if(p.current&&!m){if(!o){d(!1);return}h.registerUnmountingPath(c)}m&&h.isPathsUnmounting()&&h.unregisterUnmountingPath(c),m&&!p.current&&!h.isTransitioning()&&d(!0)},[f,o]),Xp(()=>{if(!f)return;let h=s.mount(l);return()=>{h.cancel()}},[l,s,f]),a)throw new P("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return Di.createElement(Li,{path:l},Di.createElement(Qo,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(c),d(!1)}},f&&p.current&&o))}function Zl({children:o}){return Pi(),Di.createElement(Li,{path:yn.rootPath},Di.createElement(Do,{"data-layout-path":yn.rootPath,key:yn.rootPath},o))}var fs=ed(null);function id(){return td(fs)}function od({children:o,name:e}){let[t]=de(),{path:n,router:i,consumedBy:r}=Ei(),s=id(),a=s?.name??e,l=a??n+"@default",c=a?i.joinPath(n,a):n,u=qo(()=>i.createToken(c+"@page")),p=i.getCurrentPath(),d=!a,f=nd(!1),h=y=>{f.current=y,t()},m=d&&i.exactMatch(p,n)||i.exactMatch(p,c);if(r&&r!==l)throw new P("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");Pi(),Yo(y=>{let S=d&&y.exactMatch(y.getCurrentPath(),n)||y.exactMatch(y.getCurrentPath(),c);if(f.current&&!S){if(!o){h(!1);return}y.registerUnmountingPath(u)}S&&y.isPathsUnmounting()&&y.unregisterUnmountingPath(u),S&&!f.current&&!y.isTransitioning()&&h(!0)},[m,o]),ec(()=>{if(!m)return;let y=d?i.mountDefaultHandler(c):i.mount(c);return i.emitOnPageMount(),()=>{y.cancel()}},[c,m]),ec(()=>()=>{i.unregisterUnmountingPath(u),h(!1)},[]);let g=ms.createElement(Li,{path:n,consumedBy:l},ms.createElement(Qo,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),h(!1)}},m&&f.current&&o));return(y=>s?ms.createElement(fs,{value:{name:null}},y):y)(g)}import hs,{useCallback as rd,useEffect as gs,useImperativeHandle as sd,useMemo as tc,useRef as ys,useState as ad}from"react";var ld=50,cd={position:"relative",width:"100%",height:"100%",overflow:"hidden"},nc={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function ud(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function ic(o,e){return e==null?o:Math.max(o,e)}function pd(o,e,t){return o<=0||e<=0||t<=0?{width:o,height:e}:o/e>t?{width:e*t,height:e}:{width:o,height:o/t}}var oc=hs.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:l,dataAttributes:c,onUpdate:u,children:p},d){let f=ys(null),[h,m]=ad({...nc,width:"0px",height:"0px"}),g=ys(u),b=ys(null);gs(()=>{g.current=u},[u]);let y=rd(()=>{let C=f.current;if(!C)return;let x=C.clientWidth,w=C.clientHeight;if(x<=0||w<=0||e<=0)return;let G=pd(x,w,e),I=ic(G.width,n),ae=ic(G.height,i),E=b.current;(!E||E.width!==I||E.height!==ae)&&(b.current={width:I,height:ae},m({...nc,width:`${I}px`,height:`${ae}px`}));let F=t>0?I/t:1;g.current?.({width:I,height:ae,scale:F,containerWidth:x,containerHeight:w})},[e,t,n,i]),S=tc(()=>ha(y,typeof r=="number"?r:ld),[y,r]);gs(()=>{y()},[y]),gs(()=>{let C=new ResizeObserver(()=>{S()});f.current&&C.observe(f.current);let x=()=>{S()};return window.addEventListener("resize",x),()=>{C.disconnect(),window.removeEventListener("resize",x)}},[S]),sd(d,()=>({requestUpdate:y}),[y]);let T=tc(()=>ud(c),[c]);return hs.createElement("div",{id:l,ref:f,style:cd,...T},hs.createElement("div",{className:s,style:{...h,...a}},p))}),rc=oc;function dd(){return N().getLiveGame()}import bs from"react";import md,{createContext as fd,useContext as hd,useEffect as gd,useState as sc}from"react";var yd={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},ac=fd({state:yd,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function jt(){return hd(ac)}function vs(){let{dialogs:o}=jt();return o}function vd(){let{isActive:o}=jt();return o}function Sd(){let{isVisible:o}=jt();return o}function Ss({children:o}){let t=N().getLiveGame().getGameState(),[n,i]=sc(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=sc(null);gd(()=>{let l=h=>({...h,dialogs:[...h.dialogs]}),c=t.events.on(L.EventTypes["event:state.nvl.enter"],(h,m)=>{i(l(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(L.EventTypes["event:state.nvl.exit"],()=>{i(l(t.getNvlState()))}),p=t.events.on(L.EventTypes["event:state.nvl.dialogAppend"],()=>{i(l(t.getNvlState()))}),d=t.events.on(L.EventTypes["event:state.nvl.visibilityChange"],(h,m)=>{i(l(t.getNvlState())),s(m||null)}),f=t.events.on(L.EventTypes["event:state.nvl.change"],h=>{i(l(h))});return()=>{c.cancel(),u.cancel(),p.cancel(),d.cancel(),f.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return md.createElement(ac.Provider,{value:a},o)}import{AnimatePresence as bd,motion as Td}from"motion/react";import Ad from"clsx";function Ts({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=jt(),{ratio:r}=be(),s=N(),a=i?.duration?i.duration/1e3:.3;return bs.createElement(bd,null,n&&bs.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},bs.createElement(Td.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:Ad("w-full h-full overflow-auto",e),style:{transform:s.config.useAspectScale?`scale(${r.state.scale})`:void 0,transformOrigin:"top left",width:s.config.useAspectScale?s.config.width:"100%",height:s.config.useAspectScale?s.config.height:"100%",...t}},o)))}import In from"react";function As({renderDialogItem:o,dialogs:e}){return In.createElement(Ts,{className:"bg-black/80 text-white p-16 inset-8"},In.createElement("div",{"data-element-type":"nvl-dialog-list",className:"flex flex-col space-y-4 p-4"},(e??[]).map((n,i)=>{let r=n.entry.character?In.createElement(sn,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=In.createElement(Sn,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return In.createElement("div",{key:`${n.entry.id}:${n.isActive?"active":"idle"}`,"data-element-type":"nvl-dialog-item","data-dialog-index":i,className:"nvl-dialog-item"},o?o({entry:n.entry,index:i,isActive:n.isActive,nametag:r,texts:s}):In.createElement(In.Fragment,null,r,s))})))}import Tt,{useMemo as Cd}from"react";import lc from"clsx";function xd({children:o,className:e,style:t,renderDialogItem:n}){let i=vs(),{state:r}=jt();return Tt.createElement("div",{"data-element-type":"nvl-dialog-list",className:lc("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>Tt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},Tt.createElement(wd,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?Tt.createElement(sn,{className:"nvl-character-name font-bold mr-2"}):null,texts:Tt.createElement(Sn,{className:"nvl-dialog-text"})}):o?Tt.Children.map(o,l=>Tt.isValidElement(l)?Tt.cloneElement(l,{entry:s,index:a}):l):Tt.createElement(cc,{entry:s,index:a})))))}function cc({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??Tt.createElement(Sn,{className:"nvl-dialog-text"});return Tt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:lc("nvl-dialog-item",t),style:n},r&&Tt.createElement(sn,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function wd({entry:o,children:e}){let n=N().getLiveGame().getGameState(),i=Cd(()=>o.sentence.evaluate(Ee.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",l=No({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return Tt.createElement(En,{value:l},e)}import Xo from"react";import{createPortal as kd}from"react-dom";var Cs=Xo.createContext(null),Pd={Portal:()=>null,measure:()=>null,container:null};function Ed(){let o=Xo.useContext(Cs);return Xo.useMemo(()=>{if(!o)return Pd;let e=t=>{let n=o.offsetWidth;return!n||!t.width?1:t.width/n};return{container:o,Portal:({children:t})=>kd(Xo.createElement("div",{style:{position:"absolute",left:0,top:0,pointerEvents:"auto"}},t),o),measure:t=>{if(!t)return null;let n=o.getBoundingClientRect(),i=e(n),r=t.getBoundingClientRect(),s=(r.left-n.left)/i,a=(r.top-n.top)/i,l=r.width/i,c=r.height/i;return{left:s,top:a,width:l,height:c,right:s+l,bottom:a+c}}}},[o])}import{useEffect as Dd}from"react";function Ld(o){let e=N();Dd(()=>{if(!o)return;let t=e.getLiveGame().getGameState();if(t)return t.suspendAdvance()},[o,e])}var Jo=class{constructor(e,t){this.emit=e;this.options=t;this.held=!1;this.delayTimer=null;this.repeatTimer=null}isHeld(){return this.held}press(){this.held||(this.clearTimers(),this.held=!0,this.emit(!1),this.options.delay===0?this.startRepeating():this.delayTimer=setTimeout(()=>{this.delayTimer=null,this.startRepeating()},this.options.delay))}release(){this.clearTimers(),this.held=!1}dispose(){this.release()}startRepeating(){this.repeatTimer=setInterval(()=>{this.emit(!0)},this.options.interval)}clearTimers(){this.delayTimer!==null&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.repeatTimer!==null&&(clearInterval(this.repeatTimer),this.repeatTimer=null)}};function pc({state:o}){let e=N(),t=zt(),[n]=vn(Y.Preferences.skipDelay),[i]=vn(Y.Preferences.skipInterval),[r]=Dn("skipAction");return Id(()=>{if(!e.getLiveGame().gameState.playerCurrent){o.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){o.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let a=new Jo(u=>{o.events.emit(L.EventTypes["event:state.player.skip"],u)},{delay:n,interval:i}),l=u=>{o.isAdvanceSuspended()||e.keyMap.match("skipAction",u.key)&&e.preference.getPreference(Y.Preferences.skip)&&(a.isHeld()||o.logger.verbose("KeyEventAnnouncer","Skipping"),a.press())},c=u=>{e.keyMap.match("skipAction",u.key)&&a.release()};if(e.config.useWindowListener){let u=e.getLiveGame().onWindowEvent("keydown",l).cancel,p=e.getLiveGame().onWindowEvent("keyup",c).cancel;return()=>{a.dispose(),u(),p()}}else{let u=e.getLiveGame().onPlayerEvent("keydown",l).cancel,p=e.getLiveGame().onPlayerEvent("keyup",c).cancel;return()=>{a.dispose(),u(),p()}}},[t,n,i,r]),uc.createElement(uc.Fragment,null)}import mc,{useEffect as Md}from"react";function dc({onStage:o,dialogShown:e,advanceSuspended:t}){return o?e?t?"ignore":"advance":"restoreDialog":"ignore"}function Nd(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var fc=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],Gd=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]','[data-element-type="interactive-word"]','[data-element-type="dialog-overlay"]'];function Od(o,e){return!o||e&&fc.some(t=>!!o.closest(t))?!1:[...Gd,...fc].some(t=>!!o.closest(t))}function hc(o,e){if(!e)return!1;let t=e.getBoundingClientRect();return o.clientX>=t.left&&o.clientX<=t.right&&o.clientY>=t.top&&o.clientY<=t.bottom}function gc({state:o}){let e=N();return Md(()=>{let t=e.getLiveGame().gameState?.playerCurrent;if(!t){o.logger.warn("StageClickAnnouncer","Failed to listen to playerElement events");return}let n=i=>{let r=i.target;if(!r||!t.contains(r)||!hc(i,t))return;let s=o.mainContentNode;if(s&&(!s.contains(r)||!hc(i,s))||Nd(r)||Od(r,o.isNvlMode()))return;let a=dc({onStage:!0,dialogShown:e.preference.getPreference(Y.Preferences.showDialog),advanceSuspended:o.isAdvanceSuspended()});if(a!=="ignore"){if(a==="restoreDialog"){e.preference.setPreference(Y.Preferences.showDialog,!0);return}o.events.emit(L.EventTypes["event:state.player.stageClick"]),o.recordStageClick()}};if(e.config.useWindowListener){let i=e.getLiveGame().onWindowEvent("click",n);return()=>{i.cancel()}}else{let i=e.getLiveGame().onPlayerEvent("click",n);return()=>{i.cancel()}}},[e,o]),mc.createElement(mc.Fragment,null)}import{useEffect as yc}from"react";function xs({gameState:o}){let e=o.audioManager,[t,n]=vn("globalVolume");return yc(()=>{n(e.getGlobalVolume())},[]),yc(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as Zo,useMemo as Fd,useRef as Sc}from"react";function vc(o){let e=Me.catSrc(o.srcManager?.src||[]),t=Me.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=[],s=new Set,a=o.state?.backgroundImage?.state?.currentSrc;if(k.isImageSrc(a)){let l=k.srcToURL(a);l&&(s.add(l),n.push(l))}for(let l of e.image){let c=Me.getSrc(l);!c||s.has(c)||(s.add(c),i.push(c))}for(let l of t.image){let c=Me.getSrc(l);!c||s.has(c)||(s.add(c),r.push(c))}return{firstFrame:n,critical:i,lookAhead:r,all:[...n,...i,...r],criticalAudio:e.audio}}function ws(o){let e=[],t=null;return{plan(r){return o.config.preloadAllImages?n(r):i(r)}};function n(r){if(r.kind!=="scene")return null;let s=vc(r.scene),a=o.config.preloadGate==="scene"?"gate":"soon";return{entries:[...s.firstFrame.map(c=>({type:"image",src:c,band:"gate",decode:!0})),...s.critical.map(c=>({type:"image",src:c,band:a,decode:!0})),...s.lookAhead.map(c=>({type:"image",src:c,band:"idle",decode:!1}))],audio:s.criticalAudio,keep:s.all,pin:s.firstFrame}}function i(r){if(r.kind!=="advance")return null;let s=r.story;if(!s)return null;t!==r.scene&&(e=[],t=r.scene);let a=o.getLiveGame(),l=a.stackModel?.getTopSync()?.node?.action||null,c=a.getAllPredictableActions(s,l,o.config.maxPreloadActions).map(d=>Me.getPreloadableSrc(s,d)).filter(d=>d!==null);for(let d of c)d.activeType==="scene"&&!e.includes(d)&&e.push(d);let u=new Set,p=[];for(let d of Me.catSrc([...e,...c]).image){let f=Me.getSrc(d);!f||u.has(f)||(u.add(f),p.push({type:"image",src:f,band:"idle",decode:!0}))}return{entries:p,keep:[...u]}}}var At="Preload";function bc({state:o}){let{preloaded:e,cacheManager:t}=$t(),n=N(),[i]=de(),r=Sc(new Set),s=o.getLastScene()||o.getPreloadingScene(),a=n.getLiveGame().story,l=Sc(s);l.current=s;let c=Fd(()=>n.config.preload??ws(n),[n]);function u(){o.logger.debug(At,"Preload unmounted"),e.events.emit(at.EventTypes["event:preloaded.unmount"])}return Zo(()=>o.events.on(L.EventTypes["event:state:flushPreloadedScenes"],()=>{i()}).cancel,[]),Zo(()=>(t.useAcquisition(c.acquire?c.acquire.bind(c):null),t.useMissingReporter(c.onMissing?c.onMissing.bind(c):null),o.useVideoMissingReporter(c.onMissing?c.onMissing.bind(c):null),()=>{t.useAcquisition(null),t.useMissingReporter(null),o.useVideoMissingReporter(null)}),[c,t]),Zo(()=>{if(!a||!s)return a?o.logger.debug(At,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(At,"Story not found, skipping preload"),u;if(typeof fetch>"u"&&!c.acquire)return e.events.emit(at.EventTypes["event:preloaded.complete"]),e.events.emit(at.EventTypes["event:preloaded.ready"]),o.logger.warn(At,"Fetch is not supported in this environment, skipping preload"),u;n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(At,"Cache cleared")),r.current.clear();let h={value:!1};return p({kind:"scene",scene:s,story:a},{gates:!0,cancelled:h}),e.events.emit(at.EventTypes["event:preloaded.mount"]),()=>{h.value=!0,u()}},[s,a,c]),Zo(()=>{if(!a)return;let h={value:!1},m=n.getLiveGame().onCurrentActionChange(({actionId:g})=>{p({kind:"advance",actionId:g,scene:l.current,story:a},{gates:!1,cancelled:h})});return()=>{h.value=!0,m.cancel()}},[a,c,n]),null;async function p(h,m){let g=()=>{e.events.emit(at.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(at.EventTypes["event:preloaded.ready"])};m.gates&&!n.config.waitForPreload&&e.events.emit(at.EventTypes["event:preloaded.ready"]);let b;try{b=await c.plan(h)}catch(y){o.logger.weakError(At,"Preload strategy failed to plan; nothing warmed",y),m.gates&&g();return}if(!m.cancelled.value){if(!b){m.gates&&g();return}b.pin&&t.pin(b.pin),b.keep&&t.retain(b.keep),b.audio&&o.audioManager.retainOnly([...b.audio]),b.video&&o.retainWarmVideos([...b.video]),await d(b,m,g)}}async function d(h,m,g){let b=performance.now(),y={gate:new Gn(n.config.preloadConcurrency,0),soon:new Gn(n.config.preloadConcurrency,0),idle:new Gn(n.config.preloadConcurrency,n.config.preloadDelay)},S=o.logger.group(At,!0);o.logger.debug(At,"preloading:",h);let T=0;for(let x of h.entries)f(y[x.band],x)&&(T+=1);S.end();let C=()=>{let x=t.getStats(),w=G=>(G/(1024*1024)).toFixed(1);return`${T} queued in ${(performance.now()-b).toFixed(0)}ms (${w(x.blobBytes)} MB fetched, ${w(x.decodedBytes)} MB decoded, ${x.pinned} pinned)`};await y.gate.start(),m.gates&&(o.logger.info(At,"Preload (gate)",C()),g()),!m.cancelled.value&&(await y.soon.start(),!m.cancelled.value&&(await y.idle.start(),m.cancelled.value||o.logger.info(At,"Preload (settled)",C())))}function f(h,m){let g=`${m.band}:${m.src}`;if(r.current.has(g))return!1;r.current.add(g);let b=m.decode??m.band!=="idle";return t.has(m.src)&&(!b||t.isDecoded(m.src))?(o.logger.debug(At,`Already warm (${m.band})`,m.src),!1):(h.addTask(()=>new Promise(y=>{t.preload(o,m.src,{retainDecoded:b,decode:b}).onFinished(()=>{o.logger.debug(At,`Warmed (${m.band})`,m.src),y()}).onErrored(()=>{o.logger.weakError(At,`Failed to warm (${m.band})`,m.src),y()})})),!0)}}import Ri from"react";import tr from"react";import ks,{useEffect as Ps,useLayoutEffect as Es,useRef as er,useState as Ds}from"react";function qt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:l,companionRefs:c}){let[u,p]=Ds(null),[d,f]=Ds(null),h=er(null),m=ks.useRef(null),[g]=Ds(()=>new ji("displayable.refGroup")),b=er(g.next()),y=er(ee()),T=N().getLiveGame().getGameState(),[C]=de([d,u,y]);Ps(()=>T.events.depends([T.events.on(L.EventTypes["event:state.player.skip"],ft)]).cancel,[d,u,y]),Es(()=>{if(I(),!u)return;if(y.current.some(([D])=>!D.current))throw new P("Displayable: Trying to access transition groups before they are mounted");let{controller:M,task:q}=u,ue=D=>{let ie=typeof a=="function"?a(u):a;y.current.forEach(([H],ye)=>{let Fe=q.resolve[ye],ni=typeof Fe=="function"?Fe:Fe.resolver;if(!ni)throw new P(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${ye}])`);let Ft=ni(...D),Yt=Q(ie[ye]||ie[ie.length-1]||{},Ft);E(H,l?l(Yt):Yt)})},ge=M.onUpdate(ue);ue(q.animations.map(D=>D.start));let W=!1;return Promise.all(y.current.map(([D])=>{let ie=D.current;return ie?.waitForLoad?ie.waitForLoad():Promise.resolve()})).then(()=>{W||M.start()}),()=>{W=!0,ge.cancel()}},[u]),Ps(()=>{if(!m.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Es(()=>{let M=e.toStyle(T,i);return Object.assign(m.current.style,M),G(),T.logger.debug("Displayable","Initial style applied",m.current,M),K(),()=>{F()}},[]);let x=er(()=>{});x.current=()=>{u||!m.current||(I(),!(d||h.current)&&(Object.assign(m.current.style,e.toStyle(T,i)),G()))},Es(()=>{h.current&&!o._getLoop()&&F(),x.current()});let{ratio:w}=be();Ps(()=>w.onUpdate(()=>{x.current(),requestAnimationFrame(()=>x.current())}),[w]);function G(){if(c)for(let{ref:M,project:q}of c)M.current&&Object.assign(M.current.style,q(e.get()))}function I(){let M=typeof a=="function"?a(u):a;if(!y.current||!y.current.length)throw new P("Displayable: Transition group refs are not initialized correctly");y.current.some(([q])=>!q.current)||y.current.forEach(([q],ue)=>{E(q,M[ue]||M[M.length-1]||{})})}function ae(M){T.logger.debug("Displayable","Transform applied",e.toStyle(T,i),m.current),C(),r?.(M)}function E(M,q){if(!M.current)throw new P("Displayable: Trying to assign properties to unmounted element");po(M.current,q,l)}function F(){h.current&&(h.current.stop(),h.current=null,T.logger.debug("Displayable","Loop stopped",o))}function K(){let M=o._getLoop();if(!M){F();return}h.current||he(M.transform,M.options)}function he(M,q){d&&(d.abort(),f(null)),F(),m.current&&(h.current=M.startLoop(e,{gameState:T,ref:m,overwrites:i,companionRefs:c},q))}function qe(M,q){return Qe(new ne({},{duration:M?.duration??0,ease:M?.ease??"linear"}),q)}function Qe(M,q){d&&(d.abort(),f(null)),F();let ue=M.animate(e,{gameState:T,ref:m,overwrites:i,companionRefs:c}),ge=new De(ue);return T.timelines.attachTimeline(ge),ue.onSkipControllerRegister(W=>{W.onAbort(()=>{ge.abort(),f(null)})}),f(ue),ue.then(()=>{f(null),ae(M),q(),K()}),ge}function Ot(M,q){u&&u.controller.complete();let ue=M.createTask(T),ge=M.requestAnimations(ue.animations),W=new v().registerSkipController(new B(ge.cancel)),D=new De(W);W.skipController.onAbort(()=>{ge.cancel()}),ge.onCanceled(()=>{D.abort(),p(null),T.logger.debug("Displayable","Transition cancelled",M)}),ge.onComplete(()=>{Ct(),p(null),s?.(M),q(),W.resolve()}),T.timelines.attachTimeline(D),p({task:ue,controller:ge,transition:M,resolve:q});let ie;if(y.current=ue.resolve.map(H=>{let ye=ks.createRef(),Fe=typeof H=="function"?void 0:H.key;if(!Fe)return[ye,g.next()];if(Fe==="target")return ie=g.next(),[ye,ie];if(Fe==="current")return[ye,b.current];throw new P("Displayable: Invalid key type")}),!ie)throw new P("Displayable: No target key found");return b.current=ie,D}function We(M){return T.logger.debug("initDisplayable",o),Qe(ne.immediate(e.get()),M)}function ft(){t&&d&&(d.abort(),f(null),T.logger.debug("transform skipped")),n&&u&&(u.controller.complete(),T.logger.debug("transition skipped"))}function ee(){return[[ks.createRef(),b.current]]}function Ct(){y.current.forEach(([M])=>{M.current=null}),y.current=ee()}return{transformRef:m,transitionRefs:y.current,transitionTask:u,initDisplayable:We,applyTransform:Qe,applyTransition:Ot,applyLoop:he,stopLoop:qe,updateStyleSync:I,flush:C,deps:[d,u,y]}}import{useEffect as Vd}from"react";function wt(o,e,t=[]){let i=N().getLiveGame().getGameState();return Vd(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Ls({state:o,text:e}){let{ratio:t}=be(),[n]=de(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyLoop:l,stopLoop:c,applyTransition:u,updateStyleSync:p,deps:d}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:f=>({width:"fit-content",transform:ne.propToCSSTransform(o,f,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return wt(e,{initDisplayable:s,applyTransform:a,applyLoop:l,stopLoop:c,applyTransition:u,flush:n,updateStyleSync:p},[...d]),tr.createElement(Kt.Div,{"data-element-type":"text"},tr.createElement(Kt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([f,h])=>tr.createElement("span",{key:h,ref:f,className:e.config.className},tr.createElement("span",null,e.state.text)))))}import Gt,{forwardRef as Bd,useCallback as or,useImperativeHandle as Wd,useLayoutEffect as Pc,useRef as bn,useState as Cc}from"react";import nr,{useEffect as Tc,useLayoutEffect as Hd,useRef as Xn,forwardRef as Ud}from"react";var Ac=Ud(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=Xn(null),{ratio:a}=be(),[l,c]=nr.useState(0),[u,p]=nr.useState(0),d=Xn(null),f=Xn(null),h=N(),m=Xn(!1),g=Xn(null),b=Xn(null);nr.useImperativeHandle(r,()=>s.current,[]),$o(s),Tc(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let C=()=>{let x=s.current;return!x||typeof x.decode!="function"?Promise.resolve():x.decode().catch(()=>{})};return m.current?C():(g.current||(g.current=new Promise(x=>{b.current=x})),g.current.then(C))},configurable:!0}})},[]),Hd(()=>(y(),a.onUpdate(y)),[o]),Tc(()=>{let C=new MutationObserver(x=>{x.forEach(w=>{w.type==="attributes"&&w.attributeName==="src"&&s.current&&y()})});return s.current&&C.observe(s.current,{attributes:!0}),()=>{C.disconnect()}},[o]);function y(){if(s.current&&s.current.naturalWidth){let C,x,w;if(s.current.naturalWidth*s.current.naturalHeight===1)C=a.state.width,x=a.state.height,w=`${C} / ${x}`;else{let E=t?h.config.width/s.current.naturalWidth:1;C=s.current.naturalWidth*a.state.scale*E,x=s.current.naturalHeight*a.state.scale*E,w="auto"}let G=d.current,I=!G||G.w!==C||G.h!==x||G.ar!==w,ae=!!o&&f.current!==o;if(!I&&!ae)return;I&&(d.current={w:C,h:x,ar:w},c(C),p(x),s.current.style.aspectRatio=w),o&&(f.current=o,o(C,x))}}function S(){y(),m.current=!0,b.current&&(b.current(),b.current=null,g.current=null),e&&e()}function T(){m.current=!0,b.current&&(b.current(),b.current=null,g.current=null)}return nr.createElement("img",{ref:s,onLoad:S,onError:T,width:l,height:u,alt:"",src:n,style:i})});Ac.displayName="AspectScaleImage";var ir=Ac;import xc from"clsx";import{motion as zd}from"motion/react";var Jn=0,wc=1/1024;function _d(o,e,t,n){let i=(o.width-e.width)/2,r=(o.height-e.height)/2;return Math.abs(i)*2<wc&&Math.abs(r)*2<wc?null:{top:n?"auto":0,bottom:n?0:"auto",left:t?"auto":0,right:t?0:"auto",transform:`translate(${t?-i:i}px, ${n?-r:r}px)`}}function Ec(o,e){let t=bn(null),n=or(()=>{!o.current||!t.current||(e?.(),Object.assign(o.current.style,{width:`${t.current.width}px`,height:`${t.current.height}px`}))},[o,e]);return Pc(()=>{n()},[]),or((i,r)=>{t.current={width:i,height:r},n()},[n])}var Kd={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Dc=Bd(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=bn(null),a=bn([]),l=o.findIndex(p=>p!==null),c=Ec(s),u=or((p,d)=>{c(p,d),n?.(p,d)},[c,n]);return Wd(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(p=>!p?.isLoaded||p.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(p=>p?.waitForLoad?p.waitForLoad():Promise.resolve())).then(()=>{})}),[]),Gt.createElement("div",{ref:s},o.map((p,d)=>p===null?null:Gt.createElement(ir,{key:"layer-"+d,ref:f=>{a.current[d]=f},src:t(p),style:Kd,autoFit:e,onSizeChanged:d===l?u:void 0,onLoad:d===l?i:void 0})))});Dc.displayName="LayerStack";function Rs(o){return{willChange:"filter, opacity",position:"absolute",top:0,left:0,right:0,bottom:0,transform:"none",translate:"none",opacity:1,clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat",filter:`brightness(${1-o})`}}function $d(o){return O.isStaticSrc(o)?o.state.currentSrc:O.getSrcURL(o)??void 0}var kc={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function Is(o){return{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o})`}}function jd(o,e){return qd(o,e).map(t=>({style:t}))}function qd(o,{layered:e,darkness:t,invertX:n,invertY:i,sizes:r}){let s=r[Jn];return o.map((a,l)=>{if(typeof a=="function")return e?kc:{...kc,willChange:"filter",filter:"brightness(1)"};let c=r[l],u=l!==Jn&&s&&c?_d(s,c,n,i):null;return e?u?{...Rs(t),...u}:Rs(t):u?{...Is(t),maxWidth:"none",maxHeight:"none",...u}:Is(t)})}function Qd({image:o,state:e}){let[t]=Cc(()=>new Z),[n,i]=Cc([]),{cacheManager:r}=$t(),s=bn([]),a=bn(null),l=bn(new Map),c=bn([]),u=O.isLayeredSrc(o)?O.getSrcURLs(o):null;function p(E){return!k.isInlineSrc(E)&&!r.wasCached(E)&&!r.isPreloading(E)&&!s.current.includes(E)&&(r.reportMissing(E)||e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${E}".
|
|
58
|
+
`?[...o,e]:[...o,{...e,revealFrom:t?e.text.length:0}]}function Ul(o,e,t=!1){o(n=>xp(n,e,t))}function Cp(o,e,t){return t||(o!==void 0?ve.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new ae(n.text,n.config)):[])}function wp(o,e,t){let n=Math.max(0,e??t);return typeof o=="object"?{enabled:o.enabled??!0,delay:Math.max(0,o.delay??n)}:{enabled:o??!0,delay:n}}function Vl(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function Ho(o){return o===void 0?void 0:On(o)}function Bl(o){return typeof o.tag2=="number"?o.tag2>=o.full.length-1:o.text.length>=o.full.length}function Wl({word:o,vertical:e,tateChuYoko:t,done:n,style:i,renderer:r,revealTail:s=0}){let a=o.config.ruby?Be.createElement("ruby",{className:"align-bottom inline-block"},Be.createElement("rt",{className:"block text-center"},o.config.ruby),is(o.text,e,t,s)):is(o.text,e,t,s);return r?Be.createElement(r,{text:o.text,fullText:o.full,revealed:Bl(o),done:n,style:i,config:o.config,data:o.config.data},a):a}function kp(o,e){return!!e&&Bl(o)}function as({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,writingMode:l,textOrientation:c,tateChuYoko:u,autoFit:p,autoFitMinFontSize:d,...f}){let h=G(),m=h.getLiveGame().getGameState(),g=Fl(null),[b,y]=os(()=>n&&!n.config.useTypeEffect?rs(n.config.evaluatedWords):[]),[S,T]=me();if(!n)throw new Error("Dialog state is required");Ln(()=>{if(!(!n.config.action.sentence||g.current))return m.logger.info("Initializing the sentence",n,g.current),m.schedule(({onCleanup:te})=>{if(!n.config.useTypeEffect){Al(n.config.evaluatedWords,n.config.firedTextEvents??new Set,m),n.dispatchComplete();return}y([]),g.current=R(),S(),g.current.onComplete(()=>{n.dispatchComplete()}),te(()=>{g.current?.timeline?.abort()})},0)},[]),Ln(()=>n.events.depends([n.events.on(Oe.Events.requestComplete,()=>{g.current?.interact()}),n.events.on(Oe.Events.forceSkip,()=>{n.isEnded()||g.current?.forceSkip()})]).cancel,[n,T]),Ln(()=>n.onFlush(()=>{S()}).cancel,[n]),Ln(()=>h.preference.events.depends([h.preference.onPreferenceChange(Y.Preferences.gameSpeed,()=>{g.current?.update()}),h.preference.onPreferenceChange(Y.Preferences.autoForward,()=>{g.current?.update()}),h.preference.onPreferenceChange(Y.Preferences.cps,()=>{g.current?.update()}),h.preference.onPreferenceChange(Y.Preferences.textRevealDuration,()=>{S()})]).cancel,[]);let E=(p??!0)&&!h.config.disableTextScaling,{offsets:A,revealed:C}=Ap(()=>Hl(b),[b]),L=Xr(n.config.useTypeEffect?h.preference.getPreference(Y.Preferences.textRevealDuration):0,h.preference.getPreference(Y.Preferences.cps),h.preference.getPreference(Y.Preferences.gameSpeed)),{containerRef:k,scale:X}=Ll({enabled:E,minFontSize:d??Pl,vertical:Pi(l),revealed:C});function R(){let te=new v,xt=new De(te).setGuard(m.guard),N=new Set,q=n.config.firedTextEvents??new Set,pe=new Set,ge=new Set,_=ss(n.config.evaluatedWords),D=null,oe=[],U=[],ye=()=>{oe.forEach(ze=>ze()),oe.length=0},Ve=()=>{if(U.length!==0)return{done:!1,value:U.shift()};let{done:ze,value:_e}=_.next();return{done:ze,value:_e}},ii=ze=>{let _e=cn=>{ze(cn),pe.delete(_e)};return pe.add(_e),{cancel:()=>{pe.delete(_e)}}},Vt=(ze,_e=!1)=>{Ul(y,ze,_e)},Yt=(ze=!1)=>{let _e=!1;for(;!_e;){let{done:cn,value:tt}=Ve();if(cn){_e=!0;break}if($e.isPause(tt)){if(ze)continue;_e=!0,U.push(tt);break}else pt.isTextEvent(tt)?Oo(tt,q,m):tt===`
|
|
59
|
+
`?y(lt=>[...lt,tt]):typeof tt=="object"&&"text"in tt&&!N.has(tt)&&(N.add(tt),Vt(tt,!0))}D&&!D.isSettled()?D.abort():(ge.forEach(cn=>cn()),te.resolve())};return m.schedule(async ze=>{let _e=!1,cn=!1;for(;!_e;){let{done:tt,value:lt}=Ve();if(tt){_e=cn=!0;break}if(pt.isTextEvent(lt)){Oo(lt,q,m);continue}let Wi=new v;if(m.timelines.attachTimeline(Wi),Wi.registerSkipController(new B(()=>{ye(),_e=!0,ze.retry()})),Wi.onSettled(()=>{ye()}),D=Wi,$e.isPause(lt)){let zi=$e.from(lt),_i=h.preference.getPreference(Y.Preferences.gameSpeed);if(zi.config.duration){let Ki=zi.config.duration/_i;await eo(Ki)}else{let Ki=h.preference.getPreference(Y.Preferences.autoForward),$i=v.race([v.create(fu=>{let hu=ii(gu=>{gu(),fu.resolve()});oe.push(()=>hu.cancel())}),...Ki?[v.delay(h.config.autoForwardDefaultPause/_i)]:[]]);m.timelines.attachTimeline($i),await v.wait($i)}}else{if(lt!==`
|
|
60
|
+
`&&N.has(lt))continue;N.add(lt),Vt(lt);let{gameSpeed:zi,cps:_i}=h.preference.getPreferences(),$i=1e3/((typeof lt=="object"&&"cps"in lt&<.cps!==void 0?lt.cps:_i)*zi);await eo($i)}}cn&&(ge.forEach(tt=>tt()),te.resolve())},0),{getToken:()=>te,interact:()=>{let ze=!1;pe.forEach(_e=>_e(()=>ze=!0)),!ze&&Yt()},update:()=>{D&&D.abort()},forceSkip:()=>{Yt(!0)},timeline:xt,onComplete:ze=>(ge.add(ze),{cancel:()=>{ge.delete(ze)}})}}let H=n.config.action.sentence;if(!H)return null;let z=s??"bold",le=H.config.fontSize??i,qe={fontWeight:H.config.bold?z:r,fontSize:ki(le)??Dl(),color:Ho(H.config.color??o),fontFamily:H.config.fontFamily??a,fontStyle:H.config.italic?"italic":void 0},Qe=te=>({fontWeight:te.config.bold||H.config.bold?z:r,fontSize:Rl(te.config,le),color:Ho(te.config.color??H.config.color??o),fontFamily:te.config.fontFamily??H.config.fontFamily??a,fontStyle:te.config.italic??H.config.italic?"italic":void 0,...Qr(te.config.emphasis)}),Ot=Pi(l),We=n.isEnded(),ft=(te,xt)=>{if(te===`
|
|
61
|
+
`)return Be.createElement("br",{key:xt});let N=Qe(te),q=jr(te.config.render),pe=kp(te,q);return Be.createElement(Kt.Span,{tag:`say.word.${xt}`,key:xt,"data-element-type":pe?"interactive-word":void 0,onClick:pe?ge=>ge.stopPropagation():void 0,style:{...N,...ns(),...Vn(h.config.app.debug,{outline:"1px dashed red"})},className:Fo("inline-block",te.config.className)},Be.createElement(Wl,{word:te,vertical:Ot,tateChuYoko:u,done:We,style:N,renderer:q,revealTail:Jr(L,A[xt]??0,te.text.length,C,te.revealFrom??0)}))};return Be.createElement("div",{...f,ref:k,className:Fo("whitespace-pre-wrap",e),style:{[Vo]:X,...Vn(L.duration>0,{[Yr]:`${L.duration}ms`}),...qe,...ts(l,c),...t}},b.map(ft))}function Pp({text:o,sentence:e,words:t,useTypeEffect:n=!0,loop:i=!0,restartDelay:r,cps:s,gameSpeed:a,pauseDuration:l,defaultColor:c,className:u,style:p,fontSize:d,fontWeight:f,fontWeightBold:h,fontFamily:m,writingMode:g,textOrientation:b,tateChuYoko:y,onCompleted:S,...T}){let E=al(),[,A]=os(0),C=E?.config??Y.DefaultConfig,L=E?.preference.getPreferences()??Y.DefaultPreference,k=s??L.cps,X=a??L.gameSpeed,R=l??C.autoForwardDefaultPause,H=r??C.autoForwardDefaultPause,z=Be.useMemo(()=>Cp(o,e,t),[o,e,t]),le=Be.useMemo(()=>wp(i,r,H),[i,r,H]),qe=Fl(S),[Qe,Ot]=os(()=>n?[]:rs(z));Ln(()=>{if(E)return E.preference.onPreferenceChange(()=>{A(D=>D+1)}).cancel},[E]),Ln(()=>{qe.current=S},[S]),Ln(()=>{let D=!1,oe=[],U=Math.max(.01,X),ye=Vt=>new Promise(Yt=>{let Xt=setTimeout(Yt,Math.max(0,Vt));oe.push(Xt)}),Ve=()=>{D||qe.current?.()};return n?z.length===0?(Ot([]),()=>{D=!0}):((async()=>{do{let Vt=ss(z);for(Ot([]);!D;){let{done:Yt,value:Xt}=Vt.next();if(Yt)break;if($e.isPause(Xt)){let ua=$e.from(Xt);await ye((ua.config.duration??R)/U)}else{if(pt.isTextEvent(Xt))continue;Ul(Ot,Xt),Xt===`
|
|
62
|
+
`?await ye(Vl(k,X)):await ye(Vl(Xt.cps??k,X))}}if(D)return;Ve(),le.enabled&&await ye(le.delay)}while(!D&&le.enabled)})(),()=>{D=!0,oe.forEach(Vt=>clearTimeout(Vt))}):(Ot(rs(z)),Ve(),()=>{D=!0})},[z,n,le,k,X,R]);let We=e?.config,ft=h??"bold",te={fontWeight:We?.bold?ft:f,fontSize:We?.fontSize??d,color:Ho(We?.color??c),fontFamily:We?.fontFamily??m,fontStyle:We?.italic?"italic":void 0},xt=D=>({fontWeight:D.config.bold||We?.bold?ft:f,fontSize:Il(D.config,We?.fontSize??d),color:Ho(D.config.color??We?.color??c),fontFamily:D.config.fontFamily??We?.fontFamily??m,fontStyle:D.config.italic??We?.italic?"italic":void 0,...Qr(D.config.emphasis)}),N=Pi(g),q=Xr(n?L.textRevealDuration:0,k,X),{offsets:pe,revealed:ge}=Hl(Qe),_=(D,oe)=>{if(D===`
|
|
63
|
+
`)return Be.createElement("br",{key:oe});let U=xt(D);return Be.createElement("span",{key:oe,style:{...U,...ns()},className:Fo("inline-block",D.config.className)},Be.createElement(Wl,{word:D,vertical:N,tateChuYoko:y,done:!1,style:U,renderer:jr(D.config.render),revealTail:Jr(q,pe[oe]??0,D.text.length,ge,D.revealFrom??0)}))};return Be.createElement("div",{...T,className:Fo("whitespace-pre-wrap",u),style:{...Vn(q.duration>0,{[Yr]:`${q.duration}ms`}),...te,...ts(g,b),...p}},Qe.map(_))}function zl(o){return Be.createElement(as,{...o,key:o.dialog?.config.action.id})}function Ep({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=Go({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Be.createElement(as,{...r,dialog:s,key:s.config.action.id})}function Dp(o){let e=Mt();return Be.createElement(as,{...o,dialog:e,key:e.config.action.id})}function Sn(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Be.createElement(Ep,{...o}):Be.createElement(Dp,{...o})}var Lp=Sn;import Bo,{useEffect as Rp,useLayoutEffect as Ip,useMemo as Kl,useRef as Mp,useState as Np}from"react";import Uo from"react";var ls=Uo.createContext(null);function cs(){let o=Uo.useContext(ls);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var us=Uo.createContext(null);function _l(){let o=Uo.useContext(us);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function Wo({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let l=Mp(null),{register:c,unregister:u,getIndex:p}=_l(),[d,f]=Np(-1),{choose:h,evaluated:m,gameState:g}=cs(),b=d===-1?null:m[d],y=Kl(()=>Ee.getCtx({gameState:g}),[g]),{hidden:S,disabled:T}=Kl(()=>{if(!b)return{hidden:!1,disabled:!1};let C=b.config.hidden?.evaluate(y)?.value??!1,L=!C&&(b.config.disabled?.evaluate(y)?.value??!1);return{hidden:C,disabled:L}},[b,y]);Ip(()=>{if(!l.current)return;let C=l;c(C);let L=p(C);return f(L),l.current.dataset.index=L.toString(),()=>u(C)},[c,u,p]),Rp(()=>{if(!t)return;let C=L=>{L.key.toLowerCase()===t.toLowerCase()&&!L.ctrlKey&&!L.metaKey&&(L.preventDefault(),L.stopPropagation(),E())};return window.addEventListener("keydown",C,!0),()=>{window.removeEventListener("keydown",C,!0)}},[t]);function E(){if(d===-1||!m[d]||S||T)return;let C=m[d];h({...C,evaluated:ae.getText(C.words||[])})}let A=b&&!S;return Bo.createElement(Bo.Fragment,null,Bo.createElement("button",{className:o,style:{...e,display:A?e?.display??void 0:"none"},onClick:E,ref:l,disabled:T},A&&Bo.createElement(zl,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Oe({useTypeEffect:!1,action:{sentence:b.prompt,words:b.words,character:null},gameState:g,evaluatedWords:b.words})})))}import zo from"react";import{AnimatePresence as Gp}from"motion/react";function _o({children:o,...e}){let t=Gp;return zo.createElement(zo.Fragment,null,zo.createElement("div",{...e},zo.createElement(t,null,o)))}import $l from"react";function sn({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=$l.useContext(En),l=e??o?.character??a?.config.action.character??null,c=n??l?.config.color,u=i??t??l?.state.name;return $l.createElement("div",{...s,style:{color:c?On(c):void 0,...r}},u)}import Fp from"clsx";import Hp,{useRef as Up}from"react";import ps,{createContext as Op,useContext as ql,useState as jl}from"react";var Rn=class Rn{constructor(){this.preloaded=[];this.events=new ee}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Rn.EventTypes["event:preloaded.add"],e),this.events.emit(Rn.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(i=>this.getSrc(i));return this.preloaded=this.preloaded.filter(i=>!n.includes(this.getSrc(i))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(Rn.EventTypes["event:preloaded.remove"],e),this.events.emit(Rn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Me.getSrc(e)}};Rn.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.complete":"event:preloaded.complete","event:preloaded.unmount":"event:preloaded.unmount"};var at=Rn;var Ko=class o{constructor(e){this.game=e;this.entries=new Map;this.byUrl=new Map;this.preloadTasks=new Map;this.holds=new Map;this.pinned=new Set;this.seen=new Set;this.blobBytes=0;this.decodedBytes=0;this.acquisition=null;this.missingReporter=null;this.reportedMissing=new Set;this.game.addSideEffect(()=>{this.abortAll(),this.clear()})}static getImage(e,t,n){return va(e,{...n,signal:t})}static async decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return null;let t=new window.Image;if(t.src=e,typeof t.decode!="function")return null;try{await t.decode()}catch{return null}return t}static estimateDecodedBytes(e){return(e.naturalWidth||0)*(e.naturalHeight||0)*4}static readBudget(e){return typeof e=="number"&&!Number.isNaN(e)?Math.max(0,e):1/0}useAcquisition(e){return this.acquisition=e??null,this}useMissingReporter(e){return this.missingReporter=e??null,this}reportMissing(e){return!this.missingReporter||this.reportedMissing.has(e)?!!this.missingReporter:(this.reportedMissing.add(e),this.missingReporter({type:"image",src:e}),!0)}has(e){return this.entries.has(e)}wasCached(e){return this.seen.has(e)}add(e,t){return this.insert(e,t,0),this}remove(e){let t=this.entries.get(e);return t&&this.drop(t),this}get(e){let t=this.entries.get(e);if(t)return this.touch(t),t.url}isDecoded(e){return!!this.entries.get(e)?.decoded}clear(){for(let e of[...this.entries.values()])this.drop(e);return this.seen.clear(),this}size(){return this.entries.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t,n){let i=n?.retainDecoded===!0,r=i||n?.decode!==!1,s=this.entries.get(t);if(s&&(!i||s.decoded))return this.touch(s),o.settledToken();let a=this.preloadTasks.get(t);if(a)return this.followTask(a,e,t,n);if(s)return this.touch(s),this.runTask(e,t,new AbortController,()=>this.decodeAgain(t,s.url));let l=t,c={};this.game.hooks.rawTrigger("preloadImage",()=>[l,(p,d)=>{l=p,c={...c,...d}}]);let u=new AbortController;return this.runTask(e,t,u,()=>this.acquireAndDecode(t,l,u.signal,c,i,r))}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.entries.values(),e=>e.url)}retain(e){let t=new Set(e);for(let n of[...this.entries.values()])n.stale=!t.has(n.name),n.stale&&!this.isPinned(n)&&this.drop(n);return this}pin(e){return this.pinned=new Set(e),this.enforce(),this}hold(e){this.holds.set(e,(this.holds.get(e)??0)+1)}release(e){let t=this.holds.get(e);if(t===void 0)return;if(t>1){this.holds.set(e,t-1);return}this.holds.delete(e);let n=this.byUrl.get(e);if(n){if(n.stale&&!this.isPinned(n)){this.drop(n);return}this.enforce()}}getStats(){let e=0,t=0;for(let n of this.entries.values())n.decoded&&e++,this.isPinned(n)&&t++;return{entries:this.entries.size,blobBytes:this.blobBytes,decodedEntries:e,decodedBytes:this.decodedBytes,pinned:t,budget:this.budget()}}budget(){return{blobBytes:o.readBudget(this.game.config?.imageCacheBudgetBytes),decodedBytes:o.readBudget(this.game.config?.decodedImageBudgetBytes)}}isPinned(e){return this.pinned.has(e.name)||this.holds.has(e.url)}touch(e){this.entries.delete(e.name),this.entries.set(e.name,e)}insert(e,t,n,i=null){let r=this.entries.get(e);if(r){if(r.url===t)return this.touch(r),r;this.drop(r)}let s={name:e,url:t,bytes:n,decoded:null,decodedBytes:0,stale:!1,release:i};return this.entries.set(e,s),this.byUrl.set(t,s),this.seen.add(e),this.blobBytes+=n,this.enforce(),s}drop(e){this.dropDecoded(e),this.handBack(e.url,e.release),this.blobBytes-=e.bytes,this.entries.delete(e.name),this.byUrl.get(e.url)===e&&this.byUrl.delete(e.url)}dropDecoded(e){e.decoded&&(this.decodedBytes-=e.decodedBytes,e.decoded=null,e.decodedBytes=0)}retainDecoded(e,t){this.dropDecoded(e),e.decoded=t,e.decodedBytes=o.estimateDecodedBytes(t),this.decodedBytes+=e.decodedBytes,this.enforce()}enforce(){let e=this.budget();if(this.blobBytes>e.blobBytes)for(let t of[...this.entries.values()]){if(this.blobBytes<=e.blobBytes)break;this.isPinned(t)||this.drop(t)}if(this.decodedBytes>e.decodedBytes)for(let t of this.entries.values()){if(this.decodedBytes<=e.decodedBytes)break;t.decoded&&!this.isPinned(t)&&this.dropDecoded(t)}}async acquireAndDecode(e,t,n,i,r,s){let a=await this.acquire(e,t,n,i);if(!a)return;let{url:l,bytes:c,release:u}=a;if(this.insert(e,l,c,u),this.entries.get(e)?.url!==l||!s)return;let p=await o.decodeImage(l),d=this.entries.get(e);if(!d||d.url!==l){this.handBack(l,u);return}p&&r&&this.retainDecoded(d,p)}async acquire(e,t,n,i){if(this.acquisition){let a=await this.acquisition({type:"image",src:e},n);return!a||!a.url?null:{url:a.url,bytes:a.bytes??0,release:a.release??null}}let{url:r,bytes:s}=await o.getImage(t,n,i);return r?{url:r,bytes:s,release:null}:null}handBack(e,t){if(t){t();return}e.startsWith("blob:")&&URL.revokeObjectURL(e)}async decodeAgain(e,t){let n=await o.decodeImage(t),i=this.entries.get(e);n&&i&&i.url===t&&!i.decoded&&this.retainDecoded(i,n)}runTask(e,t,n,i){let r={promise:Promise.resolve(),controller:n,errorHandlers:[],failed:!1};r.promise=Promise.resolve().then(i).then(()=>{this.preloadTasks.delete(t)}).catch(a=>{r.failed=!0,this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${a}`),r.errorHandlers.forEach(l=>l(a))}),this.preloadTasks.set(t,r);let s={abort:()=>{n.abort(),this.preloadTasks.delete(t)},onFinished:a=>(r.promise.then(a),s),onErrored:a=>(r.errorHandlers.push(a),s)};return s}followTask(e,t,n,i){let r={abort:()=>{},onFinished:s=>(e.promise.then(()=>{if(e.failed){s();return}this.preload(t,n,i).onFinished(s)}),r),onErrored:s=>(e.errorHandlers.push(s),r)};return r}static settledToken(){let e={abort:()=>{},onFinished:t=>(Promise.resolve().then(t),e),onErrored:()=>e};return e}};var $o=Op(null);function Ql({children:o}){let e=G(),[t]=jl(()=>new at),[n]=jl(()=>new Ko(e));return ps.createElement(ps.Fragment,null,ps.createElement($o,{value:{preloaded:t,cacheManager:n}},o))}function $t(){if(!$o)throw new Error("usePreloaded must be used within a PreloadedProvider");return ql($o)}function Yl(){return ql($o)}import{useLayoutEffect as Xl,useRef as Vp}from"react";function jo(o){let e=Yl()?.cacheManager??null,t=Vp(null),n=()=>{t.current?.release(),t.current=null};Xl(()=>{let i=o.current;if(t.current?.element===i||(n(),!i||!e||typeof MutationObserver>"u"))return;let r=null,s=()=>{let l=i.getAttribute("src");l!==r&&(r!==null&&e.release(r),r=l,r!==null&&e.hold(r))},a=new MutationObserver(s);t.current={element:i,release:()=>{a.disconnect(),r!==null&&(e.release(r),r=null)}},s(),a.observe(i,{attributes:!0,attributeFilter:["src"]})}),Xl(()=>n,[])}function Jl(){let o=Mt(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return zp(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?O.getSrcURL(s):null,l=s&&O.isTagSrc(s)?[...s.state.currentSrc]:null,c=Ja({character:n,sentence:i,portrait:s,currentSrc:a,tags:l,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=Wp(c.source);return{visible:!!u,src:u,character:c.character,portrait:c.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Bp({className:o,style:e,alt:t,...n}){let i=Jl(),{cacheManager:r}=$t(),s=Up(null);if(jo(s),!i.visible||!i.src)return null;let a=r.get(i.src)||i.src;return Hp.createElement("img",{...n,ref:s,"data-element-type":"dialog-avatar",className:Fp("dialog-avatar",o),src:a,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function Wp(o){return o?w.srcToURL(o):null}function zp(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var ds=Bp;import{useEffect as _p}from"react";function Kp(){let o=Mt(),[e]=me(o.deps),t=ae.getText(o.config.evaluatedWords);return _p(()=>o.events.on(Oe.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as qo,useEffect as ms,useMemo as $p,useRef as jp,useState as Zl}from"react";function qp(){let o=Mt(),[e]=me(o.deps),[t,n]=Zl(!0),[i,r]=Zl(!0),s=jp(null),a=o.config.gameState,l=o.config.action.sentence,c=l?.config.voiceId??null;ms(()=>o.events.on(Oe.Events.onFlush,()=>{e()}).cancel,[o]);let u=$p(()=>{if(!l)return null;try{return rt.getVoice(a,l)}catch{return null}},[a,l,c,l?.config.voice]);ms(()=>{s.current=null,r(!0)},[l]),ms(()=>{let m=!1,g=null,b=null,y=null;if(!u){n(!0);return}n(!1);let S=()=>{m||n(!0)};g=a.audioManager.getToken(u),g&&(g.isPlaying()||n(!0),b=()=>S(),y=()=>S(),g.once("ended",b),g.once("stop",y));let T=a.events.on(I.EventTypes["event:state.player.lineEnd"],()=>{S()});return()=>{m=!0,T.cancel(),g&&b&&g.off("ended",b),g&&y&&g.off("stop",y)}},[a,u]);let p=qo(async m=>{let g=m??u;if(!g)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let b=g instanceof URL?Se.voice(g.toString()):typeof g=="string"?Se.voice(g):g,y=await a.getLiveGame().playSound(b);s.current=y;let S=()=>{r(!0)};return y.once("ended",S),y.once("stop",S),y},[a,u]),d=qo(()=>u,[u]),f=qo(()=>c,[c]),h=qo(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:p,getVoice:d,getVoiceId:f,getVoiceSrc:h}}import fs,{createContext as sd,useContext as ad,useEffect as nc,useRef as ld}from"react";import{useState as Qp}from"react";function Qo(o){let[e]=Qp(o);return e}import{AnimatePresence as Yp}from"motion/react";var Yo=Yp;import Ri,{createContext as td,useContext as nd,useEffect as id,useRef as od}from"react";import{useEffect as Ei,useLayoutEffect as Xp}from"react";function Jp(){let o=zt(),[e]=me();return Ei(()=>o.onChange(e).cancel,[]),o.getPathname()}function Zp(){let{router:o,path:e}=Li(),[t]=me();return Ei(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function ed(){let o=zt(),[e]=me();return Ei(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Xo(o,e){let t=zt();Xp(()=>t.onUpdate(()=>o(t)).cancel,e),Ei(()=>{o(t)},[])}function Di(){let o=zt(),[e]=me();return Ei(()=>o.onChange(e).cancel,[]),e}var ec=td(null);function Ii({children:o,path:e,consumedBy:t}){let i={router:zt(),path:e,consumedBy:t};return Ri.createElement(ec,{value:i},o)}function Li(){let o=nd(ec);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new P(`Invalid useLayout call: Trying to access layout without a parent.
|
|
64
|
+
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function rd({children:o,name:e,propagate:t}){let n=G(),[i]=me(),{path:r,router:s,consumedBy:a}=Li(),l=s.joinPath(r,e),c=Qo(()=>s.createToken(l+"@layout")),u=s.getCurrentPath(),p=od(!1),d=h=>{p.current=h,i()},f=s.matchPath(u,l);if(Di(),Xo(h=>{let m=h.matchPath(h.getCurrentPath(),l);if(p.current&&!m){if(!o){d(!1);return}h.registerUnmountingPath(c)}m&&h.isPathsUnmounting()&&h.unregisterUnmountingPath(c),m&&!p.current&&!h.isTransitioning()&&d(!0)},[f,o]),id(()=>{if(!f)return;let h=s.mount(l);return()=>{h.cancel()}},[l,s,f]),a)throw new P("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return Ri.createElement(Ii,{path:l},Ri.createElement(Yo,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(c),d(!1)}},f&&p.current&&o))}function tc({children:o}){return Di(),Ri.createElement(Ii,{path:yn.rootPath},Ri.createElement(Lo,{"data-layout-path":yn.rootPath,key:yn.rootPath},o))}var hs=sd(null);function cd(){return ad(hs)}function ud({children:o,name:e}){let[t]=me(),{path:n,router:i,consumedBy:r}=Li(),s=cd(),a=s?.name??e,l=a??n+"@default",c=a?i.joinPath(n,a):n,u=Qo(()=>i.createToken(c+"@page")),p=i.getCurrentPath(),d=!a,f=ld(!1),h=y=>{f.current=y,t()},m=d&&i.exactMatch(p,n)||i.exactMatch(p,c);if(r&&r!==l)throw new P("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");Di(),Xo(y=>{let S=d&&y.exactMatch(y.getCurrentPath(),n)||y.exactMatch(y.getCurrentPath(),c);if(f.current&&!S){if(!o){h(!1);return}y.registerUnmountingPath(u)}S&&y.isPathsUnmounting()&&y.unregisterUnmountingPath(u),S&&!f.current&&!y.isTransitioning()&&h(!0)},[m,o]),nc(()=>{if(!m)return;let y=d?i.mountDefaultHandler(c):i.mount(c);return i.emitOnPageMount(),()=>{y.cancel()}},[c,m]),nc(()=>()=>{i.unregisterUnmountingPath(u),h(!1)},[]);let g=fs.createElement(Ii,{path:n,consumedBy:l},fs.createElement(Yo,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),h(!1)}},m&&f.current&&o));return(y=>s?fs.createElement(hs,{value:{name:null}},y):y)(g)}import gs,{useCallback as pd,useEffect as ys,useImperativeHandle as dd,useMemo as ic,useRef as vs,useState as md}from"react";var fd=50,hd={position:"relative",width:"100%",height:"100%",overflow:"hidden"},oc={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function gd(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function rc(o,e){return e==null?o:Math.max(o,e)}function yd(o,e,t){return o<=0||e<=0||t<=0?{width:o,height:e}:o/e>t?{width:e*t,height:e}:{width:o,height:o/t}}var sc=gs.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:l,dataAttributes:c,onUpdate:u,children:p},d){let f=vs(null),[h,m]=md({...oc,width:"0px",height:"0px"}),g=vs(u),b=vs(null);ys(()=>{g.current=u},[u]);let y=pd(()=>{let E=f.current;if(!E)return;let A=E.clientWidth,C=E.clientHeight;if(A<=0||C<=0||e<=0)return;let L=yd(A,C,e),k=rc(L.width,n),X=rc(L.height,i),R=b.current;(!R||R.width!==k||R.height!==X)&&(b.current={width:k,height:X},m({...oc,width:`${k}px`,height:`${X}px`}));let H=t>0?k/t:1;g.current?.({width:k,height:X,scale:H,containerWidth:A,containerHeight:C})},[e,t,n,i]),S=ic(()=>ga(y,typeof r=="number"?r:fd),[y,r]);ys(()=>{y()},[y]),ys(()=>{let E=new ResizeObserver(()=>{S()});f.current&&E.observe(f.current);let A=()=>{S()};return window.addEventListener("resize",A),()=>{E.disconnect(),window.removeEventListener("resize",A)}},[S]),dd(d,()=>({requestUpdate:y}),[y]);let T=ic(()=>gd(c),[c]);return gs.createElement("div",{id:l,ref:f,style:hd,...T},gs.createElement("div",{className:s,style:{...h,...a}},p))}),ac=sc;function vd(){return G().getLiveGame()}import Ts from"react";import Sd,{createContext as bd,useContext as Td,useEffect as Ad,useState as lc}from"react";var xd={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},cc=bd({state:xd,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function jt(){return Td(cc)}function Ss(){let{dialogs:o}=jt();return o}function Cd(){let{isActive:o}=jt();return o}function wd(){let{isVisible:o}=jt();return o}function bs({children:o}){let t=G().getLiveGame().getGameState(),[n,i]=lc(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=lc(null);Ad(()=>{let l=h=>({...h,dialogs:[...h.dialogs]}),c=t.events.on(I.EventTypes["event:state.nvl.enter"],(h,m)=>{i(l(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(I.EventTypes["event:state.nvl.exit"],()=>{i(l(t.getNvlState()))}),p=t.events.on(I.EventTypes["event:state.nvl.dialogAppend"],()=>{i(l(t.getNvlState()))}),d=t.events.on(I.EventTypes["event:state.nvl.visibilityChange"],(h,m)=>{i(l(t.getNvlState())),s(m||null)}),f=t.events.on(I.EventTypes["event:state.nvl.change"],h=>{i(l(h))});return()=>{c.cancel(),u.cancel(),p.cancel(),d.cancel(),f.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return Sd.createElement(cc.Provider,{value:a},o)}import{AnimatePresence as kd,motion as Pd}from"motion/react";import Ed from"clsx";function As({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=jt(),{ratio:r}=be(),s=G(),a=i?.duration?i.duration/1e3:.3;return Ts.createElement(kd,null,n&&Ts.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},Ts.createElement(Pd.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:Ed("w-full h-full overflow-auto",e),style:{transform:s.config.useAspectScale?`scale(${r.state.scale})`:void 0,transformOrigin:"top left",width:s.config.useAspectScale?s.config.width:"100%",height:s.config.useAspectScale?s.config.height:"100%",...t}},o)))}import In from"react";function xs({renderDialogItem:o,dialogs:e}){return In.createElement(As,{className:"bg-black/80 text-white p-16 inset-8"},In.createElement("div",{"data-element-type":"nvl-dialog-list",className:"flex flex-col space-y-4 p-4"},(e??[]).map((n,i)=>{let r=n.entry.character?In.createElement(sn,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=In.createElement(Sn,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return In.createElement("div",{key:`${n.entry.id}:${n.isActive?"active":"idle"}`,"data-element-type":"nvl-dialog-item","data-dialog-index":i,className:"nvl-dialog-item"},o?o({entry:n.entry,index:i,isActive:n.isActive,nametag:r,texts:s}):In.createElement(In.Fragment,null,r,s))})))}import Tt,{useMemo as Dd}from"react";import uc from"clsx";function Ld({children:o,className:e,style:t,renderDialogItem:n}){let i=Ss(),{state:r}=jt();return Tt.createElement("div",{"data-element-type":"nvl-dialog-list",className:uc("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>Tt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},Tt.createElement(Rd,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?Tt.createElement(sn,{className:"nvl-character-name font-bold mr-2"}):null,texts:Tt.createElement(Sn,{className:"nvl-dialog-text"})}):o?Tt.Children.map(o,l=>Tt.isValidElement(l)?Tt.cloneElement(l,{entry:s,index:a}):l):Tt.createElement(pc,{entry:s,index:a})))))}function pc({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??Tt.createElement(Sn,{className:"nvl-dialog-text"});return Tt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:uc("nvl-dialog-item",t),style:n},r&&Tt.createElement(sn,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function Rd({entry:o,children:e}){let n=G().getLiveGame().getGameState(),i=Dd(()=>o.sentence.evaluate(Ee.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",l=Go({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return Tt.createElement(En,{value:l},e)}import Jo from"react";import{createPortal as Id}from"react-dom";var Cs=Jo.createContext(null),Md={Portal:()=>null,measure:()=>null,container:null};function Nd(){let o=Jo.useContext(Cs);return Jo.useMemo(()=>{if(!o)return Md;let e=t=>{let n=o.offsetWidth;return!n||!t.width?1:t.width/n};return{container:o,Portal:({children:t})=>Id(Jo.createElement("div",{style:{position:"absolute",left:0,top:0,pointerEvents:"auto"}},t),o),measure:t=>{if(!t)return null;let n=o.getBoundingClientRect(),i=e(n),r=t.getBoundingClientRect(),s=(r.left-n.left)/i,a=(r.top-n.top)/i,l=r.width/i,c=r.height/i;return{left:s,top:a,width:l,height:c,right:s+l,bottom:a+c}}}},[o])}import{useEffect as Gd}from"react";function Od(o){let e=G();Gd(()=>{if(!o)return;let t=e.getLiveGame().getGameState();if(t)return t.suspendAdvance()},[o,e])}var Zo=class{constructor(e,t){this.emit=e;this.options=t;this.held=!1;this.delayTimer=null;this.repeatTimer=null}isHeld(){return this.held}press(){this.held||(this.clearTimers(),this.held=!0,this.emit(!1),this.options.delay===0?this.startRepeating():this.delayTimer=setTimeout(()=>{this.delayTimer=null,this.startRepeating()},this.options.delay))}release(){this.clearTimers(),this.held=!1}dispose(){this.release()}startRepeating(){this.repeatTimer=setInterval(()=>{this.emit(!0)},this.options.interval)}clearTimers(){this.delayTimer!==null&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.repeatTimer!==null&&(clearInterval(this.repeatTimer),this.repeatTimer=null)}};function mc({state:o}){let e=G(),t=zt(),[n]=vn(Y.Preferences.skipDelay),[i]=vn(Y.Preferences.skipInterval),[r]=Dn("skipAction");return Fd(()=>{if(!e.getLiveGame().gameState.playerCurrent){o.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){o.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let a=new Zo(u=>{o.events.emit(I.EventTypes["event:state.player.skip"],u)},{delay:n,interval:i}),l=u=>{o.isAdvanceSuspended()||e.keyMap.match("skipAction",u.key)&&e.preference.getPreference(Y.Preferences.skip)&&(a.isHeld()||o.logger.verbose("KeyEventAnnouncer","Skipping"),a.press())},c=u=>{e.keyMap.match("skipAction",u.key)&&a.release()};if(e.config.useWindowListener){let u=e.getLiveGame().onWindowEvent("keydown",l).cancel,p=e.getLiveGame().onWindowEvent("keyup",c).cancel;return()=>{a.dispose(),u(),p()}}else{let u=e.getLiveGame().onPlayerEvent("keydown",l).cancel,p=e.getLiveGame().onPlayerEvent("keyup",c).cancel;return()=>{a.dispose(),u(),p()}}},[t,n,i,r]),dc.createElement(dc.Fragment,null)}import hc,{useEffect as Hd}from"react";function fc({onStage:o,dialogShown:e,advanceSuspended:t}){return o?e?t?"ignore":"advance":"restoreDialog":"ignore"}function Ud(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var gc=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],Bd=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]','[data-element-type="interactive-word"]','[data-element-type="dialog-overlay"]'];function Wd(o,e){return!o||e&&gc.some(t=>!!o.closest(t))?!1:[...Bd,...gc].some(t=>!!o.closest(t))}function yc(o,e){if(!e)return!1;let t=e.getBoundingClientRect();return o.clientX>=t.left&&o.clientX<=t.right&&o.clientY>=t.top&&o.clientY<=t.bottom}function vc({state:o}){let e=G();return Hd(()=>{let t=e.getLiveGame().gameState?.playerCurrent;if(!t){o.logger.warn("StageClickAnnouncer","Failed to listen to playerElement events");return}let n=i=>{let r=i.target;if(!r||!t.contains(r)||!yc(i,t))return;let s=o.mainContentNode;if(s&&(!s.contains(r)||!yc(i,s))||Ud(r)||Wd(r,o.isNvlMode()))return;let a=fc({onStage:!0,dialogShown:e.preference.getPreference(Y.Preferences.showDialog),advanceSuspended:o.isAdvanceSuspended()});if(a!=="ignore"){if(a==="restoreDialog"){e.preference.setPreference(Y.Preferences.showDialog,!0);return}o.events.emit(I.EventTypes["event:state.player.stageClick"]),o.recordStageClick()}};if(e.config.useWindowListener){let i=e.getLiveGame().onWindowEvent("click",n);return()=>{i.cancel()}}else{let i=e.getLiveGame().onPlayerEvent("click",n);return()=>{i.cancel()}}},[e,o]),hc.createElement(hc.Fragment,null)}import{useEffect as Sc}from"react";function ws({gameState:o}){let e=o.audioManager,[t,n]=vn("globalVolume");return Sc(()=>{n(e.getGlobalVolume())},[]),Sc(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as er,useMemo as zd,useRef as Tc}from"react";function bc(o){let e=Me.catSrc(o.srcManager?.src||[]),t=Me.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=[],s=new Set,a=o.state?.backgroundImage?.state?.currentSrc;if(w.isImageSrc(a)){let l=w.srcToURL(a);l&&(s.add(l),n.push(l))}for(let l of e.image){let c=Me.getSrc(l);!c||s.has(c)||(s.add(c),i.push(c))}for(let l of t.image){let c=Me.getSrc(l);!c||s.has(c)||(s.add(c),r.push(c))}return{firstFrame:n,critical:i,lookAhead:r,all:[...n,...i,...r],criticalAudio:e.audio}}function ks(o){let e=[],t=null;return{plan(r){return o.config.preloadAllImages?n(r):i(r)}};function n(r){if(r.kind!=="scene")return null;let s=bc(r.scene),a=o.config.preloadGate==="scene"?"gate":"soon";return{entries:[...s.firstFrame.map(c=>({type:"image",src:c,band:"gate",decode:!0})),...s.critical.map(c=>({type:"image",src:c,band:a,decode:!0})),...s.lookAhead.map(c=>({type:"image",src:c,band:"idle",decode:!1}))],audio:s.criticalAudio,keep:s.all,pin:s.firstFrame}}function i(r){if(r.kind!=="advance")return null;let s=r.story;if(!s)return null;t!==r.scene&&(e=[],t=r.scene);let a=o.getLiveGame(),l=a.stackModel?.getTopSync()?.node?.action||null,c=a.getAllPredictableActions(s,l,o.config.maxPreloadActions).map(d=>Me.getPreloadableSrc(s,d)).filter(d=>d!==null);for(let d of c)d.activeType==="scene"&&!e.includes(d)&&e.push(d);let u=new Set,p=[];for(let d of Me.catSrc([...e,...c]).image){let f=Me.getSrc(d);!f||u.has(f)||(u.add(f),p.push({type:"image",src:f,band:"idle",decode:!0}))}return{entries:p,keep:[...u]}}}var At="Preload";function Ac({state:o}){let{preloaded:e,cacheManager:t}=$t(),n=G(),[i]=me(),r=Tc(new Set),s=o.getLastScene()||o.getPreloadingScene(),a=n.getLiveGame().story,l=Tc(s);l.current=s;let c=zd(()=>n.config.preload??ks(n),[n]);function u(){o.logger.debug(At,"Preload unmounted"),e.events.emit(at.EventTypes["event:preloaded.unmount"])}return er(()=>o.events.on(I.EventTypes["event:state:flushPreloadedScenes"],()=>{i()}).cancel,[]),er(()=>(t.useAcquisition(c.acquire?c.acquire.bind(c):null),t.useMissingReporter(c.onMissing?c.onMissing.bind(c):null),o.useVideoMissingReporter(c.onMissing?c.onMissing.bind(c):null),()=>{t.useAcquisition(null),t.useMissingReporter(null),o.useVideoMissingReporter(null)}),[c,t]),er(()=>{if(!a||!s)return a?o.logger.debug(At,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(At,"Story not found, skipping preload"),u;if(typeof fetch>"u"&&!c.acquire)return e.events.emit(at.EventTypes["event:preloaded.complete"]),e.events.emit(at.EventTypes["event:preloaded.ready"]),o.logger.warn(At,"Fetch is not supported in this environment, skipping preload"),u;n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(At,"Cache cleared")),r.current.clear();let h={value:!1};return p({kind:"scene",scene:s,story:a},{gates:!0,cancelled:h}),e.events.emit(at.EventTypes["event:preloaded.mount"]),()=>{h.value=!0,u()}},[s,a,c]),er(()=>{if(!a)return;let h={value:!1},m=n.getLiveGame().onCurrentActionChange(({actionId:g})=>{p({kind:"advance",actionId:g,scene:l.current,story:a},{gates:!1,cancelled:h})});return()=>{h.value=!0,m.cancel()}},[a,c,n]),null;async function p(h,m){let g=()=>{e.events.emit(at.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(at.EventTypes["event:preloaded.ready"])};m.gates&&!n.config.waitForPreload&&e.events.emit(at.EventTypes["event:preloaded.ready"]);let b;try{b=await c.plan(h)}catch(y){o.logger.weakError(At,"Preload strategy failed to plan; nothing warmed",y),m.gates&&g();return}if(!m.cancelled.value){if(!b){m.gates&&g();return}b.pin&&t.pin(b.pin),b.keep&&t.retain(b.keep),b.audio&&o.audioManager.retainOnly([...b.audio]),b.video&&o.retainWarmVideos([...b.video]),await d(b,m,g)}}async function d(h,m,g){let b=performance.now(),y={gate:new Gn(n.config.preloadConcurrency,0),soon:new Gn(n.config.preloadConcurrency,0),idle:new Gn(n.config.preloadConcurrency,n.config.preloadDelay)},S=o.logger.group(At,!0);o.logger.debug(At,"preloading:",h);let T=0;for(let A of h.entries)f(y[A.band],A)&&(T+=1);S.end();let E=()=>{let A=t.getStats(),C=L=>(L/(1024*1024)).toFixed(1);return`${T} queued in ${(performance.now()-b).toFixed(0)}ms (${C(A.blobBytes)} MB fetched, ${C(A.decodedBytes)} MB decoded, ${A.pinned} pinned)`};await y.gate.start(),m.gates&&(o.logger.info(At,"Preload (gate)",E()),g()),!m.cancelled.value&&(await y.soon.start(),!m.cancelled.value&&(await y.idle.start(),m.cancelled.value||o.logger.info(At,"Preload (settled)",E())))}function f(h,m){let g=`${m.band}:${m.src}`;if(r.current.has(g))return!1;r.current.add(g);let b=m.decode??m.band!=="idle";return t.has(m.src)&&(!b||t.isDecoded(m.src))?(o.logger.debug(At,`Already warm (${m.band})`,m.src),!1):(h.addTask(()=>new Promise(y=>{t.preload(o,m.src,{retainDecoded:b,decode:b}).onFinished(()=>{o.logger.debug(At,`Warmed (${m.band})`,m.src),y()}).onErrored(()=>{o.logger.weakError(At,`Failed to warm (${m.band})`,m.src),y()})})),!0)}}import Mi from"react";import nr from"react";import Ps,{useEffect as Es,useLayoutEffect as Ds,useRef as tr,useState as Ls}from"react";function qt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:l,companionRefs:c}){let[u,p]=Ls(null),[d,f]=Ls(null),h=tr(null),m=Ps.useRef(null),[g]=Ls(()=>new Qi("displayable.refGroup")),b=tr(g.next()),y=tr(te()),T=G().getLiveGame().getGameState(),[E]=me([d,u,y]);Es(()=>T.events.depends([T.events.on(I.EventTypes["event:state.player.skip"],ft)]).cancel,[d,u,y]),Ds(()=>{if(k(),!u)return;if(y.current.some(([D])=>!D.current))throw new P("Displayable: Trying to access transition groups before they are mounted");let{controller:N,task:q}=u,pe=D=>{let oe=typeof a=="function"?a(u):a;y.current.forEach(([U],ye)=>{let Ve=q.resolve[ye],ii=typeof Ve=="function"?Ve:Ve.resolver;if(!ii)throw new P(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${ye}])`);let Vt=ii(...D),Yt=Q(oe[ye]||oe[oe.length-1]||{},Vt);R(U,l?l(Yt):Yt)})},ge=N.onUpdate(pe);pe(q.animations.map(D=>D.start));let _=!1;return Promise.all(y.current.map(([D])=>{let oe=D.current;return oe?.waitForLoad?oe.waitForLoad():Promise.resolve()})).then(()=>{_||N.start()}),()=>{_=!0,ge.cancel()}},[u]),Es(()=>{if(!m.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Ds(()=>{let N=e.toStyle(T,i);return Object.assign(m.current.style,N),L(),T.logger.debug("Displayable","Initial style applied",m.current,N),z(),()=>{H()}},[]);let A=tr(()=>{});A.current=()=>{u||!m.current||(k(),!(d||h.current)&&(Object.assign(m.current.style,e.toStyle(T,i)),L()))},Ds(()=>{h.current&&!o._getLoop()&&H(),A.current()});let{ratio:C}=be();Es(()=>C.onUpdate(()=>{A.current(),requestAnimationFrame(()=>A.current())}),[C]);function L(){if(c)for(let{ref:N,project:q}of c)N.current&&Object.assign(N.current.style,q(e.get()))}function k(){let N=typeof a=="function"?a(u):a;if(!y.current||!y.current.length)throw new P("Displayable: Transition group refs are not initialized correctly");y.current.some(([q])=>!q.current)||y.current.forEach(([q],pe)=>{R(q,N[pe]||N[N.length-1]||{})})}function X(N){T.logger.debug("Displayable","Transform applied",e.toStyle(T,i),m.current),E(),r?.(N)}function R(N,q){if(!N.current)throw new P("Displayable: Trying to assign properties to unmounted element");mi(N.current,q,l)}function H(){h.current&&(h.current.stop(),h.current=null,T.logger.debug("Displayable","Loop stopped",o))}function z(){let N=o._getLoop();if(!N){H();return}h.current||le(N.transform,N.options)}function le(N,q){d&&(d.abort(),f(null)),H(),m.current&&(h.current=N.startLoop(e,{gameState:T,ref:m,overwrites:i,companionRefs:c},q))}function qe(N,q){return Qe(new ie({},{duration:N?.duration??0,ease:N?.ease??"linear"}),q)}function Qe(N,q){d&&(d.abort(),f(null)),H();let pe=N.animate(e,{gameState:T,ref:m,overwrites:i,companionRefs:c}),ge=new De(pe);return T.timelines.attachTimeline(ge),pe.onSkipControllerRegister(_=>{_.onAbort(()=>{ge.abort(),f(null)})}),f(pe),pe.then(()=>{f(null),X(N),q(),z()}),ge}function Ot(N,q){u&&u.controller.complete();let pe=N.createTask(T),ge=N.requestAnimations(pe.animations),_=new v().registerSkipController(new B(ge.cancel)),D=new De(_);_.skipController.onAbort(()=>{ge.cancel()}),ge.onCanceled(()=>{D.abort(),p(null),T.logger.debug("Displayable","Transition cancelled",N)}),ge.onComplete(()=>{xt(),p(null),s?.(N),q(),_.resolve()}),T.timelines.attachTimeline(D),p({task:pe,controller:ge,transition:N,resolve:q});let oe;if(y.current=pe.resolve.map(U=>{let ye=Ps.createRef(),Ve=typeof U=="function"?void 0:U.key;if(!Ve)return[ye,g.next()];if(Ve==="target")return oe=g.next(),[ye,oe];if(Ve==="current")return[ye,b.current];throw new P("Displayable: Invalid key type")}),!oe)throw new P("Displayable: No target key found");return b.current=oe,D}function We(N){return T.logger.debug("initDisplayable",o),Qe(ie.immediate(e.get()),N)}function ft(){t&&d&&(d.abort(),f(null),T.logger.debug("transform skipped")),n&&u&&(u.controller.complete(),T.logger.debug("transition skipped"))}function te(){return[[Ps.createRef(),b.current]]}function xt(){y.current.forEach(([N])=>{N.current=null}),y.current=te()}return{transformRef:m,transitionRefs:y.current,transitionTask:u,initDisplayable:We,applyTransform:Qe,applyTransition:Ot,applyLoop:le,stopLoop:qe,updateStyleSync:k,flush:E,deps:[d,u,y]}}import{useEffect as _d}from"react";function wt(o,e,t=[]){let i=G().getLiveGame().getGameState();return _d(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Rs({state:o,text:e}){let{ratio:t}=be(),[n]=me(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyLoop:l,stopLoop:c,applyTransition:u,updateStyleSync:p,deps:d}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:f=>({width:"fit-content",transform:ie.propToCSSTransform(o,f,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return wt(e,{initDisplayable:s,applyTransform:a,applyLoop:l,stopLoop:c,applyTransition:u,flush:n,updateStyleSync:p},[...d]),nr.createElement(Kt.Div,{"data-element-type":"text"},nr.createElement(Kt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([f,h])=>nr.createElement("span",{key:h,ref:f,className:e.config.className},nr.createElement("span",null,e.state.text)))))}import Gt,{forwardRef as jd,useCallback as rr,useImperativeHandle as qd,useLayoutEffect as Dc,useRef as bn,useState as wc}from"react";import ir,{useEffect as xc,useLayoutEffect as Kd,useRef as Xn,forwardRef as $d}from"react";var Cc=$d(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=Xn(null),{ratio:a}=be(),[l,c]=ir.useState(0),[u,p]=ir.useState(0),d=Xn(null),f=Xn(null),h=G(),m=Xn(!1),g=Xn(null),b=Xn(null);ir.useImperativeHandle(r,()=>s.current,[]),jo(s),xc(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let E=()=>{let A=s.current;return!A||typeof A.decode!="function"?Promise.resolve():A.decode().catch(()=>{})};return m.current?E():(g.current||(g.current=new Promise(A=>{b.current=A})),g.current.then(E))},configurable:!0}})},[]),Kd(()=>(y(),a.onUpdate(y)),[o]),xc(()=>{let E=new MutationObserver(A=>{A.forEach(C=>{C.type==="attributes"&&C.attributeName==="src"&&s.current&&y()})});return s.current&&E.observe(s.current,{attributes:!0}),()=>{E.disconnect()}},[o]);function y(){if(s.current&&s.current.naturalWidth){let E,A,C;if(s.current.naturalWidth*s.current.naturalHeight===1)E=a.state.width,A=a.state.height,C=`${E} / ${A}`;else{let R=t?h.config.width/s.current.naturalWidth:1;E=s.current.naturalWidth*a.state.scale*R,A=s.current.naturalHeight*a.state.scale*R,C="auto"}let L=d.current,k=!L||L.w!==E||L.h!==A||L.ar!==C,X=!!o&&f.current!==o;if(!k&&!X)return;k&&(d.current={w:E,h:A,ar:C},c(E),p(A),s.current.style.aspectRatio=C),o&&(f.current=o,o(E,A))}}function S(){y(),m.current=!0,b.current&&(b.current(),b.current=null,g.current=null),e&&e()}function T(){m.current=!0,b.current&&(b.current(),b.current=null,g.current=null)}return ir.createElement("img",{ref:s,onLoad:S,onError:T,width:l,height:u,alt:"",src:n,style:i})});Cc.displayName="AspectScaleImage";var or=Cc;import kc from"clsx";import{motion as Qd}from"motion/react";var Jn=0,Pc=1/1024;function Yd(o,e,t,n){let i=(o.width-e.width)/2,r=(o.height-e.height)/2;return Math.abs(i)*2<Pc&&Math.abs(r)*2<Pc?null:{top:n?"auto":0,bottom:n?0:"auto",left:t?"auto":0,right:t?0:"auto",transform:`translate(${t?-i:i}px, ${n?-r:r}px)`}}function Lc(o,e){let t=bn(null),n=rr(()=>{!o.current||!t.current||(e?.(),Object.assign(o.current.style,{width:`${t.current.width}px`,height:`${t.current.height}px`}))},[o,e]);return Dc(()=>{n()},[]),rr((i,r)=>{t.current={width:i,height:r},n()},[n])}var Xd={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Rc=jd(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=bn(null),a=bn([]),l=o.findIndex(p=>p!==null),c=Lc(s),u=rr((p,d)=>{c(p,d),n?.(p,d)},[c,n]);return qd(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(p=>!p?.isLoaded||p.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(p=>p?.waitForLoad?p.waitForLoad():Promise.resolve())).then(()=>{})}),[]),Gt.createElement("div",{ref:s},o.map((p,d)=>p===null?null:Gt.createElement(or,{key:"layer-"+d,ref:f=>{a.current[d]=f},src:t(p),style:Xd,autoFit:e,onSizeChanged:d===l?u:void 0,onLoad:d===l?i:void 0})))});Rc.displayName="LayerStack";function Is(o){return{willChange:"filter, opacity",position:"absolute",top:0,left:0,right:0,bottom:0,transform:"none",translate:"none",opacity:1,clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat",filter:`brightness(${1-o})`}}function Jd(o){return O.isStaticSrc(o)?o.state.currentSrc:O.getSrcURL(o)??void 0}var Ec={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function Ms(o){return{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o})`}}function Zd(o,e){return em(o,e).map(t=>({style:t}))}function em(o,{layered:e,darkness:t,invertX:n,invertY:i,sizes:r}){let s=r[Jn];return o.map((a,l)=>{if(typeof a=="function")return e?Ec:{...Ec,willChange:"filter",filter:"brightness(1)"};let c=r[l],u=l!==Jn&&s&&c?Yd(s,c,n,i):null;return e?u?{...Is(t),...u}:Is(t):u?{...Ms(t),maxWidth:"none",maxHeight:"none",...u}:Ms(t)})}function tm({image:o,state:e}){let[t]=wc(()=>new ee),[n,i]=wc([]),{cacheManager:r}=$t(),s=bn([]),a=bn(null),l=bn(new Map),c=bn([]),u=O.isLayeredSrc(o)?O.getSrcURLs(o):null;function p(R){return!w.isInlineSrc(R)&&!r.wasCached(R)&&!r.isPreloading(R)&&!s.current.includes(R)&&(r.reportMissing(R)||e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${R}".
|
|
65
65
|
This may be caused by complicated image action behavior that cannot be predicted.
|
|
66
|
-
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(E)),r.get(E)||E}let{transformRef:d,transitionRefs:f,transitionTask:h,initDisplayable:m,applyTransition:g,applyTransform:b,applyLoop:y,stopLoop:S,updateStyleSync:T,flush:C,deps:x}=qt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:E=>{if(E){let{invertX:K,invertY:he}=e.getStory().getInversionConfig();return jd(E.task.resolve,{layered:!!u,darkness:o.state.darkness,invertX:K,invertY:he,sizes:c.current.map(qe=>l.current.get(qe))})}if(u)return[{style:Rs(o.state.darkness)}];let F=$d(o);return[{style:{...Is(o.state.darkness),backgroundColor:k.isColor(F)?k.colorToString(F):void 0},src:k.isImageSrc(F)?k.srcToURL(F):O.DefaultImagePlaceholder}]},propOverwrite:E=>E.src?{...E,src:p(E.src)}:E});wt(o,{createWearable:E=>{i(F=>[...F,E])},disposeWearable:E=>{i(F=>F.filter(K=>K.getId()!==E.getId()))},initDisplayable:m,applyTransform:b,applyLoop:y,stopLoop:S,applyTransition:g,events:t,updateStyleSync:T,flush:C},[...x]);let w=or(()=>{t.emit("event:image.onLoad")},[t]),G=Ec(a,w),I=bn(new Map),ae=(E,F)=>{let K=F?`${E}:sizing`:E,he=I.current.get(K);return he||(he=(qe,Qe)=>{l.current.set(E,{width:qe,height:Qe}),F&&G(qe,Qe)},I.current.set(K,he)),he};return c.current=f.map(([,E])=>E),Pc(()=>{let E=new Set(c.current);l.current.forEach((F,K)=>{E.has(K)||l.current.delete(K)}),I.current.forEach((F,K)=>{E.has(K.replace(/:sizing$/,""))||I.current.delete(K)})}),Gt.createElement(zd.div,{ref:d,className:"absolute w-max h-max","data-element-type":"image"},Gt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},u?f.map(([E,F],K)=>{let he=h?h.task.resolve[K]:null;if(he&&typeof he=="function")return Gt.createElement(ir,{key:F,ref:E,autoFit:o.config.autoFit});let qe=he?he.key==="target"?h.transition._getTargetLayers():h.transition._getPrevLayers():u;return Gt.createElement(Dc,{key:F,ref:E,src:qe||u,autoFit:o.config.autoFit,resolveSrc:p,onSizeChanged:ae(F,K===Jn),onLoad:K===Jn?w:void 0})}):f.map(([E,F],K)=>Gt.createElement(ir,{key:F,ref:E,autoFit:o.config.autoFit,onSizeChanged:ae(F,K===Jn),onLoad:K===Jn?w:void 0})),Gt.createElement("div",{className:xc("w-full h-full top-0 left-0 absolute")},n.map(E=>Gt.createElement("div",{className:xc("w-full h-full relative"),key:"wearable-"+E.getId()},Gt.createElement(Lc,{image:E,state:e}))))))}var Lc=Gt.memo(Qd),Rc=Lc;import sr,{useEffect as Ms,useMemo as em,useRef as ar}from"react";var Yd=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,Xd=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function Ic(o,e){if(typeof e!="string"||!e.length)return o;if(Yd.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=Jd(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+Zd(r+e.replace(/\\/g,"/"))}function Jd(o){let e=Xd.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function Zd(o){let e=o.split("/"),t=[];for(let n=0;n<e.length;n++){let i=e[n];if(!(i==="."||i===""&&n!==e.length-1)){if(i===".."){t.pop();continue}t.push(i)}}return t.join("/")}var rr=class{constructor(){this.backends=new Map;this.reportedMissing=new Set}register(e){if(!e||typeof e.name!="string"||!e.name.length)throw new Error("A puppet backend must have a non-empty name.");if(typeof e.mount!="function")throw new Error(`Puppet backend "${e.name}" must implement mount().`);return this.backends.set(e.name,e),this.reportedMissing.delete(e.name),this}get(e){return this.backends.get(e)||null}has(e){return this.backends.has(e)}list(){return Array.from(this.backends.keys())}unregister(e){return this.backends.delete(e)}reportMissing(e,t){return this.reportedMissing.has(e)?!1:(this.reportedMissing.add(e),t(`No puppet backend is registered under "${e}". The element keeps its place on the stage, its transform and its saved state, but draws nothing. Register one with game.registerPuppetBackend({name, mount}) before the game mounts.`),!0)}};function Ns({state:o,puppet:e}){let[t]=de(),{cacheManager:n}=$t(),i=ar(null),r=em(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=ar(r);s.current=r;let{transformRef:a,transitionRefs:l,initDisplayable:c,applyTransform:u,applyLoop:p,stopLoop:d,applyTransition:f,updateStyleSync:h,deps:m}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipImageTransform,skipTransition:o.game.config.allowSkipImageTransition,transitionsProps:[{style:{position:"relative",width:`${r.width}px`,height:`${r.height}px`}}]});wt(e,{initDisplayable:c,applyTransform:u,applyLoop:p,stopLoop:d,applyTransition:f,updateStyleSync:h,flush:t},[...m]),Ms(()=>{let S=i.current;if(!S)return;let T=o.game,C=e.config.backend,x=T.getPuppetBackend(C);if(!x)return e._setStatus("missing-backend"),T.getPuppetBackendRegistry().reportMissing(C,I=>{o.logger.warn("Puppet",I)}),()=>{e._setStatus("unmounted")};let w;try{w=x.mount(S,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:y,resolveSibling:I=>y(Ic(e.config.src,I)),warn:(I,ae)=>{o.logger.warn("Puppet",I,ae)}})}catch(I){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${C}" threw while mounting "${e.config.src}"`,I),()=>{e._setStatus("unmounted")}}let G=!1;return e._attachInstance(w),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!G&&typeof w.ready=="function"?w.ready():void 0).then(()=>{G||e._setStatus("ready")}).catch(I=>{G||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${C}" failed to load "${e.config.src}"`,I))}),()=>{G=!0,e._attachInstance(null),e._setStatus("unmounted");try{w.dispose()}catch(I){o.logger.error("Puppet",`Backend "${C}" threw while disposing`,I)}}},[]);let g=ar(r);Ms(()=>{let S=g.current;if(S.width===r.width&&S.height===r.height)return;g.current=r;let T=e._getInstance();if(!(!T||typeof T.resize!="function"))try{T.resize(r)}catch(C){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,C)}},[r]);let b=ar(new Set);Ms(()=>{let S=b.current;return()=>{S.forEach(T=>n.release(T)),S.clear()}},[]);function y(S){if(k.isDataURI(S))return S;let T=n.get(S);return T?(b.current.has(T)||(b.current.add(T),n.hold(T)),T):S}return sr.createElement(Kt.Div,{"data-element-type":"puppet"},sr.createElement(Kt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},l.map(([S,T])=>sr.createElement("div",{key:T,ref:S,className:e.config.className},sr.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function Gs({state:o,displayable:e}){return Ri.createElement(Ri.Fragment,null,e.map(t=>{if(t instanceof Pn)return Ri.createElement(Ls,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof O)return Ri.createElement(Rc,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof Rt)return Ri.createElement(Ns,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import lr,{useEffect as tm}from"react";import{motion as nm}from"motion/react";function Mc({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:l,stopLoop:c,updateStyleSync:u,deps:p}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return wt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:l,stopLoop:c,updateStyleSync:u},[...p]),tm(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),lr.createElement(lr.Fragment,null,lr.createElement(nm.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([d,f])=>lr.createElement("div",{className:"relative w-full h-full",ref:d,key:f},t))))}async function Nc(o,e,t,n){let i=e.state.backgroundMusic,r=i&&o.audioManager.isManaged(i)?o.audioManager.stop(i,n):null;if(r&&t===i&&await r,t)try{await o.audioManager.playSoundToken(t,{end:t.state.volume,duration:n}),e.state.backgroundMusic=t}catch{e.state.backgroundMusic=null}else e.state.backgroundMusic=null;r&&await r}import im from"clsx";import{useEffect as Os,useRef as om}from"react";import Fs from"react";function Vs({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=om(null);return Os(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),Os(()=>n.events.depends([n.events.on(Je.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),Os(()=>(n.events.emit(Je.EventTypes["event:scene.mount"]),o.events.emit(L.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(Je.EventTypes["event:scene.unmount"]),o.events.emit(L.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),wt(n,{setBackgroundMusic(s,a){return Nc(o,n,s,a)}}),Fs.createElement("div",{className:im(e,"w-full h-full absolute"),ref:r,"data-element-type":"scene","data-scene-id":n.getId()},[...i.entries()].sort(([s],[a])=>s.state.zIndex-a.state.zIndex).map(([s,a])=>Fs.createElement(Mc,{state:o,layer:s,key:s.getId()},Fs.createElement(Gs,{state:o,displayable:a}))))}import{AnimatePresence as lm}from"motion/react";import{useEffect as cm,useReducer as um,useRef as cr}from"react";import rm from"clsx";import Qt,{useCallback as Hs,useMemo as sm,useRef as am}from"react";function Us({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=N(),a=am([]),l=Hs(h=>(a.current.push(h),a.current.indexOf(h)),[]),c=Hs(h=>{let m=a.current.indexOf(h);m!==-1&&a.current.splice(m,1)},[]),u=Hs(h=>a.current.indexOf(h),[]),p=s.config.menu,d=sm(()=>e.map(h=>({...h,words:h.prompt.evaluate(Ee.getCtx({gameState:n}))})),[e,n]);function f(h){t(h)}return Qt.createElement(Qt.Fragment,null,Qt.createElement(as,{value:{evaluated:d,choose:f,gameState:n}},Qt.createElement(cs,{value:{register:l,unregister:c,getIndex:u}},Qt.createElement(_t,{className:"absolute"},r&&o&&Qt.createElement(Ci,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),Qt.createElement(Kt.Div,{color:"green",border:"dashed",className:rm("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},Qt.createElement(p,{items:d.map((h,m)=>m)})))))}function Gc({items:o}){return Qt.createElement(Lo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>Qt.createElement(Bo,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import pm from"clsx";import Ii from"react";var Oc=120;function Fc({sources:o,menuCount:e,presence:t,retained:n,lastActive:i,sceneId:r}){if(o.length===0){let l=n??(i.length>0?i.map(c=>({...c,active:!1})):null);return{items:l??[],retained:l,lastActive:i,retaining:l!==null,interactive:e>0}}let s=new Set(o.map(({slot:l})=>l));for(let[l,c]of Array.from(t.slotKeys))s.has(l)||(t.exitingKeys.add(c),t.slotKeys.delete(l));let a=o.map(({slot:l,...c})=>{let u=t.slotKeys.get(l);return(!u||t.exitingKeys.has(u))&&(u=`say-${r}-${t.nextKey++}`,t.slotKeys.set(l,u)),{...c,presenceKey:u,slot:l,active:!0}});return{items:a,retained:null,lastActive:a,retaining:!1,interactive:!0}}function Bs({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=cr({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),a=cr([]),l=cr(null),c=cr(null),[,u]=um(g=>g+1,0),p=()=>{c.current&&(clearTimeout(c.current),c.current=null)},d=()=>{let g=l.current;if(!g)return;let b=s.current;g.forEach(({slot:y,presenceKey:S})=>{b.slotKeys.get(y)===S&&b.slotKeys.delete(y),b.exitingKeys.add(S)}),l.current=null,c.current=null,a.current=[],u()};cm(()=>()=>{p()},[]);let f=s.current,h=i.length>0?i.map(({action:g,onClick:b},y)=>({action:g,slot:y,useTypeEffect:!0,onFinished:()=>{b(),o.events.emit(L.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((g,b)=>{if(!g.action.prompt||!g.action.words)return[];let y=f.menuPromptIds.get(g);return y||(y=`menu-prompt-${n.getId()}-${f.nextKey++}`,f.menuPromptIds.set(g,y)),[{action:{sentence:g.action.prompt,words:g.action.words,character:null,id:y},slot:b,useTypeEffect:!1}]}),m=Fc({sources:h,menuCount:r.length,presence:f,retained:l.current,lastActive:a.current,sceneId:n.getId()});return l.current=m.retained,a.current=m.lastActive,m.retaining?c.current||(c.current=setTimeout(d,Oc)):p(),Ii.createElement("div",{className:pm(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs",style:{pointerEvents:m.interactive?"auto":"none"}},Ii.createElement(lm,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{s.current.exitingKeys.clear()}},m.items.map(({action:g,onFinished:b,presenceKey:y,active:S,useTypeEffect:T})=>Ii.createElement(Ci,{gameState:o,key:y,action:g,active:S,onFinished:b,useTypeEffect:T}))),r.map(({action:g,onClick:b},y)=>Ii.createElement("div",{key:"menu-"+y,"data-element-type":"menu"},Ii.createElement(Us,{state:o,prompt:g.prompt,choices:g.choices,renderPrompt:!g.prompt,afterChoose:S=>{b(S),o.stage.next()},words:g.words}))))}import Tn,{useEffect as dm,useRef as Ws}from"react";import{motion as mm}from"motion/react";function Vc({state:o,camera:e,children:t}){let n=Ws(null),i=Ws(null),r=Ws(null),{transformRef:s,transitionRefs:a,initDisplayable:l,applyTransition:c,applyTransform:u,applyLoop:p,stopLoop:d,updateStyleSync:f,deps:h}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:qa},{ref:i,project:$a},{ref:r,project:ja}],transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return wt(e,{initDisplayable:l,applyTransition:c,applyTransform:u,applyLoop:p,stopLoop:d,updateStyleSync:f},[...h]),dm(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),Tn.createElement(Tn.Fragment,null,Tn.createElement(mm.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([m,g])=>Tn.createElement("div",{className:"relative w-full h-full",ref:m,key:g},t))),Tn.createElement("div",{className:"absolute w-full h-full","data-element-type":"camera-lens",style:{pointerEvents:"none"}},Tn.createElement("div",{className:"absolute w-full h-full",ref:n,"data-element-type":"camera-lens-vignette"}),Tn.createElement("div",{className:"absolute w-full h-full",ref:i,"data-element-type":"camera-lens-shutter-top"}),Tn.createElement("div",{className:"absolute w-full h-full",ref:r,"data-element-type":"camera-lens-shutter-bottom"})))}import fm from"react";import{useEffect as zs,useLayoutEffect as hm,useRef as gm,useState as ym}from"react";var Hc={linear:"linear",easeIn:"cubic-bezier(0.42, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.58, 1)",easeInOut:"cubic-bezier(0.42, 0, 0.58, 1)"};function Mi(o){return o===void 0?"linear":Array.isArray(o)?`cubic-bezier(${o.join(", ")})`:typeof o=="string"&&Hc[o]?Hc[o]:null}var ur=class{constructor(e,t=n=>Mi(n)??"ease"){this.getElement=e;this.cssEasing=t;this.operation=null}isFading(){return this.operation!==null}set(e){this.settleOperation(),this.apply(e)}fadeTo(e,t){let n=t?.duration??0,i=this.getElement();return!i||!(n>0)?(this.set(e),Promise.resolve()):!this.operation&&this.isShowing(i)===e?(this.apply(e),Promise.resolve()):(this.operation?.settle(),this.operation=null,i.style.visibility==="hidden"&&(i.style.transition="",i.style.opacity="0"),i.style.visibility="inherit",i.style.pointerEvents="none",new Promise(r=>{let s=!1,a=null,l={visible:e,settle:()=>{s||(s=!0,a!==null&&clearTimeout(a),this.operation===l&&(this.operation=null),r())}};this.operation=l,i.style.transition=`opacity ${n}ms ${this.cssEasing(t?.easing)}`,i.offsetWidth,i.style.opacity=e?"1":"0",a=setTimeout(()=>{l.settle(),this.apply(e)},n)}))}skip(){let e=this.operation;e&&(e.settle(),this.apply(e.visible))}cancel(){this.settleOperation();let e=this.getElement();e&&(e.style.transition="")}dispose(){this.settleOperation()}settleOperation(){let e=this.operation;this.operation=null,e?.settle()}isShowing(e){return e.style.visibility!=="hidden"&&e.style.opacity!=="0"}apply(e){let t=this.getElement();t&&(t.style.transition="",t.style.opacity=e?"1":"0",t.style.pointerEvents=e?"auto":"none",t.style.visibility=e?"inherit":"hidden")}};function _s({gameState:o,video:e}){let t=gm(null),[n]=ym(()=>new ur(()=>t.current,r=>{let s=Mi(r);return s===null?(o.logger.debug("NarraLeaf-React: Video",'Easing has no CSS equivalent, falling back to "ease"',r),"ease"):s}));zs(()=>o.events.depends([o.events.on(L.EventTypes["event:state.player.skip"],()=>{n.skip(),o.game.config.allowSkipVideo&&(i(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),hm(()=>{n.isFading()||n.set(e.state.display)}),zs(()=>()=>n.dispose(),[n]),zs(()=>{if(!t.current)return;let r=t.current,s=!1,a=new Set,l=()=>new P(`Failed to add event listener, ref is not available
|
|
67
|
-
at Video.tsx: useEffect`),c=d=>{s||(s=!0,o.mountState(e,{show:f=>{if(!t.current)throw l();return n.fadeTo(!0,f)},hide:f=>{if(!t.current)throw l();return n.fadeTo(!1,f)},cancelFade:()=>{n.cancel(),n.set(e.state.display)},play:()=>{if(!t.current)throw l();let f=t.current;return d||f.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(f.currentTime=0,new Promise(h=>{let m=!1,g=null,b=[],y=()=>{m||(m=!0,a.delete(y),g&&g(),b.forEach(S=>S()),h())};a.add(y),g=o.schedule(({retry:S})=>{if(m)return;if(f.readyState<3){let w=()=>{f.removeEventListener("loadeddata",w),S()};f.addEventListener("loadeddata",w),b.push(()=>f.removeEventListener("loadeddata",w));return}let T=()=>y(),C=()=>y(),x=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),y()};f.addEventListener("ended",T),f.addEventListener("stopped",C),f.addEventListener("error",x),b.push(()=>{f.removeEventListener("ended",T),f.removeEventListener("stopped",C),f.removeEventListener("error",x)}),f.play().catch(w=>{o.logger.error("Failed to play video: "+w),y()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(f=>{o.logger.error("Failed to resume video: "+f)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:f=>{if(!t.current)throw l();t.current.currentTime=f}}))},u=()=>c(!1),p=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(r.error?` (media error code ${r.error.code})`:"")),c(!0)};return r.addEventListener("canplay",u),r.addEventListener("error",p),r.readyState>=3?c(!1):r.error&&p(),()=>{r.removeEventListener("canplay",u),r.removeEventListener("error",p),a.forEach(d=>d()),r.currentTime>0&&r.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function i(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return fm.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:r=>r.preventDefault()})}import vm,{useEffect as Sm,useRef as bm}from"react";function Tm(o,e){let t=Mi(e);return t===null?(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease"):t}function Ks({gameState:o,vfx:e}){let t=bm(null);return Sm(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,l=new Set,c=new Set,u=[],p=T=>{n.style.transition="",n.style.opacity=String(T)},d=()=>{n.play().catch(T=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+T)})},f=()=>i||n.error?(o.logger.error("NarraLeaf-React: Vfx","Cannot wait for a vfx whose source failed to load: "+e.config.src),Promise.resolve()):n.readyState>=2?Promise.resolve():new Promise(T=>{let C=!1,x=()=>G(),w=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),G()},G=()=>{C||(C=!0,c.delete(G),n.removeEventListener("loadeddata",x),n.removeEventListener("error",w),T())};c.add(G),n.addEventListener("loadeddata",x),n.addEventListener("error",w),(n.readyState>=2||n.error)&&G()}),h=(T,C,x)=>{let w=C?.duration??0,G=++s;return x.instant||w<=0?(p(T),Promise.resolve()):new Promise(I=>{let ae=!1,E=null,F=()=>{ae||(ae=!0,c.delete(F),E!==null&&clearTimeout(E),s===G&&t.current&&p(T),I())};c.add(F),n.style.transition=`opacity ${w}ms ${Tm(o,C?.easing)}`,n.offsetWidth,n.style.opacity=String(T),E=setTimeout(F,w)})},m=T=>{r||(r=!0,i=T,o.mountState(e,{show:async C=>{a=!0;let x={instant:!1};l.add(x);try{if(await f(),!t.current)return;n.playbackRate=C?.rate??e.config.playbackRate,e.state.paused||d(),await h(C?.opacity??e.config.opacity,C,x)}finally{l.delete(x)}},hide:async C=>{a=!0;let x={instant:!1};l.add(x);try{await h(0,C,x),t.current&&n.pause()}finally{l.delete(x)}},pause:()=>{n.pause()},resume:()=>{d()},setRate:C=>{n.playbackRate=C}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&p(e.config.opacity)},0)))},g=()=>m(!1),b=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(n.error?` (media error code ${n.error.code})`:"")),m(!0)},y=o.events.on(L.EventTypes["event:state.player.skip"],()=>{l.size===0&&c.size===0||(l.forEach(T=>{T.instant=!0}),[...c].forEach(T=>T()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),S=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&d()};return document.addEventListener("visibilitychange",S),n.style.opacity="0",n.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&d(),n.addEventListener("canplay",g),n.addEventListener("error",b),n.readyState>=3?m(!1):n.error&&b(),()=>{n.removeEventListener("canplay",g),n.removeEventListener("error",b),document.removeEventListener("visibilitychange",S),y.cancel(),u.forEach(T=>T()),[...c].forEach(T=>T()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),vm.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,loop:e.config.loop,playsInline:!0,onContextMenu:n=>n.preventDefault(),style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:e.config.fit,pointerEvents:"none"}})}import Am from"clsx";import Cm,{useCallback as xm,useEffect as pr,useRef as wm}from"react";function $s({children:o,className:e,gameState:t}){let{ratio:n}=be(),i=N(),[r]=de(),s=wm(null),a=i.config.minWidth,l=i.config.minHeight,c=xm(u=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(u.width,u.height,u.scale),n.updateMin(a,l),r()},[r,t.logger,l,a,n]);return pr(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),pr(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),pr(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,l,a]),pr(()=>t.events.on(L.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),Cm.createElement(rc,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:l,debounceMs:i.config.ratioUpdateInterval,className:Am(e),onUpdate:c},o)}import Uc,{useEffect as km,useRef as Pm,useState as Bc}from"react";function js({src:o,width:e,height:t}){let[n,i]=Bc({x:0,y:0}),[r,s]=Bc(!1),a=Pm(null),{ratio:l}=be();return km(()=>{let c=u=>{if(a.current){let p=a.current.getBoundingClientRect(),d=u.clientX-p.left,f=u.clientY-p.top;i({x:d,y:f}),r||s(!0)}};return window.addEventListener("mousemove",c),()=>{window.removeEventListener("mousemove",c)}},[r]),Uc.createElement(_t,{ref:a,className:"overflow-hidden absolute"},Uc.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${l.state.scale})`},alt:""}))}import Wc from"react";import an from"react";function qs({error:o,errorInfo:e}){return N().config.app.debug?an.createElement("div",{className:"text-left"},an.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),an.createElement("p",{className:"text-red-700"},"Message: ",o.message),an.createElement("pre",null,"Error Stack: ",o?.stack),an.createElement("pre",null,"Component Stack: ",e?.componentStack),an.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):an.createElement("div",{className:"bg-white w-full h-full"},an.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),an.createElement("p",null,"Please contact the game developer for further assistance."))}var dr=class extends Wc.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?Wc.createElement(qs,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import Kc from"clsx";import U,{useEffect as kt,useLayoutEffect as Rm,useReducer as $c,useRef as Im,useState as Zn}from"react";import{flushSync as jc}from"react-dom";import{useRef as Em}from"react";import{useEffect as Dm}from"react";function zc({gameState:o}){let e=Em(null);return Dm(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(L.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import Ni,{useEffect as Lm}from"react";function Qs({gameState:o}){let[e]=de(),{ratio:t}=be(),n=o.notificationMgr;Lm(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return Ni.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},Ni.createElement(i,{notifications:n.toArray()}))}function _c({notifications:o}){return Ni.createElement(zo,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>Ni.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},Ni.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function Qc({story:o=hi.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:l,onError:c,children:u,active:p=!0}){let[d,f]=$c(W=>W+1,0),[h,m]=$c(W=>W+1,0),[g,b]=Zn(0),y=N(),[S]=Zn(()=>new L(y,{update:f,forceUpdate:()=>{S.logger.weakWarn("Player","force update"),jc(()=>{f()})},forceRemount:()=>{S.logger.weakWarn("Player","force remount"),jc(()=>{b(W=>W+1),f()})},next:q})),T=U.createRef(),C=U.createRef(),[x,w]=Zn(!1),G=U.useRef(!1),I=U.useRef(null),ae=U.useRef(null),{preloaded:E,cacheManager:F}=$t(),[K,he]=Zn(!1),qe=U.useRef(!1),[Qe,Ot]=Zn(!1),We=U.useRef(!1),ft=U.useRef(null),ee=U.useRef(!1),[Ct]=Zn(new Map);function M(W){return{game:y,gameState:S,liveGame:y.getLiveGame(),storable:y.getLiveGame().getStorable(),scene:W}}function q(){let W=()=>{Ct.forEach(H=>H.cancel())};if(S.rollLock.isLocked())return;W();let D=!1,ie=0;for(;!D;){if(ie++>y.config.maxStackModelLoop)throw new P("Max stack model loop reached");let H=y.getLiveGame().next();if(!H){if(y.getLiveGame().stackModel&&!y.getLiveGame().stackModel.isEmpty())continue;break}if(v.isAwaitable(H)){if(I.current===H)break;I.current=H,H.onSettled(()=>{H.isFailed()||(I.current===H&&(I.current=null),q())}),H.onFailed(ye=>{I.current===H&&(I.current=null),S.logger.error("Player",ye)}),D=!0;break}if(H instanceof Nn){if(ae.current===H)break;ae.current=H,H.nextUnlock().then(()=>{ae.current===H&&(ae.current=null),q()}),D=!0;break}if(Ze.isCalledActionResult(H)&&H.wait&&Ze.isStackModelsAwaiting(H.wait.type,H.wait.stackModels)){if(I.current===H)break;if(I.current=H,H.wait){let ye=Ze.executeStackModelGroup(H.wait.type,H.wait.stackModels);ye.then(()=>{I.current===H&&(I.current=null),q()}),ye.onFailed(Fe=>{I.current===H&&(I.current=null),S.logger.error("Player",Fe)})}D=!0;break}S.handle(H)}S.stage.update()}kt(()=>{S.audioManager.initialize()},[]),kt(()=>(S.setImageCache(F),()=>{S.setImageCache(null)}),[F]),kt(()=>(y.getLiveGame().setGameState(S),o&&!y.getLiveGame().isPlaying()&&y.getLiveGame().loadStory(o),o?.entryScene&&!S.getPreloadingScene()&&!S.getLastScene()&&S.preloadScene(o.entryScene),S.playerCurrent=T.current,S.mainContentNode=C.current,()=>{y.getLiveGame().setGameState(void 0),S.playerCurrent=null}),[y,o]),kt(()=>ct(()=>{w(!0);let W=S.getLastScene(),D=[];W?D.push(W.events.once("event:scene.mount",()=>{S.stage.next()}).cancel):S.stage.next();let ie=S.events.on(L.EventTypes["event:state.end"],()=>{l&&l({game:y,gameState:S,liveGame:y.getLiveGame(),storable:y.getLiveGame().getStorable()})});return S.stage.update(),()=>{W&&D.forEach(H=>H()),ie.cancel()}}),[]),kt(()=>ct(()=>{x&&i&&!G.current&&(G.current=!0,S.stage.forceUpdate(),y.hooks.trigger("init",[]),i({game:y,gameState:S,liveGame:y.getLiveGame(),storable:y.getLiveGame().getStorable()}))}),[x]),kt(()=>ct(()=>{if(K&&s&&!qe.current){qe.current=!0;let W=ft.current||S.getLastScene()||S.getPreloadingScene(),D=M(W);s(D)}}),[K]),kt(()=>ct(()=>{if(Qe&&!We.current){We.current=!0;let W=ft.current||S.getLastScene()||S.getPreloadingScene(),D=M(W);y.markPreloadComplete(D)&&r&&r(D)}}),[Qe]),kt(()=>S.events.on(L.EventTypes["event:state.scene.mount"],W=>{ft.current||(ft.current=W,m())}).cancel,[]),kt(()=>{if(!Qe||!p||ee.current||y.isFirstSceneReady())return;let W=ft.current||S.getLastScene();if(!W)return;let D=null,ie=null,H=!1;ee.current=!0;let ye=()=>{H=!0,ee.current=!1;let Fe=M(W);y.markFirstSceneReady(Fe)&&a&&a(Fe)};return typeof requestAnimationFrame=="function"?D=requestAnimationFrame(()=>{ie=setTimeout(ye,0)}):ie=setTimeout(ye,0),()=>{H||(ee.current=!1,D!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(D),ie!==null&&clearTimeout(ie))}},[p,h,d,Qe]),kt(()=>E.events.depends([E.events.on(at.EventTypes["event:preloaded.ready"],()=>{he(!0),S.stage.update(),o&&y.getLiveGame().isPlaying()&&q()}),E.events.on(at.EventTypes["event:preloaded.complete"],()=>{Ot(!0)})]).cancel,[]),kt(()=>{S.flushDep=d},[d]);let ue=e||y.config.width,ge=t||y.config.height;return U.createElement(dr,{onError:c},U.createElement("div",{style:{width:typeof ue=="number"?`${ue}px`:ue,height:typeof ge=="number"?`${ge}px`:ge},className:Kc(n,"__narraleaf_content-player"),ref:T,tabIndex:0},U.createElement($s,{className:Kc("flex-grow overflow-auto"),gameState:S},U.createElement(xs,{gameState:S}),U.createElement(zc,{gameState:S}),U.createElement(_t,{className:"absolute",ref:C,style:{cursor:S.game.config.cursor?"none":"auto",overflow:S.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},y.config.cursor&&U.createElement(js,{src:y.config.cursor,width:y.config.cursorWidth,height:y.config.cursorHeight}),U.createElement(Mm,{show:K&&p,key:g},U.createElement(Ss,null,U.createElement(pc,{state:S}),U.createElement(gc,{state:S}),U.createElement(Gm,{state:S},U.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},U.createElement(Nm,{state:S})),U.createElement(Om,{state:S}),S.getVfx().map(W=>U.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+W.getId(),"data-element-type":"vfx",style:{zIndex:W.config.zIndex,mixBlendMode:W.config.blendMode}},U.createElement(Ks,{gameState:S,vfx:W})))),S.getSceneElements().map(W=>U.createElement(Bs,{key:"scene-dialogs-"+W.scene.getId(),state:S,elements:W})),U.createElement(Fm,{NvlComponent:y.config.nvlDialog}))),U.createElement(bc,{state:S}),U.createElement(Zl,null,u),U.createElement(Qs,{gameState:S})))))}function Mm({children:o,show:e}){return U.createElement(U.Fragment,null,e?o:null)}function Nm({state:o}){let e=[],t=new Set;return o.getSceneElements().forEach(n=>{e.push(U.createElement(Vs,{key:"scene-"+n.scene.getId(),state:o,elements:n})),o.getVideosOf(n.scene).forEach(i=>{t.add(i),e.push(U.createElement(qc,{key:"video-"+i.getId(),state:o,video:i,owner:n.scene}))})}),o.getVideos().forEach(n=>{t.has(n)||e.push(U.createElement(qc,{key:"video-"+n.getId(),state:o,video:n,owner:null}))}),U.createElement(U.Fragment,null,e)}function qc({state:o,video:e,owner:t}){let n=Im(null);return Rm(()=>{if(!(!t||!n.current))return o.stageTransition.bindCompanion(t,n.current)},[t]),U.createElement("div",{className:"w-full h-full absolute",ref:n,"data-element-type":"video"},U.createElement(_s,{gameState:o,video:e}))}function Gm({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?U.createElement(Vc,{state:o,camera:t},e):U.createElement(U.Fragment,null,e)}function Om({state:o}){let e=U.useRef(null);return kt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),U.createElement("div",{className:"w-full h-full absolute pointer-events-none",ref:e,"data-element-type":"stage-transition-overlay-host"})}function Fm({NvlComponent:o}){let{dialogs:e,state:t}=jt(),i=N().getLiveGame().getGameState(),r=U.useMemo(()=>e.map((s,a)=>{let l=s.sentence.evaluate(Ee.getCtx({gameState:i})),c=t.activeDialogId===s.id,u=c&&t.phase==="typing";return{entry:s,index:a,isActive:c,gameState:i,words:l,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return U.createElement(o,{dialogs:r})}import"client-only";import ei from"react";function Yc({children:o,game:e}){return ei.createElement(ei.Fragment,null,ei.createElement(cl,null,ei.createElement(ol,{game:e},ei.createElement(jl,null,ei.createElement(ll,null,o)))))}var Vm=(l=>(l.image="narraleaf:image",l.text="narraleaf:text",l.layer="narraleaf:layer",l.scene="narraleaf:scene",l.video="narraleaf:video",l.vfx="narraleaf:vfx",l.camera="narraleaf:camera",l.puppet="narraleaf:puppet",l))(Vm||{});import Hm from"clsx";import Pt,{useEffect as Jc,useRef as Um,useState as Bm}from"react";function Xc(o){return o?{className:"",ariaHidden:!1}:{className:"opacity-0",ariaHidden:!0}}import{motion as Wm,useIsPresent as zm}from"motion/react";var _m={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Km({children:o,initial:e,transition:t,...n}){let i=N(),r=Mt(),{ratio:s}=be(),[a]=vn(Y.Preferences.showDialog),l=Um(null),[c]=Dn("nextAction"),u=zm(),[p,d]=Bm(null),f=Xc(a);function h(){a&&(r.config.gameState.isAdvanceSuspended()||r.requestComplete())}return Jc(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
68
|
-
at Say.tsx: onElementClick`);return}let m=b=>{b.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",b.key)&&r.requestComplete()};window.addEventListener("keydown",m);let g=r.events.on(Oe.Events.simulateClick,()=>{l.current&&l.current.click()});return()=>{window.removeEventListener("keydown",m),g.cancel()}},[r,c]),Jc(()=>{let m=i.preference.onPreferenceChange(Y.Preferences.autoForward,g=>{g&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{m.cancel()}},[r]),Pt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},Pt.createElement("div",{className:Hm("absolute bottom-0 w-full h-full",f.className),"aria-hidden":f.ariaHidden,onClick:h,style:{...Fn(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:l},Pt.createElement(Cs,{value:p},Pt.createElement(Wm.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),Pt.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:d})))}function Zc({children:o,...e}){let t=Mt();return!t.config.action.sentence||!t.config.action.words?null:Pt.createElement(Km,{...e},o)}var Rd=Zc;function eu(){return Pt.createElement(Zc,null,Pt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},Pt.createElement(ps,null),Pt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},Pt.createElement(sn,null),Pt.createElement(Sn,{..._m}))))}var Gi={say:eu,menu:Gc,notification:_c,nvlDialog:As};var mr=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var Oi=class{constructor(e={}){this.keyMap=e;this.events=new Z}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],i=r=>Array.isArray(r)?r:[r];Array.isArray(n)?this.setKeyBinding(e,[...n,...i(t)]):this.setKeyBinding(e,[n,...i(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,i)=>{n===e&&t(i)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(i=>i.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var tu=(e=>(e.game="game",e))(tu||{}),et=class et{constructor(e){this.hooks=new Qi;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new Ti(et.DefaultPreference);this.audioBuses=new pi(()=>this.config.audioBuses??[],Na(this.preference));this.keyMap=new Oi({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new Z;this.puppetBackends=new rr;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=Q(et.DefaultConfig,e),this.plugins=new mr(this),this.router=new yn(this)}configure(e){let[t,n]=Aa(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=Q(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(L.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}registerPuppetBackend(e){return this.puppetBackends.register(e),this}getPuppetBackend(e){return this.puppetBackends.get(e)}listPuppetBackends(){return this.puppetBackends.list()}getPuppetBackendRegistry(){return this.puppetBackends}onPreloadComplete(e){return this.lifecycleEvents.on(et.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(et.LifecycleEventTypes["event:game.preloadComplete"],e)}whenPreloadComplete(){return this.preloadCompleteContext?Promise.resolve(this.preloadCompleteContext):new Promise(e=>{this.oncePreloadComplete(e)})}isPreloadComplete(){return this.preloadCompleteContext!==null}onFirstSceneReady(e){return this.lifecycleEvents.on(et.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(et.LifecycleEventTypes["event:game.firstSceneReady"],e)}whenFirstSceneReady(){return this.firstSceneReadyContext?Promise.resolve(this.firstSceneReadyContext):new Promise(e=>{this.onceFirstSceneReady(e)})}isFirstSceneReady(){return this.firstSceneReadyContext!==null}markPreloadComplete(e){return this.preloadCompleteContext?!1:(this.preloadCompleteContext=e,this.lifecycleEvents.emit(et.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(et.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.audioBuses.dispose(),this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Wt(this)}};et.defaultSettings={volume:1},et.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,textRevealDuration:0,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:0,skipInterval:100},et.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",textRevealDuration:"textRevealDuration",voiceVolume:"voiceVolume",voiceFadeDuration:"voiceFadeDuration",voiceEndMode:"voiceEndMode",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},et.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadGate:"firstFrame",preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,imageCacheBudgetBytes:256*1024*1024,decodedImageBudgetBytes:128*1024*1024,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipSceneTransition:!0,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:Gi.notification,menu:Gi.menu,dialog:Gi.say,nvlDialog:Gi.nvlDialog,onError:e=>{console.error(e)},disableTextScaling:!1,stage:null,maxStackModelLoop:1e3,maxActionHistory:100,maxSceneCallDepth:8,audioBuses:[],audioStreaming:"loops"},et.GameSettingsNamespace=tu,et.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var Y=et;var fr=class fr extends X{constructor(){super(...arguments);this._jumpTarget=null}setJumpTarget(t){return this._jumpTarget=t,this}getJumpTarget(){return this._jumpTarget}static executeActionsAsync(t,n){let i=t.game.getLiveGame().requestAsyncStackModel([{type:n.type,node:n.contentNode}]);return t.game.getLiveGame().executeAsyncStackModel(i)}checkActionChain(t){if(t.some(n=>!!n.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return t}executeAction(t,n){let i=this.contentNode,[r]=i.getContent();if(this.type===le.do)return r.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:r[0].contentNode}];if(this.type===le.doAsync){if(r.length===0)return super.executeAction(t,n);let s=fr.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===le.any){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:s}}}else if(this.type===le.all){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:s}}}else if(this.type===le.allAsync){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().requestAsyncStackModel([{type:a.type,node:a.contentNode}]));return t.timelines.attachTimeline(v.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===le.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let l=Ze.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[l]}}}else if(this.type===le.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let l=Ze.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[l]}}}else if(this.type===le.break){if(!n.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return n.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===le.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=v.delay(s):v.isAwaitable(s)?a=s:a=v.fromPromise(s);let l=new v,c=new De(a);return t.timelines.attachTimeline(c),a.then(()=>{l.resolve({type:this.type,node:this.contentNode.getChild()})}),l.onSkipControllerRegister(u=>{u.onAbort(()=>{c.abort()})}),l}else if(this.type===le.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new v,a=new v,l=new De(a);t.timelines.attachTimeline(l);let c=t.game.preference,u=c.getPreference(Y.Preferences.autoForward),p=c.getPreference(Y.Preferences.gameSpeed),d=u?t.game.config.autoForwardDelay/p:null,f=!1,h=null,m=null,g=null,b=()=>{m?.cancel(),g?.cancel(),h&&(clearTimeout(h),h=null)},y=()=>{f||(f=!0,b(),a.resolve())};return m=t.events.on(L.EventTypes["event:state.player.stageClick"],y),g=t.events.on(L.EventTypes["event:state.player.skip"],y),d!==null&&(h=setTimeout(y,d)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(S=>{S.onAbort(()=>{f||(f=!0,b(),l.abort())})}),s}else{if(this.type===le.label)return super.executeAction(t,n);if(this.type===le.jump){let s=this._jumpTarget;if(!s){let[c]=this.contentNode.getContent();throw new ke(`Jump target label "${c}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),l=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(c,u)},[l]),a.getStackModelForce().clearAboveCallFrame().push({type:this.type,node:s.contentNode}),null}}throw new Error("Unknown control action type: "+this.type)}getFutureActions(t,n){if(this.callee.config.allowFutureScene===!1&&n.allowFutureScene===!1)return[...super.getFutureActions(t,n)];if(this.type===le.break||this.type===le.waitForClick||this.type===le.label||this.type===le.jump)return super.getFutureActions(t,n);let i=this.contentNode.getContent()[0],r=super.getFutureActions(t,n);return[...i??[],...r]}stringify(t,n,i){if(this.type===le.break)return super.stringifyWithContent("Control","break");if(this.type===le.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===le.label||this.type===le.jump){let[a]=this.contentNode.getContent(),l=this.type===le.label?"label":"jump";return super.stringifyWithContent("Control",`${l}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};fr.ActionTypes=le;var ce=fr;var Ve=class o extends me{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static whileLoop(t,n){return new o().whileLoop(t,n)}static breakLoop(){return new o().breakLoop()}static sleep(t){return new o().sleep(t)}static waitForClick(){return new o().waitForClick()}static label(t){return new o().label(t)}static jump(t){return new o().jump(t)}do(t){return this.push(ce.ActionTypes.do,t)}doAsync(t){return this.push(ce.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(ce.ActionTypes.any,t)}all(t){return this.pushUnchained(ce.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(ce.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(ce.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=J.from(t);return this.pushWithLambda(ce.ActionTypes.while,n,i)}breakLoop(){let t=new ce(this.chain(),ce.ActionTypes.break,new A().setContent([]));return this.chain(t)}sleep(t){return this.push(ce.ActionTypes.sleep,[],t)}waitForClick(){let t=new ce(this.chain(),ce.ActionTypes.waitForClick,new A().setContent([]));return this.chain(t)}label(t){let n=new ce(this.chain(),ce.ActionTypes.label,new A().setContent([t]));return this.chain(n)}jump(t){let n=new ce(this.chain(),ce.ActionTypes.jump,new A().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new ce(this.chain(),t,new A().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new ce(this.chain(),t,new A().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new ce(this.chain(),t,new A().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?nn.say(n).getActions():Ke.toActions([n]))}};var j=class j extends je{static get DefaultUserConfig(){return j._defaultUserConfig??(j._defaultUserConfig=new $({name:"(anonymous)",autoInit:!0,src:j.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...re.DefaultTransformState.getDefaultConfig()},{position:e=>V.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return k.isStaticImageData(t)?k.srcToURL(t):k.isColor(t)?t:k.isImageSrc(t)?k.srcToURL(t):j.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isLayeredSrc(e){return!!e.config.src?.slots}static isSrcDefinitionObject(e){return typeof e=="object"&&e!==null&&!k.isImageSrc(e)&&!k.isColor(e)}static isLayeredDefinition(e){return this.isSrcDefinitionObject(e)&&"layers"in e}static isTagDefinition(e){return this.isSrcDefinitionObject(e)&&"resolve"in e}static isLayerVariants(e){return typeof e=="object"&&e!==null}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(k.isImageSrc(t)||k.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:j.isLayeredSrc(e)?null:j.isTagSrc(e)&&e.config.src.resolve?j.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):j.isStaticSrc(e)?k.isStaticImageData(e.state.currentSrc)?k.srcToURL(e.state.currentSrc):k.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static getSrcURLs(e,t){let n=e.config.src?.slots;if(!n)return[];let i=new Set(t??e.state.currentSrc);return n.map(r=>j.resolveLayerSlot(r,i))}static resolveLayerSlot(e,t){if(e===null||typeof e=="string")return e;if(typeof e=="function")return e(t);for(let[n,i]of Object.entries(e))if(t.has(n))return i;return null}static getAllLayerSrc(e){let t=e.config.src?.slots;if(!t)return[];let n=[];for(let i of t)if(typeof i=="string")n.push(i);else if(j.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new j({src:e})}constructor(e={}){super();let t=j.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new Ve,n=>{if(k.isImageSrc(e)||k.isColor(e)){if(k.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new Ae(n,Ae.ActionTypes.setAppearance,new A().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Ve,i=>i.chain(this._setDarkness(i,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new te("Cannot add self as a wearable");this.config.wearables.push(n),Object.assign(n.config,{isWearable:!0})}return this}wear(e){return this.addWearable(e)}bindWearable(e){return e.addWearable([this])}asWearableOf(e){return this.bindWearable(e)}useLayer(e){return this.userConfig.get().layer=e||void 0,Object.assign(this.config,{layer:e||void 0}),this}toData(){return{state:j.StateSerializer.serialize(this.state),transformState:re.TransformStateSerializer.serialize(this.transformState.get()),loop:this._serializeLoop()}}fromData(e){return this.state=j.StateSerializer.deserialize(e.state),this.transformState.resetTo(re.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_applyTransition(e,t){return new xe(this.chain(),fe.applyTransition,new A().setContent([e,t]))}_init(e,t){return new xe(this.chain(),fe.init,new A().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new Ae(this.chain(),Ae.ActionTypes.initWearable,new A().setContent([e]))}_flush(){return new Ae(this.chain(),Ae.ActionTypes.flush,new A)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get()),this}resolveTags(e,t){if(!j.isTagSrc(this))throw new Error(`Tag not defined
|
|
69
|
-
Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(l=>{let c=n.get(l);c&&i.set(c,l)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let l=i.get(a);if(!l)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(l)}),r}_setAppearanceSync(e){if(
|
|
66
|
+
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(R)),r.get(R)||R}let{transformRef:d,transitionRefs:f,transitionTask:h,initDisplayable:m,applyTransition:g,applyTransform:b,applyLoop:y,stopLoop:S,updateStyleSync:T,flush:E,deps:A}=qt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:R=>{if(R){let{invertX:z,invertY:le}=e.getStory().getInversionConfig();return Zd(R.task.resolve,{layered:!!u,darkness:o.state.darkness,invertX:z,invertY:le,sizes:c.current.map(qe=>l.current.get(qe))})}if(u)return[{style:Is(o.state.darkness)}];let H=Jd(o);return[{style:{...Ms(o.state.darkness),backgroundColor:w.isColor(H)?w.colorToString(H):void 0},src:w.isImageSrc(H)?w.srcToURL(H):O.DefaultImagePlaceholder}]},propOverwrite:R=>R.src?{...R,src:p(R.src)}:R});wt(o,{createWearable:R=>{i(H=>[...H,R])},disposeWearable:R=>{i(H=>H.filter(z=>z.getId()!==R.getId()))},initDisplayable:m,applyTransform:b,applyLoop:y,stopLoop:S,applyTransition:g,events:t,updateStyleSync:T,flush:E},[...A]);let C=rr(()=>{t.emit("event:image.onLoad")},[t]),L=Lc(a,C),k=bn(new Map),X=(R,H)=>{let z=H?`${R}:sizing`:R,le=k.current.get(z);return le||(le=(qe,Qe)=>{l.current.set(R,{width:qe,height:Qe}),H&&L(qe,Qe)},k.current.set(z,le)),le};return c.current=f.map(([,R])=>R),Dc(()=>{let R=new Set(c.current);l.current.forEach((H,z)=>{R.has(z)||l.current.delete(z)}),k.current.forEach((H,z)=>{R.has(z.replace(/:sizing$/,""))||k.current.delete(z)})}),Gt.createElement(Qd.div,{ref:d,className:"absolute w-max h-max","data-element-type":"image"},Gt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},u?f.map(([R,H],z)=>{let le=h?h.task.resolve[z]:null;if(le&&typeof le=="function")return Gt.createElement(or,{key:H,ref:R,autoFit:o.config.autoFit});let qe=le?le.key==="target"?h.transition._getTargetLayers():h.transition._getPrevLayers():u;return Gt.createElement(Rc,{key:H,ref:R,src:qe||u,autoFit:o.config.autoFit,resolveSrc:p,onSizeChanged:X(H,z===Jn),onLoad:z===Jn?C:void 0})}):f.map(([R,H],z)=>Gt.createElement(or,{key:H,ref:R,autoFit:o.config.autoFit,onSizeChanged:X(H,z===Jn),onLoad:z===Jn?C:void 0})),Gt.createElement("div",{className:kc("w-full h-full top-0 left-0 absolute")},n.map(R=>Gt.createElement("div",{className:kc("w-full h-full relative"),key:"wearable-"+R.getId()},Gt.createElement(Ic,{image:R,state:e}))))))}var Ic=Gt.memo(tm),Mc=Ic;import ar,{useEffect as Ns,useMemo as sm,useRef as lr}from"react";var nm=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,im=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function Nc(o,e){if(typeof e!="string"||!e.length)return o;if(nm.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=om(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+rm(r+e.replace(/\\/g,"/"))}function om(o){let e=im.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function rm(o){let e=o.split("/"),t=[];for(let n=0;n<e.length;n++){let i=e[n];if(!(i==="."||i===""&&n!==e.length-1)){if(i===".."){t.pop();continue}t.push(i)}}return t.join("/")}var sr=class{constructor(){this.backends=new Map;this.reportedMissing=new Set}register(e){if(!e||typeof e.name!="string"||!e.name.length)throw new Error("A puppet backend must have a non-empty name.");if(typeof e.mount!="function")throw new Error(`Puppet backend "${e.name}" must implement mount().`);return this.backends.set(e.name,e),this.reportedMissing.delete(e.name),this}get(e){return this.backends.get(e)||null}has(e){return this.backends.has(e)}list(){return Array.from(this.backends.keys())}unregister(e){return this.backends.delete(e)}reportMissing(e,t){return this.reportedMissing.has(e)?!1:(this.reportedMissing.add(e),t(`No puppet backend is registered under "${e}". The element keeps its place on the stage, its transform and its saved state, but draws nothing. Register one with game.registerPuppetBackend({name, mount}) before the game mounts.`),!0)}};function Gs({state:o,puppet:e}){let[t]=me(),{cacheManager:n}=$t(),i=lr(null),r=sm(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=lr(r);s.current=r;let{transformRef:a,transitionRefs:l,initDisplayable:c,applyTransform:u,applyLoop:p,stopLoop:d,applyTransition:f,updateStyleSync:h,deps:m}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipImageTransform,skipTransition:o.game.config.allowSkipImageTransition,transitionsProps:[{style:{position:"relative",width:`${r.width}px`,height:`${r.height}px`}}]});wt(e,{initDisplayable:c,applyTransform:u,applyLoop:p,stopLoop:d,applyTransition:f,updateStyleSync:h,flush:t},[...m]),Ns(()=>{let S=i.current;if(!S)return;let T=o.game,E=e.config.backend,A=T.getPuppetBackend(E);if(!A)return e._setStatus("missing-backend"),T.getPuppetBackendRegistry().reportMissing(E,k=>{o.logger.warn("Puppet",k)}),()=>{e._setStatus("unmounted")};let C;try{C=A.mount(S,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:y,resolveSibling:k=>y(Nc(e.config.src,k)),warn:(k,X)=>{o.logger.warn("Puppet",k,X)}})}catch(k){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${E}" threw while mounting "${e.config.src}"`,k),()=>{e._setStatus("unmounted")}}let L=!1;return e._attachInstance(C),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!L&&typeof C.ready=="function"?C.ready():void 0).then(()=>{L||e._setStatus("ready")}).catch(k=>{L||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${E}" failed to load "${e.config.src}"`,k))}),()=>{L=!0,e._attachInstance(null),e._setStatus("unmounted");try{C.dispose()}catch(k){o.logger.error("Puppet",`Backend "${E}" threw while disposing`,k)}}},[]);let g=lr(r);Ns(()=>{let S=g.current;if(S.width===r.width&&S.height===r.height)return;g.current=r;let T=e._getInstance();if(!(!T||typeof T.resize!="function"))try{T.resize(r)}catch(E){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,E)}},[r]);let b=lr(new Set);Ns(()=>{let S=b.current;return()=>{S.forEach(T=>n.release(T)),S.clear()}},[]);function y(S){if(w.isDataURI(S))return S;let T=n.get(S);return T?(b.current.has(T)||(b.current.add(T),n.hold(T)),T):S}return ar.createElement(Kt.Div,{"data-element-type":"puppet"},ar.createElement(Kt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},l.map(([S,T])=>ar.createElement("div",{key:T,ref:S,className:e.config.className},ar.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function Os({state:o,displayable:e}){return Mi.createElement(Mi.Fragment,null,e.map(t=>{if(t instanceof Pn)return Mi.createElement(Rs,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof O)return Mi.createElement(Mc,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof Rt)return Mi.createElement(Gs,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import cr,{useEffect as am}from"react";import{motion as lm}from"motion/react";function Gc({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:l,stopLoop:c,updateStyleSync:u,deps:p}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return wt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:l,stopLoop:c,updateStyleSync:u},[...p]),am(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),cr.createElement(cr.Fragment,null,cr.createElement(lm.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([d,f])=>cr.createElement("div",{className:"relative w-full h-full",ref:d,key:f},t))))}async function Oc(o,e,t,n){let i=e.state.backgroundMusic,r=i&&o.audioManager.isManaged(i)?o.audioManager.stop(i,n):null;if(r&&t===i&&await r,t)try{await o.audioManager.playSoundToken(t,{end:t.state.volume,duration:n}),e.state.backgroundMusic=t}catch{e.state.backgroundMusic=null}else e.state.backgroundMusic=null;r&&await r}import cm from"clsx";import{useEffect as Vs,useRef as um}from"react";import Fs from"react";function Hs({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=um(null);return Vs(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),Vs(()=>n.events.depends([n.events.on(Je.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),Vs(()=>(n.events.emit(Je.EventTypes["event:scene.mount"]),o.events.emit(I.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(Je.EventTypes["event:scene.unmount"]),o.events.emit(I.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),wt(n,{setBackgroundMusic(s,a){return Oc(o,n,s,a)}}),Fs.createElement("div",{className:cm(e,"w-full h-full absolute"),ref:r,"data-element-type":"scene","data-scene-id":n.getId()},[...i.entries()].sort(([s],[a])=>s.state.zIndex-a.state.zIndex).map(([s,a])=>Fs.createElement(Gc,{state:o,layer:s,key:s.getId()},Fs.createElement(Os,{state:o,displayable:a}))))}import{AnimatePresence as fm}from"motion/react";import{useEffect as hm,useReducer as gm,useRef as ur}from"react";import pm from"clsx";import Qt,{useCallback as Us,useMemo as dm,useRef as mm}from"react";function Bs({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=G(),a=mm([]),l=Us(h=>(a.current.push(h),a.current.indexOf(h)),[]),c=Us(h=>{let m=a.current.indexOf(h);m!==-1&&a.current.splice(m,1)},[]),u=Us(h=>a.current.indexOf(h),[]),p=s.config.menu,d=dm(()=>e.map(h=>({...h,words:h.prompt.evaluate(Ee.getCtx({gameState:n}))})),[e,n]);function f(h){t(h)}return Qt.createElement(Qt.Fragment,null,Qt.createElement(ls,{value:{evaluated:d,choose:f,gameState:n}},Qt.createElement(us,{value:{register:l,unregister:c,getIndex:u}},Qt.createElement(_t,{className:"absolute"},r&&o&&Qt.createElement(wi,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),Qt.createElement(Kt.Div,{color:"green",border:"dashed",className:pm("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},Qt.createElement(p,{items:d.map((h,m)=>m)})))))}function Vc({items:o}){return Qt.createElement(Ro,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>Qt.createElement(Wo,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import ym from"clsx";import Ni from"react";var Fc=120;function Hc({sources:o,menuCount:e,presence:t,retained:n,lastActive:i,sceneId:r}){if(o.length===0){let l=n??(i.length>0?i.map(c=>({...c,active:!1})):null);return{items:l??[],retained:l,lastActive:i,retaining:l!==null,interactive:e>0}}let s=new Set(o.map(({slot:l})=>l));for(let[l,c]of Array.from(t.slotKeys))s.has(l)||(t.exitingKeys.add(c),t.slotKeys.delete(l));let a=o.map(({slot:l,...c})=>{let u=t.slotKeys.get(l);return(!u||t.exitingKeys.has(u))&&(u=`say-${r}-${t.nextKey++}`,t.slotKeys.set(l,u)),{...c,presenceKey:u,slot:l,active:!0}});return{items:a,retained:null,lastActive:a,retaining:!1,interactive:!0}}function Ws({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=ur({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),a=ur([]),l=ur(null),c=ur(null),[,u]=gm(g=>g+1,0),p=()=>{c.current&&(clearTimeout(c.current),c.current=null)},d=()=>{let g=l.current;if(!g)return;let b=s.current;g.forEach(({slot:y,presenceKey:S})=>{b.slotKeys.get(y)===S&&b.slotKeys.delete(y),b.exitingKeys.add(S)}),l.current=null,c.current=null,a.current=[],u()};hm(()=>()=>{p()},[]);let f=s.current,h=i.length>0?i.map(({action:g,onClick:b},y)=>({action:g,slot:y,useTypeEffect:!0,onFinished:()=>{b(),o.events.emit(I.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((g,b)=>{if(!g.action.prompt||!g.action.words)return[];let y=f.menuPromptIds.get(g);return y||(y=`menu-prompt-${n.getId()}-${f.nextKey++}`,f.menuPromptIds.set(g,y)),[{action:{sentence:g.action.prompt,words:g.action.words,character:null,id:y},slot:b,useTypeEffect:!1}]}),m=Hc({sources:h,menuCount:r.length,presence:f,retained:l.current,lastActive:a.current,sceneId:n.getId()});return l.current=m.retained,a.current=m.lastActive,m.retaining?c.current||(c.current=setTimeout(d,Fc)):p(),Ni.createElement("div",{className:ym(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs",style:{pointerEvents:m.interactive?"auto":"none"}},Ni.createElement(fm,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{s.current.exitingKeys.clear()}},m.items.map(({action:g,onFinished:b,presenceKey:y,active:S,useTypeEffect:T})=>Ni.createElement(wi,{gameState:o,key:y,action:g,active:S,onFinished:b,useTypeEffect:T}))),r.map(({action:g,onClick:b},y)=>Ni.createElement("div",{key:"menu-"+y,"data-element-type":"menu"},Ni.createElement(Bs,{state:o,prompt:g.prompt,choices:g.choices,renderPrompt:!g.prompt,afterChoose:S=>{b(S),o.stage.next()},words:g.words}))))}import Tn,{useEffect as vm,useRef as zs}from"react";import{motion as Sm}from"motion/react";function Uc({state:o,camera:e,children:t}){let n=zs(null),i=zs(null),r=zs(null),{transformRef:s,transitionRefs:a,initDisplayable:l,applyTransition:c,applyTransform:u,applyLoop:p,stopLoop:d,updateStyleSync:f,deps:h}=qt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:Ya},{ref:i,project:qa},{ref:r,project:Qa}],transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return wt(e,{initDisplayable:l,applyTransition:c,applyTransform:u,applyLoop:p,stopLoop:d,updateStyleSync:f},[...h]),vm(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),Tn.createElement(Tn.Fragment,null,Tn.createElement(Sm.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([m,g])=>Tn.createElement("div",{className:"relative w-full h-full",ref:m,key:g},t))),Tn.createElement("div",{className:"absolute w-full h-full","data-element-type":"camera-lens",style:{pointerEvents:"none"}},Tn.createElement("div",{className:"absolute w-full h-full",ref:n,"data-element-type":"camera-lens-vignette"}),Tn.createElement("div",{className:"absolute w-full h-full",ref:i,"data-element-type":"camera-lens-shutter-top"}),Tn.createElement("div",{className:"absolute w-full h-full",ref:r,"data-element-type":"camera-lens-shutter-bottom"})))}import bm from"react";import{useEffect as _s,useLayoutEffect as Wc,useRef as Tm,useState as zc}from"react";var Bc={linear:"linear",easeIn:"cubic-bezier(0.42, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.58, 1)",easeInOut:"cubic-bezier(0.42, 0, 0.58, 1)"};function Gi(o){return o===void 0?"linear":Array.isArray(o)?`cubic-bezier(${o.join(", ")})`:typeof o=="string"&&Bc[o]?Bc[o]:null}var pr=class{constructor(e,t=n=>Gi(n)??"ease"){this.getElement=e;this.cssEasing=t;this.operation=null}isFading(){return this.operation!==null}set(e){this.settleOperation(),this.apply(e)}fadeTo(e,t){let n=t?.duration??0,i=this.getElement();return!i||!(n>0)?(this.set(e),Promise.resolve()):!this.operation&&this.isShowing(i)===e?(this.apply(e),Promise.resolve()):(this.operation?.settle(),this.operation=null,i.style.visibility==="hidden"&&(i.style.transition="",i.style.opacity="0"),i.style.visibility="inherit",i.style.pointerEvents="none",new Promise(r=>{let s=!1,a=null,l={visible:e,settle:()=>{s||(s=!0,a!==null&&clearTimeout(a),this.operation===l&&(this.operation=null),r())}};this.operation=l,i.style.transition=`opacity ${n}ms ${this.cssEasing(t?.easing)}`,i.offsetWidth,i.style.opacity=e?"1":"0",a=setTimeout(()=>{l.settle(),this.apply(e)},n)}))}skip(){let e=this.operation;e&&(e.settle(),this.apply(e.visible))}cancel(){this.settleOperation();let e=this.getElement();e&&(e.style.transition="")}dispose(){this.settleOperation()}settleOperation(){let e=this.operation;this.operation=null,e?.settle()}isShowing(e){return e.style.visibility!=="hidden"&&e.style.opacity!=="0"}apply(e){let t=this.getElement();t&&(t.style.transition="",t.style.opacity=e?"1":"0",t.style.pointerEvents=e?"auto":"none",t.style.visibility=e?"inherit":"hidden")}};var Zn=class{constructor(e,t){this.getElement=e;this.onPlayError=t;this.parked=!1;this.playOnReturn=!1}isParked(){return this.parked}setParked(e){if(e===this.parked)return;this.parked=e;let t=this.getElement();if(e){t&&!t.paused&&!t.ended&&(this.playOnReturn=!0,t.pause());return}this.playOnReturn&&(this.playOnReturn=!1,t?.play().catch(this.onPlayError))}requestPlay(){return this.parked?(this.playOnReturn=!0,!1):!0}cancel(){this.playOnReturn=!1}};function Ks({gameState:o,video:e,parked:t=!1}){let n=Tm(null),[i]=zc(()=>new Zn(()=>n.current,a=>{o.logger.error("Failed to resume video: "+a)}));Wc(()=>{i.setParked(t)},[t]);let[r]=zc(()=>new pr(()=>n.current,a=>{let l=Gi(a);return l===null?(o.logger.debug("NarraLeaf-React: Video",'Easing has no CSS equivalent, falling back to "ease"',a),"ease"):l}));_s(()=>o.events.depends([o.events.on(I.EventTypes["event:state.player.skip"],()=>{r.skip(),o.game.config.allowSkipVideo&&(s(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),Wc(()=>{r.isFading()||r.set(e.state.display)}),_s(()=>()=>r.dispose(),[r]),_s(()=>{if(!n.current)return;let a=n.current,l=!1,c=new Set,u=()=>new P(`Failed to add event listener, ref is not available
|
|
67
|
+
at Video.tsx: useEffect`),p=h=>{l||(l=!0,o.mountState(e,{show:m=>{if(!n.current)throw u();return r.fadeTo(!0,m)},hide:m=>{if(!n.current)throw u();return r.fadeTo(!1,m)},cancelFade:()=>{r.cancel(),r.set(e.state.display)},play:()=>{if(!n.current)throw u();let m=n.current;return h||m.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(m.currentTime=0,new Promise(g=>{let b=!1,y=null,S=[],T=()=>{b||(b=!0,c.delete(T),y&&y(),S.forEach(E=>E()),g())};c.add(T),y=o.schedule(({retry:E})=>{if(b)return;if(m.readyState<3){let k=()=>{m.removeEventListener("loadeddata",k),E()};m.addEventListener("loadeddata",k),S.push(()=>m.removeEventListener("loadeddata",k));return}let A=()=>T(),C=()=>T(),L=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),T()};m.addEventListener("ended",A),m.addEventListener("stopped",C),m.addEventListener("error",L),S.push(()=>{m.removeEventListener("ended",A),m.removeEventListener("stopped",C),m.removeEventListener("error",L)}),i.requestPlay()&&m.play().catch(k=>{o.logger.error("Failed to play video: "+k),T()})},10)}))},pause:()=>{if(!n.current)throw u();i.cancel(),n.current.pause()},resume:()=>{if(!n.current)throw u();return i.requestPlay()?n.current.play().catch(m=>{o.logger.error("Failed to resume video: "+m)}):Promise.resolve()},stop:()=>{if(!n.current)throw u();i.cancel(),n.current.pause(),n.current.dispatchEvent(new Event("stopped"))},seek:m=>{if(!n.current)throw u();n.current.currentTime=m}}))},d=()=>p(!1),f=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(a.error?` (media error code ${a.error.code})`:"")),p(!0)};return a.addEventListener("canplay",d),a.addEventListener("error",f),a.readyState>=3?p(!1):a.error&&f(),()=>{a.removeEventListener("canplay",d),a.removeEventListener("error",f),c.forEach(h=>h()),a.currentTime>0&&a.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function s(){n.current&&(n.current.pause(),n.current.currentTime=0,n.current.dispatchEvent(new Event("stopped")))}return bm.createElement("video",{ref:n,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:a=>a.preventDefault()})}import Am,{useEffect as xm,useLayoutEffect as Cm,useRef as wm,useState as km}from"react";function Pm(o,e){let t=Gi(e);return t===null?(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease"):t}function $s({gameState:o,vfx:e,parked:t=!1}){let n=wm(null),[i]=km(()=>new Zn(()=>n.current,r=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+r)}));return Cm(()=>{i.setParked(t)},[t]),xm(()=>{let r=n.current;if(!r)return;let s=!1,a=!1,l=0,c=!1,u=new Set,p=new Set,d=[],f=A=>{r.style.transition="",r.style.opacity=String(A)},h=()=>{i.requestPlay()&&r.play().catch(A=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+A)})},m=()=>s||r.error?(o.logger.error("NarraLeaf-React: Vfx","Cannot wait for a vfx whose source failed to load: "+e.config.src),Promise.resolve()):r.readyState>=2?Promise.resolve():new Promise(A=>{let C=!1,L=()=>X(),k=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),X()},X=()=>{C||(C=!0,p.delete(X),r.removeEventListener("loadeddata",L),r.removeEventListener("error",k),A())};p.add(X),r.addEventListener("loadeddata",L),r.addEventListener("error",k),(r.readyState>=2||r.error)&&X()}),g=(A,C,L)=>{let k=C?.duration??0,X=++l;return L.instant||k<=0?(f(A),Promise.resolve()):new Promise(R=>{let H=!1,z=null,le=()=>{H||(H=!0,p.delete(le),z!==null&&clearTimeout(z),l===X&&n.current&&f(A),R())};p.add(le),r.style.transition=`opacity ${k}ms ${Pm(o,C?.easing)}`,r.offsetWidth,r.style.opacity=String(A),z=setTimeout(le,k)})},b=A=>{a||(a=!0,s=A,o.mountState(e,{show:async C=>{c=!0;let L={instant:!1};u.add(L);try{if(await m(),!n.current)return;r.playbackRate=C?.rate??e.config.playbackRate,e.state.paused||h(),await g(C?.opacity??e.config.opacity,C,L)}finally{u.delete(L)}},hide:async C=>{c=!0;let L={instant:!1};u.add(L);try{await g(0,C,L),n.current&&r.pause()}finally{u.delete(L)}},pause:()=>{i.cancel(),r.pause()},resume:()=>{h()},setRate:C=>{r.playbackRate=C}}),e.state.display&&d.push(o.schedule(()=>{!c&&n.current&&f(e.config.opacity)},0)))},y=()=>b(!1),S=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(r.error?` (media error code ${r.error.code})`:"")),b(!0)},T=o.events.on(I.EventTypes["event:state.player.skip"],()=>{u.size===0&&p.size===0||(u.forEach(A=>{A.instant=!0}),[...p].forEach(A=>A()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),E=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&n.current&&h()};return document.addEventListener("visibilitychange",E),r.style.opacity="0",r.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&h(),r.addEventListener("canplay",y),r.addEventListener("error",S),r.readyState>=3?b(!1):r.error&&S(),()=>{r.removeEventListener("canplay",y),r.removeEventListener("error",S),document.removeEventListener("visibilitychange",E),T.cancel(),d.forEach(A=>A()),[...p].forEach(A=>A()),r.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),Am.createElement("video",{ref:n,src:e.config.src,preload:"auto",muted:e.config.muted,loop:e.config.loop,playsInline:!0,onContextMenu:r=>r.preventDefault(),style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:e.config.fit,pointerEvents:"none"}})}import Em from"clsx";import Dm,{useCallback as Lm,useEffect as dr,useRef as Rm}from"react";function js({children:o,className:e,gameState:t}){let{ratio:n}=be(),i=G(),[r]=me(),s=Rm(null),a=i.config.minWidth,l=i.config.minHeight,c=Lm(u=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(u.width,u.height,u.scale),n.updateMin(a,l),r()},[r,t.logger,l,a,n]);return dr(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),dr(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),dr(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,l,a]),dr(()=>t.events.on(I.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),Dm.createElement(ac,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:l,debounceMs:i.config.ratioUpdateInterval,className:Em(e),onUpdate:c},o)}import _c,{useEffect as Im,useRef as Mm,useState as Kc}from"react";function qs({src:o,width:e,height:t}){let[n,i]=Kc({x:0,y:0}),[r,s]=Kc(!1),a=Mm(null),{ratio:l}=be();return Im(()=>{let c=u=>{if(a.current){let p=a.current.getBoundingClientRect(),d=u.clientX-p.left,f=u.clientY-p.top;i({x:d,y:f}),r||s(!0)}};return window.addEventListener("mousemove",c),()=>{window.removeEventListener("mousemove",c)}},[r]),_c.createElement(_t,{ref:a,className:"overflow-hidden absolute"},_c.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${l.state.scale})`},alt:""}))}import $c from"react";import an from"react";function Qs({error:o,errorInfo:e}){return G().config.app.debug?an.createElement("div",{className:"text-left"},an.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),an.createElement("p",{className:"text-red-700"},"Message: ",o.message),an.createElement("pre",null,"Error Stack: ",o?.stack),an.createElement("pre",null,"Component Stack: ",e?.componentStack),an.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):an.createElement("div",{className:"bg-white w-full h-full"},an.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),an.createElement("p",null,"Please contact the game developer for further assistance."))}var mr=class extends $c.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?$c.createElement(Qs,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import Qc from"clsx";import F,{useEffect as kt,useLayoutEffect as eu,useReducer as Yc,useRef as tu,useState as ei}from"react";import{flushSync as Xc}from"react-dom";import{useRef as Nm}from"react";import{useEffect as Gm}from"react";function jc({gameState:o}){let e=Nm(null);return Gm(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(I.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import Oi,{useEffect as Om}from"react";function Ys({gameState:o}){let[e]=me(),{ratio:t}=be(),n=o.notificationMgr;Om(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return Oi.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},Oi.createElement(i,{notifications:n.toArray()}))}function qc({notifications:o}){return Oi.createElement(_o,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>Oi.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},Oi.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function nu({story:o=yi.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:l,onError:c,children:u,active:p=!0}){let[d,f]=Yc(_=>_+1,0),[h,m]=Yc(_=>_+1,0),[g,b]=ei(0),y=G(),[S]=ei(()=>new I(y,{update:f,forceUpdate:()=>{S.logger.weakWarn("Player","force update"),Xc(()=>{f()})},forceRemount:()=>{S.logger.weakWarn("Player","force remount"),Xc(()=>{b(_=>_+1),f()})},next:q})),T=F.createRef(),E=F.createRef(),[A,C]=ei(!1),L=F.useRef(!1),k=F.useRef(null),X=F.useRef(null),{preloaded:R,cacheManager:H}=$t(),[z,le]=ei(!1),qe=F.useRef(!1),[Qe,Ot]=ei(!1),We=F.useRef(!1),ft=F.useRef(null),te=F.useRef(!1),[xt]=ei(new Map);function N(_){return{game:y,gameState:S,liveGame:y.getLiveGame(),storable:y.getLiveGame().getStorable(),scene:_}}function q(){let _=()=>{xt.forEach(U=>U.cancel())};if(S.rollLock.isLocked())return;_();let D=!1,oe=0;for(;!D;){if(oe++>y.config.maxStackModelLoop)throw new P("Max stack model loop reached");let U=y.getLiveGame().next();if(!U){if(y.getLiveGame().stackModel&&!y.getLiveGame().stackModel.isEmpty())continue;break}if(v.isAwaitable(U)){if(k.current===U)break;k.current=U,U.onSettled(()=>{U.isFailed()||(k.current===U&&(k.current=null),q())}),U.onFailed(ye=>{k.current===U&&(k.current=null),S.logger.error("Player",ye)}),D=!0;break}if(U instanceof Nn){if(X.current===U)break;X.current=U,U.nextUnlock().then(()=>{X.current===U&&(X.current=null),q()}),D=!0;break}if(Ze.isCalledActionResult(U)&&U.wait&&Ze.isStackModelsAwaiting(U.wait.type,U.wait.stackModels)){if(k.current===U)break;if(k.current=U,U.wait){let ye=Ze.executeStackModelGroup(U.wait.type,U.wait.stackModels);ye.then(()=>{k.current===U&&(k.current=null),q()}),ye.onFailed(Ve=>{k.current===U&&(k.current=null),S.logger.error("Player",Ve)})}D=!0;break}S.handle(U)}S.stage.update()}kt(()=>{S.audioManager.initialize()},[]),kt(()=>(S.setImageCache(H),()=>{S.setImageCache(null)}),[H]),kt(()=>(y.getLiveGame().setGameState(S),o&&!y.getLiveGame().isPlaying()&&y.getLiveGame().loadStory(o),o?.entryScene&&!S.getPreloadingScene()&&!S.getLastScene()&&S.preloadScene(o.entryScene),S.playerCurrent=T.current,S.mainContentNode=E.current,()=>{y.getLiveGame().setGameState(void 0),S.playerCurrent=null}),[y,o]),kt(()=>ct(()=>{C(!0);let _=S.getLastScene(),D=[];_?D.push(_.events.once("event:scene.mount",()=>{S.stage.next()}).cancel):S.stage.next();let oe=S.events.on(I.EventTypes["event:state.end"],()=>{l&&l({game:y,gameState:S,liveGame:y.getLiveGame(),storable:y.getLiveGame().getStorable()})});return S.stage.update(),()=>{_&&D.forEach(U=>U()),oe.cancel()}}),[]),kt(()=>ct(()=>{A&&i&&!L.current&&(L.current=!0,S.stage.forceUpdate(),y.hooks.trigger("init",[]),i({game:y,gameState:S,liveGame:y.getLiveGame(),storable:y.getLiveGame().getStorable()}))}),[A]),kt(()=>ct(()=>{if(z&&s&&!qe.current){qe.current=!0;let _=ft.current||S.getLastScene()||S.getPreloadingScene(),D=N(_);s(D)}}),[z]),kt(()=>ct(()=>{if(Qe&&!We.current){We.current=!0;let _=ft.current||S.getLastScene()||S.getPreloadingScene(),D=N(_);y.markPreloadComplete(D)&&r&&r(D)}}),[Qe]),kt(()=>S.events.on(I.EventTypes["event:state.scene.mount"],_=>{ft.current||(ft.current=_,m())}).cancel,[]),kt(()=>{if(!Qe||!p||te.current||y.isFirstSceneReady())return;let _=ft.current||S.getLastScene();if(!_)return;let D=null,oe=null,U=!1;te.current=!0;let ye=()=>{U=!0,te.current=!1;let Ve=N(_);y.markFirstSceneReady(Ve)&&a&&a(Ve)};return typeof requestAnimationFrame=="function"?D=requestAnimationFrame(()=>{oe=setTimeout(ye,0)}):oe=setTimeout(ye,0),()=>{U||(te.current=!1,D!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(D),oe!==null&&clearTimeout(oe))}},[p,h,d,Qe]),kt(()=>R.events.depends([R.events.on(at.EventTypes["event:preloaded.ready"],()=>{le(!0),S.stage.update(),o&&y.getLiveGame().isPlaying()&&q()}),R.events.on(at.EventTypes["event:preloaded.complete"],()=>{Ot(!0)})]).cancel,[]),kt(()=>{S.flushDep=d},[d]);let pe=e||y.config.width,ge=t||y.config.height;return F.createElement(mr,{onError:c},F.createElement("div",{style:{width:typeof pe=="number"?`${pe}px`:pe,height:typeof ge=="number"?`${ge}px`:ge},className:Qc(n,"__narraleaf_content-player"),ref:T,tabIndex:0},F.createElement(js,{className:Qc("flex-grow overflow-auto"),gameState:S},F.createElement(ws,{gameState:S}),F.createElement(jc,{gameState:S}),F.createElement(_t,{className:"absolute",ref:E,style:{cursor:S.game.config.cursor?"none":"auto",overflow:S.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},y.config.cursor&&F.createElement(qs,{src:y.config.cursor,width:y.config.cursorWidth,height:y.config.cursorHeight}),F.createElement(Vm,{show:z&&p,key:g},F.createElement(bs,null,F.createElement(mc,{state:S}),F.createElement(vc,{state:S}),F.createElement(Hm,{state:S},F.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},F.createElement(Fm,{state:S})),F.createElement(Um,{state:S})),S.getSceneElements().map(_=>F.createElement(Ws,{key:"scene-dialogs-"+_.scene.getId(),state:S,elements:_})),F.createElement(Bm,{NvlComponent:y.config.nvlDialog}))),F.createElement(Ac,{state:S}),F.createElement(tc,null,u),F.createElement(Ys,{gameState:S})))))}function Vm({children:o,show:e}){return F.createElement(F.Fragment,null,e?o:null)}function Fm({state:o}){let e=[],t=new Set,n=new Set;return o.getSceneElements().forEach(i=>{let r=i.suspended===!0;e.push(F.createElement(Hs,{key:"scene-"+i.scene.getId(),state:o,elements:i})),o.getVideosOf(i.scene).forEach(s=>{t.add(s),e.push(F.createElement(Jc,{key:"video-"+s.getId(),state:o,video:s,owner:i.scene,parked:r}))}),o.getVfxOf(i.scene).forEach(s=>{n.add(s),e.push(F.createElement(Zc,{key:"vfx-"+s.getId(),state:o,vfx:s,owner:i.scene,parked:r}))})}),o.getVideos().forEach(i=>{t.has(i)||e.push(F.createElement(Jc,{key:"video-"+i.getId(),state:o,video:i,owner:null,parked:!1}))}),o.getVfx().forEach(i=>{n.has(i)||e.push(F.createElement(Zc,{key:"vfx-"+i.getId(),state:o,vfx:i,owner:null,parked:!1}))}),F.createElement(F.Fragment,null,e)}function Jc({state:o,video:e,owner:t,parked:n}){let i=tu(null);return eu(()=>{if(!(!t||!i.current))return o.stageTransition.bindCompanion(t,i.current)},[t]),F.createElement("div",{className:"w-full h-full absolute",ref:i,"data-element-type":"video"},F.createElement(Ks,{gameState:o,video:e,parked:n}))}function Zc({state:o,vfx:e,owner:t,parked:n}){let i=tu(null);return eu(()=>{if(!(!t||!i.current))return o.stageTransition.bindCompanion(t,i.current,{keepZIndex:!0})},[t]),F.createElement("div",{className:"w-full h-full absolute",ref:i,"data-element-type":"vfx",style:{zIndex:e.config.zIndex,mixBlendMode:e.config.blendMode}},F.createElement($s,{gameState:o,vfx:e,parked:n}))}function Hm({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?F.createElement(Uc,{state:o,camera:t},e):F.createElement(F.Fragment,null,e)}function Um({state:o}){let e=F.useRef(null);return kt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),F.createElement("div",{className:"w-full h-full absolute pointer-events-none",ref:e,"data-element-type":"stage-transition-overlay-host"})}function Bm({NvlComponent:o}){let{dialogs:e,state:t}=jt(),i=G().getLiveGame().getGameState(),r=F.useMemo(()=>e.map((s,a)=>{let l=s.sentence.evaluate(Ee.getCtx({gameState:i})),c=t.activeDialogId===s.id,u=c&&t.phase==="typing";return{entry:s,index:a,isActive:c,gameState:i,words:l,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return F.createElement(o,{dialogs:r})}import"client-only";import ti from"react";function iu({children:o,game:e}){return ti.createElement(ti.Fragment,null,ti.createElement(pl,null,ti.createElement(sl,{game:e},ti.createElement(Ql,null,ti.createElement(ul,null,o)))))}var Wm=(l=>(l.image="narraleaf:image",l.text="narraleaf:text",l.layer="narraleaf:layer",l.scene="narraleaf:scene",l.video="narraleaf:video",l.vfx="narraleaf:vfx",l.camera="narraleaf:camera",l.puppet="narraleaf:puppet",l))(Wm||{});import zm from"clsx";import Pt,{useEffect as ru,useRef as _m,useState as Km}from"react";function ou(o){return o?{className:"",ariaHidden:!1}:{className:"opacity-0",ariaHidden:!0}}import{motion as $m,useIsPresent as jm}from"motion/react";var qm={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Qm({children:o,initial:e,transition:t,...n}){let i=G(),r=Mt(),{ratio:s}=be(),[a]=vn(Y.Preferences.showDialog),l=_m(null),[c]=Dn("nextAction"),u=jm(),[p,d]=Km(null),f=ou(a);function h(){a&&(r.config.gameState.isAdvanceSuspended()||r.requestComplete())}return ru(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
68
|
+
at Say.tsx: onElementClick`);return}let m=b=>{b.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",b.key)&&r.requestComplete()};window.addEventListener("keydown",m);let g=r.events.on(Oe.Events.simulateClick,()=>{l.current&&l.current.click()});return()=>{window.removeEventListener("keydown",m),g.cancel()}},[r,c]),ru(()=>{let m=i.preference.onPreferenceChange(Y.Preferences.autoForward,g=>{g&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{m.cancel()}},[r]),Pt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},Pt.createElement("div",{className:zm("absolute bottom-0 w-full h-full",f.className),"aria-hidden":f.ariaHidden,onClick:h,style:{...Vn(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:l},Pt.createElement(Cs,{value:p},Pt.createElement($m.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),Pt.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:d})))}function su({children:o,...e}){let t=Mt();return!t.config.action.sentence||!t.config.action.words?null:Pt.createElement(Qm,{...e},o)}var Vd=su;function au(){return Pt.createElement(su,null,Pt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},Pt.createElement(ds,null),Pt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},Pt.createElement(sn,null),Pt.createElement(Sn,{...qm}))))}var Vi={say:au,menu:Vc,notification:qc,nvlDialog:xs};var fr=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var Fi=class{constructor(e={}){this.keyMap=e;this.events=new ee}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],i=r=>Array.isArray(r)?r:[r];Array.isArray(n)?this.setKeyBinding(e,[...n,...i(t)]):this.setKeyBinding(e,[n,...i(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,i)=>{n===e&&t(i)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(i=>i.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var lu=(e=>(e.game="game",e))(lu||{}),et=class et{constructor(e){this.hooks=new Xi;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new xi(et.DefaultPreference);this.audioBuses=new di(()=>this.config.audioBuses??[],Ga(this.preference));this.keyMap=new Fi({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new ee;this.puppetBackends=new sr;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=Q(et.DefaultConfig,e),this.plugins=new fr(this),this.router=new yn(this)}configure(e){let[t,n]=xa(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=Q(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(I.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}registerPuppetBackend(e){return this.puppetBackends.register(e),this}getPuppetBackend(e){return this.puppetBackends.get(e)}listPuppetBackends(){return this.puppetBackends.list()}getPuppetBackendRegistry(){return this.puppetBackends}onPreloadComplete(e){return this.lifecycleEvents.on(et.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(et.LifecycleEventTypes["event:game.preloadComplete"],e)}whenPreloadComplete(){return this.preloadCompleteContext?Promise.resolve(this.preloadCompleteContext):new Promise(e=>{this.oncePreloadComplete(e)})}isPreloadComplete(){return this.preloadCompleteContext!==null}onFirstSceneReady(e){return this.lifecycleEvents.on(et.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(et.LifecycleEventTypes["event:game.firstSceneReady"],e)}whenFirstSceneReady(){return this.firstSceneReadyContext?Promise.resolve(this.firstSceneReadyContext):new Promise(e=>{this.onceFirstSceneReady(e)})}isFirstSceneReady(){return this.firstSceneReadyContext!==null}markPreloadComplete(e){return this.preloadCompleteContext?!1:(this.preloadCompleteContext=e,this.lifecycleEvents.emit(et.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(et.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.audioBuses.dispose(),this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Wt(this)}};et.defaultSettings={volume:1},et.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,textRevealDuration:0,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:0,skipInterval:100},et.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",textRevealDuration:"textRevealDuration",voiceVolume:"voiceVolume",voiceFadeDuration:"voiceFadeDuration",voiceEndMode:"voiceEndMode",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},et.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadGate:"firstFrame",preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,imageCacheBudgetBytes:256*1024*1024,decodedImageBudgetBytes:128*1024*1024,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipSceneTransition:!0,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:Vi.notification,menu:Vi.menu,dialog:Vi.say,nvlDialog:Vi.nvlDialog,onError:e=>{console.error(e)},disableTextScaling:!1,stage:null,maxStackModelLoop:1e3,maxActionHistory:100,maxSceneCallDepth:8,audioBuses:[],audioStreaming:"loops"},et.GameSettingsNamespace=lu,et.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var Y=et;var hr=class hr extends J{constructor(){super(...arguments);this._jumpTarget=null}setJumpTarget(t){return this._jumpTarget=t,this}getJumpTarget(){return this._jumpTarget}static executeActionsAsync(t,n){let i=t.game.getLiveGame().requestAsyncStackModel([{type:n.type,node:n.contentNode}]);return t.game.getLiveGame().executeAsyncStackModel(i)}checkActionChain(t){if(t.some(n=>!!n.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return t}executeAction(t,n){let i=this.contentNode,[r]=i.getContent();if(this.type===ce.do)return r.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:r[0].contentNode}];if(this.type===ce.doAsync){if(r.length===0)return super.executeAction(t,n);let s=hr.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===ce.any){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:s}}}else if(this.type===ce.all){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:s}}}else if(this.type===ce.allAsync){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().requestAsyncStackModel([{type:a.type,node:a.contentNode}]));return t.timelines.attachTimeline(v.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===ce.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let l=Ze.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[l]}}}else if(this.type===ce.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let l=Ze.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[l]}}}else if(this.type===ce.break){if(!n.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return n.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===ce.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=v.delay(s):v.isAwaitable(s)?a=s:a=v.fromPromise(s);let l=new v,c=new De(a);return t.timelines.attachTimeline(c),a.then(()=>{l.resolve({type:this.type,node:this.contentNode.getChild()})}),l.onSkipControllerRegister(u=>{u.onAbort(()=>{c.abort()})}),l}else if(this.type===ce.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new v,a=new v,l=new De(a);t.timelines.attachTimeline(l);let c=t.game.preference,u=c.getPreference(Y.Preferences.autoForward),p=c.getPreference(Y.Preferences.gameSpeed),d=u?t.game.config.autoForwardDelay/p:null,f=!1,h=null,m=null,g=null,b=()=>{m?.cancel(),g?.cancel(),h&&(clearTimeout(h),h=null)},y=()=>{f||(f=!0,b(),a.resolve())};return m=t.events.on(I.EventTypes["event:state.player.stageClick"],y),g=t.events.on(I.EventTypes["event:state.player.skip"],y),d!==null&&(h=setTimeout(y,d)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(S=>{S.onAbort(()=>{f||(f=!0,b(),l.abort())})}),s}else{if(this.type===ce.label)return super.executeAction(t,n);if(this.type===ce.jump){let s=this._jumpTarget;if(!s){let[c]=this.contentNode.getContent();throw new ke(`Jump target label "${c}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),l=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(c,u)},[l]),a.getStackModelForce().clearAboveCallFrame().push({type:this.type,node:s.contentNode}),null}}throw new Error("Unknown control action type: "+this.type)}getFutureActions(t,n){if(this.callee.config.allowFutureScene===!1&&n.allowFutureScene===!1)return[...super.getFutureActions(t,n)];if(this.type===ce.break||this.type===ce.waitForClick||this.type===ce.label||this.type===ce.jump)return super.getFutureActions(t,n);let i=this.contentNode.getContent()[0],r=super.getFutureActions(t,n);return[...i??[],...r]}stringify(t,n,i){if(this.type===ce.break)return super.stringifyWithContent("Control","break");if(this.type===ce.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===ce.label||this.type===ce.jump){let[a]=this.contentNode.getContent(),l=this.type===ce.label?"label":"jump";return super.stringifyWithContent("Control",`${l}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};hr.ActionTypes=ce;var ue=hr;var Fe=class o extends fe{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static whileLoop(t,n){return new o().whileLoop(t,n)}static breakLoop(){return new o().breakLoop()}static sleep(t){return new o().sleep(t)}static waitForClick(){return new o().waitForClick()}static label(t){return new o().label(t)}static jump(t){return new o().jump(t)}do(t){return this.push(ue.ActionTypes.do,t)}doAsync(t){return this.push(ue.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(ue.ActionTypes.any,t)}all(t){return this.pushUnchained(ue.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(ue.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(ue.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=Z.from(t);return this.pushWithLambda(ue.ActionTypes.while,n,i)}breakLoop(){let t=new ue(this.chain(),ue.ActionTypes.break,new x().setContent([]));return this.chain(t)}sleep(t){return this.push(ue.ActionTypes.sleep,[],t)}waitForClick(){let t=new ue(this.chain(),ue.ActionTypes.waitForClick,new x().setContent([]));return this.chain(t)}label(t){let n=new ue(this.chain(),ue.ActionTypes.label,new x().setContent([t]));return this.chain(n)}jump(t){let n=new ue(this.chain(),ue.ActionTypes.jump,new x().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new ue(this.chain(),t,new x().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new ue(this.chain(),t,new x().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new ue(this.chain(),t,new x().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?nn.say(n).getActions():Ke.toActions([n]))}};var j=class j extends je{static get DefaultUserConfig(){return j._defaultUserConfig??(j._defaultUserConfig=new $({name:"(anonymous)",autoInit:!0,src:j.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...se.DefaultTransformState.getDefaultConfig()},{position:e=>V.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return w.isStaticImageData(t)?w.srcToURL(t):w.isColor(t)?t:w.isImageSrc(t)?w.srcToURL(t):j.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isLayeredSrc(e){return!!e.config.src?.slots}static isSrcDefinitionObject(e){return typeof e=="object"&&e!==null&&!w.isImageSrc(e)&&!w.isColor(e)}static isLayeredDefinition(e){return this.isSrcDefinitionObject(e)&&"layers"in e}static isTagDefinition(e){return this.isSrcDefinitionObject(e)&&"resolve"in e}static isLayerVariants(e){return typeof e=="object"&&e!==null}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(w.isImageSrc(t)||w.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:j.isLayeredSrc(e)?null:j.isTagSrc(e)&&e.config.src.resolve?j.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):j.isStaticSrc(e)?w.isStaticImageData(e.state.currentSrc)?w.srcToURL(e.state.currentSrc):w.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static getSrcURLs(e,t){let n=e.config.src?.slots;if(!n)return[];let i=new Set(t??e.state.currentSrc);return n.map(r=>j.resolveLayerSlot(r,i))}static resolveLayerSlot(e,t){if(e===null||typeof e=="string")return e;if(typeof e=="function")return e(t);for(let[n,i]of Object.entries(e))if(t.has(n))return i;return null}static getAllLayerSrc(e){let t=e.config.src?.slots;if(!t)return[];let n=[];for(let i of t)if(typeof i=="string")n.push(i);else if(j.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new j({src:e})}constructor(e={}){super();let t=j.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new Fe,n=>{if(w.isImageSrc(e)||w.isColor(e)){if(w.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new Ae(n,Ae.ActionTypes.setAppearance,new x().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Fe,i=>i.chain(this._setDarkness(i,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new ne("Cannot add self as a wearable");this.config.wearables.push(n),Object.assign(n.config,{isWearable:!0})}return this}wear(e){return this.addWearable(e)}bindWearable(e){return e.addWearable([this])}asWearableOf(e){return this.bindWearable(e)}useLayer(e){return this.userConfig.get().layer=e||void 0,Object.assign(this.config,{layer:e||void 0}),this}toData(){return{state:j.StateSerializer.serialize(this.state),transformState:se.TransformStateSerializer.serialize(this.transformState.get()),loop:this._serializeLoop()}}fromData(e){return this.state=j.StateSerializer.deserialize(e.state),this.transformState.resetTo(se.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_applyTransition(e,t){return new Ce(this.chain(),he.applyTransition,new x().setContent([e,t]))}_init(e,t){return new Ce(this.chain(),he.init,new x().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new Ae(this.chain(),Ae.ActionTypes.initWearable,new x().setContent([e]))}_flush(){return new Ae(this.chain(),Ae.ActionTypes.flush,new x)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get()),this}resolveTags(e,t){if(!j.isTagSrc(this))throw new Error(`Tag not defined
|
|
69
|
+
Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(l=>{let c=n.get(l);c&&i.set(c,l)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let l=i.get(a);if(!l)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(l)}),r}_setAppearanceSync(e){if(w.isImageSrc(e)||w.isColor(e)){if(w.isColor(e)&&!this.config.isBackground)throw new ne("Color src is not allowed for non-background image");this.state.currentSrc=e;return}if(!j.isTagSrc(this))throw this._mixedSrcError();let t=this.state.currentSrc,n=this.resolveTags(t,e);this.state.currentSrc=n}_mixedSrcError(){throw new ne(`Trying to mix src and tags
|
|
70
70
|
To better understand the behavior of the image, you cannot mix static src and tags in the same image. `)}_invalidSrcHandlerError(){throw new Error("Invalid src handler, If you are using tags, config.src must be a function that resolves the src from the tags. If you are using src, config.src must be a string or StaticImageData")}_invalidWearableError(e){throw new Error(`Invalid wearable
|
|
71
71
|
Wearable must be an Image with isWearable set to true
|
|
72
72
|
It seems like you are trying to add a non-wearable image to wearables
|
|
73
73
|
Image below violates the rule:
|
|
74
74
|
`+e)}_invalidTagGroupDefinitionError(e,t=!1){throw new Error("Invalid tag group definition. Tags in groups must be unique and not conflicting with each other."+(e?`
|
|
75
75
|
Tag "${e}" belongs to more than one group.`:"")+(t?`
|
|
76
|
-
Layers offering the same tag set share one group, so a shared tag means two layers offer different sets. Repeat the whole set on every layer that follows the group, using null where that layer draws nothing.`:""))}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(Ae.resolveCurrentSrc(this))._setTargetSrc(t))),new Ae(e,Ae.ActionTypes.setSrc,new
|
|
76
|
+
Layers offering the same tag set share one group, so a shared tag means two layers offer different sets. Repeat the whole set on every layer that follows the group, using null where that layer draws nothing.`:""))}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(Ae.resolveCurrentSrc(this))._setTargetSrc(t))),new Ae(e,Ae.ActionTypes.setSrc,new x().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){let e=this.config.src;return e?.slots?j.getAllLayerSrc(this).forEach(t=>this.srcManager.registerRawSrc(t)):e?.resolve?this.srcManager.registerRawSrc(j.getSrcFromTags(e.defaults,e.resolve)):w.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(w.srcToURL(this.state.currentSrc)),this}static collectLayerGroups(e){let t=[],n=new Set;for(let i of e){if(!j.isLayerVariants(i))continue;let r=Object.keys(i),s=[...r].sort().join("\0");n.has(s)||(n.add(s),t.push(r))}return t}static normalizeSrcDefinition(e){return j.isLayeredDefinition(e)?{groups:j.collectLayerGroups(e.layers),defaults:[...e.defaults],resolve:null,slots:e.layers}:j.isTagDefinition(e)?{groups:e.groups,defaults:[...e.defaults],resolve:e.resolve,slots:null}:null}createImageConfig(e){let t=e.get();return j.DefaultImageConfig.create({...t,src:j.normalizeSrcDefinition(t.src)})}getInitialState(){return j.DefaultImageState.create().assign({currentSrc:j.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(se.DefaultTransformState.keys());return new se(se.DefaultTransformState.create(t.get()).get())}checkConfig(){for(let e of this.config.wearables)if(!e.config.isWearable)throw this._invalidWearableError(JSON.stringify(e.config));if(j.isTagSrc(this)){let e=this.config.src,t=new Set;for(let r of e.groups)for(let s of r){if(t.has(s))throw this._invalidTagGroupDefinitionError(s,!!e.slots);t.add(s)}let n=this.constructTagMap(e.groups),i=new Set;for(let r of e.defaults){if(i.has(r))throw new Error(`Tag conflict
|
|
77
77
|
Tag "${r}" is conflicting with another tag
|
|
78
78
|
Error found in config.tag.defaults`);if(!n.has(r))throw new Error(`Tag not found
|
|
79
79
|
Tag "${r}" is not defined in tagDefinitions
|
|
80
|
-
Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}if(e.slots){let r=new Set(e.defaults);for(let s of e.groups)if(!s.some(a=>r.has(a)))throw new
|
|
81
|
-
The group with tags "${s.join(", ")}" needs exactly one of them listed in src.defaults`)}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new Ae(e,Ae.ActionTypes.setDarkness,new A().setContent([t,n,i]))}};j.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",j.StateSerializer=new Xe,j._defaultUserConfig=null,j.DefaultImageConfig=new $({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),j.DefaultImageState=new $({currentSrc:j.DefaultImagePlaceholder,darkness:0});var O=j;var we=class extends Bt{constructor(){super(...arguments);this._detached=!1}_setDetached(t){return this._detached=t,this}_isDetached(){return this._detached}_setPrevLayers(t){return this._prevLayers=t,this}_setTargetLayers(t){return this._targetLayers=t,this}_getPrevLayers(){return this._prevLayers}_getTargetLayers(){return this._targetLayers}_isLayered(){return!!this._prevLayers||!!this._targetLayers}_setPrevSrc(t){return this._prevSrc=t,this}_setTargetSrc(t){return this._targetSrc=t,this}_setCurrentSrc(t){return this._currentSrc=t,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),n}asPrev(t){return super.asPrev((...n)=>Q(t(...n),this._srcToProps(this._prevSrc)))}asTarget(t){return super.asTarget((...n)=>Q(t(...n),this._srcToProps(this._targetSrc)))}_srcToProps(t){if(this._isLayered()||this._detached)return{};if(k.isColor(t))return{src:O.DefaultImagePlaceholder,style:{backgroundColor:k.isRGBAColor(t)?k.RGBAColorToHex(t):t}};if(k.isImageSrc(t))return{src:k.srcToURL(t)};throw new te("Image transition src cannot be identified, using: "+t)}};import{anticipate as $m,backIn as jm,backInOut as qm,backOut as Qm,circIn as Ym,circInOut as Xm,circOut as Jm,cubicBezier as Zm,easeIn as ef,easeInOut as iu,easeOut as tf}from"motion/react";var nu=1;function _(o){return o<0?0:o>1?1:o}function ou(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function Ys(o){return{position:"absolute",top:"50%",left:"50%",width:`calc(100% + ${nu*2}px)`,height:`calc(100% + ${nu*2}px)`,transform:"translate(-50%, -50%)",backgroundColor:o}}function ru(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 su(o){return o==="vertical"?"to right":"to bottom"}var nf={easeIn:ef,easeOut:tf,easeInOut:iu,circIn:Ym,circOut:Jm,circInOut:Xm,backIn:jm,backOut:Qm,backInOut:qm,anticipate:$m};function Xs(o){return typeof o=="function"?o:Array.isArray(o)?Zm(o[0],o[1],o[2],o[3]):o==="linear"?e=>e:nf[o??"easeInOut"]??iu}function hr(o){let e=Xs(o.easing),t=(1-Fi(o))/2,n=1-t;return i=>i<=t?t<=0?1:e(_(i/t)):i>=n?n>=1?1:e(_((1-i)/(1-n))):1}function Fi(o){return o.holdMs!==void 0?o.duration<=0?o.holdMs>0?1:0:_(o.holdMs/o.duration):_(o.hold??0)}var Vi=class o extends we{constructor(e){super(),this.from=e.from,this.to=e.to,this.duration=e.duration,this.holdMs=e.holdMs,this.easing=e.easing}createTask(){let e=Fi({duration:this.duration,holdMs:this.holdMs}),t=Xs(this.easing),n=i=>i<=e?this.from:e>=1?this.from:this.from+(this.to-this.from)*t((i-e)/(1-e));return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asTarget(i=>({style:{filter:`brightness(${1-n(i)})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o({from:this.from,to:this.to,duration:this.duration,holdMs:this.holdMs,easing:this.easing})}};var Hi=class Hi extends X{static resolveTagSrc(e,t){if(!O.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return O.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(O.isLayeredSrc(e))throw e._mixedSrcError();if(O.isStaticSrc(e))return k.isImageSrc(e.state.currentSrc)?k.srcToURL(e.state.currentSrc):e.state.currentSrc;if(O.isTagSrc(e)&&e.config.src.resolve)return O.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===ht.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new v(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===ht.setSrc){let n=this.contentNode.getContent()[0];if(k.isColor(n)&&!this.callee.config.isBackground)throw new te("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else{if(this.type===ht.flush)return super.executeAction(e,t);if(this.type===ht.setAppearance){let[n,i]=this.contentNode.getContent();if(!O.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],l=()=>{this.callee.state.currentSrc=a};if(O.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let p=new v(m=>m).registerSkipController(new B(()=>super.executeAction(e,t)));i._setPrevLayers(O.getSrcURLs(this.callee))._setTargetLayers(O.getSrcURLs(this.callee,s));let f=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(p).attachChild(f);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},l,[]),p}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),e.stage.update(),e.getExposedState(this.callee)?.flush(),super.executeAction(e,t)}let c=this.callee.config.src.resolve;if(!c)throw this.callee._invalidSrcHandlerError();let u=O.getSrcFromTags(s,c);if(e.logger.debug("Image - Set Appearance",s,u),i){let p=new v(m=>m).registerSkipController(new B(()=>super.executeAction(e,t)));i._setPrevSrc(Hi.resolveCurrentSrc(this.callee))._setTargetSrc(u);let f=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(p).attachChild(f);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},l,[]),p}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else if(this.type===ht.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},l=e.getExposedStateForce(this.callee);if(i){let c=new v(f=>f),u=new Vi({from:s,to:n,duration:i,easing:r});if(O.isLayeredSrc(this.callee)){let f=O.getSrcURLs(this.callee);u._setPrevLayers(f)._setTargetLayers(f)}else{let f=Hi.resolveCurrentSrc(this.callee);u._setPrevSrc(f)._setTargetSrc(f)}let p=l.applyTransition(u,()=>{this.callee.state.darkness=n,c.resolve(super.executeAction(e,t))}),d=e.timelines.attachTimeline(c).attachChild(p);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:d},()=>{c.isSettled()||c.abort(),p.abort(),a()}),c}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),l.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};Hi.ActionTypes=ht;var Ae=Hi;var Js=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},Et=class Et{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||Et.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return Et.isHexString(e)||Et.isNamedColor(e)||Et.isRGBAColor(e)}static isNamedColor(e){return Sa(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(Et.isHexString(e))return e;if(Et.isNamedColor(e))return e;if(Et.isRGBAColor(e))return Et.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static isInlineSrc(e){return Et.isDataURI(e)||e.startsWith("blob:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,l=this.calc(i,s),c=this.calc(r,a),u=n.invertX?{right:l}:{left:l},p=n.invertY?{bottom:c}:{top:c};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...p}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};Et.RGBColor=Js;var k=Et,Zs=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},He=class o extends Zs{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},Ao=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let l=a.contentNode.getChild();l&&l.action&&i.push(l.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof Ae)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof oe){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
|
|
80
|
+
Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}if(e.slots){let r=new Set(e.defaults);for(let s of e.groups)if(!s.some(a=>r.has(a)))throw new ne(`Layer has no default
|
|
81
|
+
The group with tags "${s.join(", ")}" needs exactly one of them listed in src.defaults`)}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new Ae(e,Ae.ActionTypes.setDarkness,new x().setContent([t,n,i]))}};j.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",j.StateSerializer=new Xe,j._defaultUserConfig=null,j.DefaultImageConfig=new $({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),j.DefaultImageState=new $({currentSrc:j.DefaultImagePlaceholder,darkness:0});var O=j;var we=class extends Bt{constructor(){super(...arguments);this._detached=!1}_setDetached(t){return this._detached=t,this}_isDetached(){return this._detached}_setPrevLayers(t){return this._prevLayers=t,this}_setTargetLayers(t){return this._targetLayers=t,this}_getPrevLayers(){return this._prevLayers}_getTargetLayers(){return this._targetLayers}_isLayered(){return!!this._prevLayers||!!this._targetLayers}_setPrevSrc(t){return this._prevSrc=t,this}_setTargetSrc(t){return this._targetSrc=t,this}_setCurrentSrc(t){return this._currentSrc=t,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),n}asPrev(t){return super.asPrev((...n)=>Q(t(...n),this._srcToProps(this._prevSrc)))}asTarget(t){return super.asTarget((...n)=>Q(t(...n),this._srcToProps(this._targetSrc)))}_srcToProps(t){if(this._isLayered()||this._detached)return{};if(w.isColor(t))return{src:O.DefaultImagePlaceholder,style:{backgroundColor:w.isRGBAColor(t)?w.RGBAColorToHex(t):t}};if(w.isImageSrc(t))return{src:w.srcToURL(t)};throw new ne("Image transition src cannot be identified, using: "+t)}};import{anticipate as Ym,backIn as Xm,backInOut as Jm,backOut as Zm,circIn as ef,circInOut as tf,circOut as nf,cubicBezier as of,easeIn as rf,easeInOut as uu,easeOut as sf}from"motion/react";var cu=1;function K(o){return o<0?0:o>1?1:o}function pu(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function Xs(o){return{position:"absolute",top:"50%",left:"50%",width:`calc(100% + ${cu*2}px)`,height:`calc(100% + ${cu*2}px)`,transform:"translate(-50%, -50%)",backgroundColor:o}}function du(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 mu(o){return o==="vertical"?"to right":"to bottom"}var af={easeIn:rf,easeOut:sf,easeInOut:uu,circIn:ef,circOut:nf,circInOut:tf,backIn:Xm,backOut:Zm,backInOut:Jm,anticipate:Ym};function Js(o){return typeof o=="function"?o:Array.isArray(o)?of(o[0],o[1],o[2],o[3]):o==="linear"?e=>e:af[o??"easeInOut"]??uu}function gr(o){let e=Js(o.easing),t=(1-Hi(o))/2,n=1-t;return i=>i<=t?t<=0?1:e(K(i/t)):i>=n?n>=1?1:e(K((1-i)/(1-n))):1}function Hi(o){return o.holdMs!==void 0?o.duration<=0?o.holdMs>0?1:0:K(o.holdMs/o.duration):K(o.hold??0)}var Ui=class o extends we{constructor(e){super(),this.from=e.from,this.to=e.to,this.duration=e.duration,this.holdMs=e.holdMs,this.easing=e.easing}createTask(){let e=Hi({duration:this.duration,holdMs:this.holdMs}),t=Js(this.easing),n=i=>i<=e?this.from:e>=1?this.from:this.from+(this.to-this.from)*t((i-e)/(1-e));return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asTarget(i=>({style:{filter:`brightness(${1-n(i)})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o({from:this.from,to:this.to,duration:this.duration,holdMs:this.holdMs,easing:this.easing})}};var Bi=class Bi extends J{static resolveTagSrc(e,t){if(!O.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return O.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(O.isLayeredSrc(e))throw e._mixedSrcError();if(O.isStaticSrc(e))return w.isImageSrc(e.state.currentSrc)?w.srcToURL(e.state.currentSrc):e.state.currentSrc;if(O.isTagSrc(e)&&e.config.src.resolve)return O.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===ht.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new v(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===ht.setSrc){let n=this.contentNode.getContent()[0];if(w.isColor(n)&&!this.callee.config.isBackground)throw new ne("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else{if(this.type===ht.flush)return super.executeAction(e,t);if(this.type===ht.setAppearance){let[n,i]=this.contentNode.getContent();if(!O.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],l=()=>{this.callee.state.currentSrc=a};if(O.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let p=new v(m=>m).registerSkipController(new B(()=>super.executeAction(e,t)));i._setPrevLayers(O.getSrcURLs(this.callee))._setTargetLayers(O.getSrcURLs(this.callee,s));let f=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(p).attachChild(f);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},l,[]),p}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),e.stage.update(),e.getExposedState(this.callee)?.flush(),super.executeAction(e,t)}let c=this.callee.config.src.resolve;if(!c)throw this.callee._invalidSrcHandlerError();let u=O.getSrcFromTags(s,c);if(e.logger.debug("Image - Set Appearance",s,u),i){let p=new v(m=>m).registerSkipController(new B(()=>super.executeAction(e,t)));i._setPrevSrc(Bi.resolveCurrentSrc(this.callee))._setTargetSrc(u);let f=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),h=e.timelines.attachTimeline(p).attachChild(f);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:h},l,[]),p}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else if(this.type===ht.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},l=e.getExposedStateForce(this.callee);if(i){let c=new v(f=>f),u=new Ui({from:s,to:n,duration:i,easing:r});if(O.isLayeredSrc(this.callee)){let f=O.getSrcURLs(this.callee);u._setPrevLayers(f)._setTargetLayers(f)}else{let f=Bi.resolveCurrentSrc(this.callee);u._setPrevSrc(f)._setTargetSrc(f)}let p=l.applyTransition(u,()=>{this.callee.state.darkness=n,c.resolve(super.executeAction(e,t))}),d=e.timelines.attachTimeline(c).attachChild(p);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:d},()=>{c.isSettled()||c.abort(),p.abort(),a()}),c}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),l.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};Bi.ActionTypes=ht;var Ae=Bi;var Zs=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},Et=class Et{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||Et.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return Et.isHexString(e)||Et.isNamedColor(e)||Et.isRGBAColor(e)}static isNamedColor(e){return ba(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(Et.isHexString(e))return e;if(Et.isNamedColor(e))return e;if(Et.isRGBAColor(e))return Et.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static isInlineSrc(e){return Et.isDataURI(e)||e.startsWith("blob:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,l=this.calc(i,s),c=this.calc(r,a),u=n.invertX?{right:l}:{left:l},p=n.invertY?{bottom:c}:{top:c};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...p}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};Et.RGBColor=Zs;var w=Et,ea=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},He=class o extends ea{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},xo=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let l=a.contentNode.getChild();l&&l.action&&i.push(l.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof Ae)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof re){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
|
|
82
82
|
Scene: ${s.config.name}
|
|
83
83
|
|
|
84
|
-
At: ${t.__stack}`;throw new He(a)}}else i.set(s.config.name,s);if(t.type===
|
|
84
|
+
At: ${t.__stack}`;throw new He(a)}}else i.set(s.config.name,s);if(t.type===W.jumpTo){let a=t.contentNode.getContent()[0],l=e.getScene(a,!0);if(r.has(l))return;r.add(l)}}}checkImage(e,t){if(t.type===ht.setSrc){let i=t.contentNode.getContent()[0];w.isImageURL(i)&&w.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},ne=class o extends Error{static describeAction(e,t){return`
|
|
85
85
|
Action: (id: ${e.id}) ${e.type}`+(t?`
|
|
86
86
|
At: ${t}`:"")}static getActionTrace(e){return o.describeAction({id:e.getId(),type:String(e.type)},e.__stack)}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("")}constructor(e,t){super(Array.isArray(e)?e.join(""):e),this.name="RuntimeScriptError";let n=t===void 0?[]:Array.isArray(t)?t:[t],i=n[0];if(i&&(this.action={id:i.getId(),type:String(i.type)},this.actionStack=i.__stack),this.traceTail=n.map(o.getActionTrace).join(""),this.traceTail&&typeof this.stack=="string"){let r=this.stack.indexOf(this.message);this.stack=r===-1?`${this.name}: ${this.composedMessage}
|
|
87
|
-
${this.stack}`:this.stack.slice(0,r)+this.composedMessage+this.stack.slice(r+this.message.length)}}get composedMessage(){return this.message+this.traceTail}},P=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},ke=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function of(o,e){return se.color(o,e)}function rf(o){return se.bold(o)}function sf(o){return se.italic(o)}var ea=class o extends we{constructor(e){super(),this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(e=>({style:{opacity:1-e}})),this.asTarget(e=>({style:{opacity:e}}))]}}copy(){return new o({duration:this.duration,easing:this.easing})}};var ta=class o extends we{constructor(e){super(),this.duration=e.duration,this.offset=e.offset??[0,0],this.easing=e.easing}createTask(e){let{invertX:t,invertY:n}=e.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.offset[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.offset[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((i,r,s)=>({style:{opacity:i,translate:`${t?-r:r}px ${n?-s:s}px`}}))]}}copy(){return new o({duration:this.duration,offset:this.offset,easing:this.easing})}};var na=class o extends we{constructor(e){super(),this.duration=e.duration,this.blur=e.blur??16,this.easing=e.easing}createTask(){let e=Math.max(0,this.blur);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-_(t),filter:`blur(${e*_(t)}px)`}})),this.asTarget(t=>({style:{opacity:_(t),filter:`blur(${e*(1-_(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var ia=class o extends we{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*_(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-_(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var oa=class o extends we{constructor(e){super(),this.duration=e.duration,this.ev=e.ev??4.6,this.lift=e.lift??.04,this.hold=e.hold,this.holdMs=e.holdMs,this.easing=e.easing}burnStyle(e){let t=_(e);if(t<=0)return{filter:"none"};let n=_(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=hr({duration:this.duration,hold:this.hold,holdMs:this.holdMs,easing:this.easing});return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asPrev(n=>({style:{opacity:n<.5?1:0,...this.burnStyle(t(n))}})),this.asTarget(n=>({style:{opacity:n<.5?0:1,...this.burnStyle(t(n))}}))]}}copy(){return new o({duration:this.duration,ev:this.ev,lift:this.lift,hold:this.hold,holdMs:this.holdMs,easing:this.easing})}};function R(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function Mn(o,e,t){return o<e?e:o>t?t:o}var ln=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${R(t)}deg`:ru(t);return{mask:(r,s)=>{let a=-n+(s?1-_(r):_(r))*(100+n);return s?`linear-gradient(${i}, transparent ${R(a)}%, #000 ${R(a+n)}%)`:`linear-gradient(${i}, #000 ${R(a)}%, transparent ${R(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${R(t)}deg`,`${R(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let l=-n+_(s)*(50+n);if(!a){let c=u=>`linear-gradient(${u}, #000 ${R(l)}%, transparent ${R(l+n)}%)`;return`${c(i)}, ${c(r)}`}if(l<0){let c=_((l+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${R(50-l-n)}%, rgba(0,0,0,${R(c)}) 50%, transparent ${R(50+l+n)}%)`}return`linear-gradient(${i}, transparent ${R(50-l-n)}%, #000 ${R(50-l)}%, #000 ${R(50+l)}%, transparent ${R(50+l+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 l=(1-_(r))*150;return`radial-gradient(${i} at ${t}, transparent ${R(l-n)}%, #000 ${R(l)}%)`}let a=_(r)*150;return`radial-gradient(${i} at ${t}, #000 ${R(a-n)}%, transparent ${R(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 l=r==="counterclockwise"!=!!a,c=-i+_(s)*(360+i);if(l){let p=Math.max(0,360-c-i),d=Math.max(p,360-c);return`conic-gradient(from ${R(n)}deg at ${t}, transparent ${R(p)}deg, #000 ${R(d)}deg)`}let u=Math.max(0,c);return`conic-gradient(from ${R(n)}deg at ${t}, #000 ${R(u)}deg, transparent ${R(Math.max(u,c+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,l)=>{let c=-r+(l?1-_(a):_(a))*(s+r),u=Mn(c,0,s),p=Mn(c+r,0,s),d=`repeating-conic-gradient(from ${R(i)}deg at ${n}`;return l?`${d}, transparent 0deg, transparent ${R(u)}deg, #000 ${R(p)}deg, #000 ${R(s)}deg)`:`${d}, #000 0deg, #000 ${R(u)}deg, transparent ${R(p)}deg, transparent ${R(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,Math.round(e.slats??8)),i=Math.max(0,e.feather??0),r=Mn(e.stagger??0,-1,1),s=typeof t=="number"?`${R(t)}deg`:su(t),a=100/n,l=Math.abs(r)/n,c=1-l*(n-1),u=(d,f)=>l*(r>=0!==f?d:n-1-d),p=(d,f,h)=>{let m=-i+(h?1-f:f)*(a+i),g=Mn(m,0,a),b=Mn(m+i,0,a),y=d*a;return h?`linear-gradient(${s}, transparent ${R(y+g)}%, #000 ${R(y+b)}%, #000 ${R(y+a)}%, transparent ${R(y+a)}%)`:`linear-gradient(${s}, transparent ${R(y)}%, #000 ${R(y)}%, #000 ${R(y+g)}%, transparent ${R(y+b)}%)`};return{mask:(d,f)=>{if(r!==0){let b=[];for(let y=0;y<n;y++)b.push(p(y,_((_(d)-u(y,!!f))/c),!!f));return b.join(", ")}let h=-i+(f?1-_(d):_(d))*(a+i),m=Mn(h,0,a),g=Mn(h+i,0,a);return f?`repeating-linear-gradient(${s}, transparent 0, transparent ${R(m)}%, #000 ${R(g)}%, #000 ${R(a)}%)`:`repeating-linear-gradient(${s}, #000 0, #000 ${R(m)}%, transparent ${R(g)}%, transparent ${R(a)}%)`}}}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=_(e.stagger??0)*.5,a=(l,c,u)=>{let p=-i+_(c)*(100+i);return u?`radial-gradient(circle farthest-corner at ${l}, transparent ${R(p)}%, #000 ${R(p+i)}%)`:`radial-gradient(circle farthest-corner at ${l}, #000 ${R(p)}%, transparent ${R(p+i)}%)`};return{size:`${R(100/n)}% ${R(100/t)}%`,repeat:"repeat",mask:(l,c)=>{let u=c?1-_(l):_(l);if(s<=0)return a("50% 50%",u,c);let p=_(u/(1-s)),d=_((u-s)/(1-s));return c?`${a("50% 50%",d,!0)}, ${a("0% 0%",p,!0)}`:`${a("50% 50%",p)}, ${a("0% 0%",d)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return ou(e.mask(t,n),e.size,e.repeat)}};var af=.3,ra=class o extends we{constructor(e){super(),this.duration=e.duration,this.color=e.color??"#000000",this.hold=e.hold,this.holdMs=e.holdMs,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{...Ys(this.color),opacity:_(e)};let n={...Ys(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...ln.toStyle(this.pattern,e,!this.inverted)}:{...n,...ln.toStyle(this.uncover,e)}:{...n,...ln.toStyle(this.pattern,e,this.inverted)}}createTask(){let e={duration:this.duration,hold:this.hold??(this.holdMs===void 0?af:void 0),holdMs:this.holdMs,easing:this.easing},t=1-(1-Fi(e))/2,n=.5,i=hr(e);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asPrev(r=>({style:{opacity:r<n?1:0}})),this.asTarget(r=>({style:{opacity:r<n?0:1}})),r=>({src:O.DefaultImagePlaceholder,style:this.coverStyle(i(r),r>=t)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,holdMs:this.holdMs,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var sa=class o extends we{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:ln.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var ti="http://www.w3.org/2000/svg",lf="http://www.w3.org/1999/xlink",cf=.002,uf=1,pf=.12,df=0,aa=class o extends we{constructor(t){super();this.filterId=null;this.host=null;this.cut=null;this.duration=t.duration,this.rule=k.srcToURL(t.rule),this.feather=Math.min(uf,Math.max(cf,t.feather??pf)),this.inverted=t.inverted??!1,this.easing=t.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(t=>({style:this.styleAt(t)}))]}}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>this.dispose()),n.onCanceled(()=>this.dispose()),n}copy(){return new o({duration:this.duration,rule:this.rule,feather:this.feather,inverted:this.inverted,easing:this.easing})}styleAt(t){if(t>=1)return this.dispose(),{filter:""};let n=this.ensureScaffold();if(!n)return{filter:""};let i=t*(1+this.feather),r=(this.inverted?1:-1)/this.feather,s=(this.inverted?i-1:i)/this.feather;return this.cut?.setAttribute("k3",String(r)),this.cut?.setAttribute("k4",String(s)),{filter:`url(#${n})`}}ensureScaffold(){if(typeof document>"u")return null;if(this.filterId&&this.host)return this.filterId;let t=`nl-rule-${++df}`,n=document.createElementNS(ti,"svg");n.setAttribute("aria-hidden","true"),n.setAttribute("data-element-type","rule-transition"),n.setAttribute("width","0"),n.setAttribute("height","0"),Object.assign(n.style,{position:"absolute",width:"0",height:"0",overflow:"hidden"});let i=document.createElementNS(ti,"filter");i.setAttribute("id",t),i.setAttribute("color-interpolation-filters","sRGB"),i.setAttribute("primitiveUnits","objectBoundingBox"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("width","100%"),i.setAttribute("height","100%");let r=document.createElementNS(ti,"feImage");r.setAttribute("href",this.rule),r.setAttributeNS(lf,"xlink:href",this.rule),r.setAttribute("preserveAspectRatio","none"),r.setAttribute("x","0"),r.setAttribute("y","0"),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("result","rule");let s=document.createElementNS(ti,"feColorMatrix");s.setAttribute("in","rule"),s.setAttribute("type","luminanceToAlpha"),s.setAttribute("result","lum");let a=document.createElementNS(ti,"feComposite");a.setAttribute("in","lum"),a.setAttribute("in2","lum"),a.setAttribute("operator","arithmetic"),a.setAttribute("k1","0"),a.setAttribute("k2","0"),a.setAttribute("k3","0"),a.setAttribute("k4","0"),a.setAttribute("result","cut");let l=document.createElementNS(ti,"feComposite");return l.setAttribute("in","SourceGraphic"),l.setAttribute("in2","cut"),l.setAttribute("operator","in"),i.append(r,s,a,l),n.appendChild(i),document.body.appendChild(n),this.filterId=t,this.host=n,this.cut=a,t}dispose(){this.host?.remove(),this.host=null,this.cut=null,this.filterId=null}};var la=class extends yi{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new J(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var gr=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=Ke.isChained(e)?e.getActions():e;return Ve.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return O.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 Rt.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?Rt.normalizeState(n):Rt.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(L.EventTypes["event:state.dialog.change"],t),e.events.on(L.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};gr.DynamicPersistent=zn;if(typeof document<"u"){let o=document.createElement("style");o.setAttribute("data-narraleaf-react",""),o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */@layer narraleaf-react{@layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*:where(.__narraleaf_content-player,.__narraleaf_content-player *),:where(.__narraleaf_content-player,.__narraleaf_content-player *):before,:where(.__narraleaf_content-player,.__narraleaf_content-player *):after,:where(.__narraleaf_content-player,.__narraleaf_content-player *)::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:where(.__narraleaf_content-player,.__narraleaf_content-player *){visibility:collapse}.invisible:where(.__narraleaf_content-player,.__narraleaf_content-player *){visibility:hidden}.visible:where(.__narraleaf_content-player,.__narraleaf_content-player *){visibility:visible}.absolute:where(.__narraleaf_content-player,.__narraleaf_content-player *){position:absolute}.fixed:where(.__narraleaf_content-player,.__narraleaf_content-player *){position:fixed}.relative:where(.__narraleaf_content-player,.__narraleaf_content-player *){position:relative}.static:where(.__narraleaf_content-player,.__narraleaf_content-player *){position:static}.isolate:where(.__narraleaf_content-player,.__narraleaf_content-player *){isolation:isolate}.z-20:where(.__narraleaf_content-player,.__narraleaf_content-player *){z-index:20}.container:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:100%}.\\!hidden:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:none!important}.block:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:block}.contents:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:contents}.flex:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:flex}.grid:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:grid}.hidden:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:none}.inline:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:inline}.inline-block:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:inline-block}.table:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:table}.h-\\[80px\\]:where(.__narraleaf_content-player,.__narraleaf_content-player *){height:80px}.h-full:where(.__narraleaf_content-player,.__narraleaf_content-player *){height:100%}.h-max:where(.__narraleaf_content-player,.__narraleaf_content-player *){height:-moz-max-content;height:max-content}.w-1\\/2:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:50%}.w-\\[100px\\]:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:100px}.w-full:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:100%}.w-max:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:-moz-max-content;width:max-content}.min-w-full:where(.__narraleaf_content-player,.__narraleaf_content-player *){min-width:100%}.flex-grow:where(.__narraleaf_content-player,.__narraleaf_content-player *),.grow:where(.__narraleaf_content-player,.__narraleaf_content-player *){flex-grow:1}.transform:where(.__narraleaf_content-player,.__narraleaf_content-player *){transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.resize:where(.__narraleaf_content-player,.__narraleaf_content-player *){resize:both}.flex-col:where(.__narraleaf_content-player,.__narraleaf_content-player *){flex-direction:column}.items-center:where(.__narraleaf_content-player,.__narraleaf_content-player *){align-items:center}.justify-center:where(.__narraleaf_content-player,.__narraleaf_content-player *){justify-content:center}.overflow-auto:where(.__narraleaf_content-player,.__narraleaf_content-player *){overflow:auto}.overflow-hidden:where(.__narraleaf_content-player,.__narraleaf_content-player *){overflow:hidden}.border:where(.__narraleaf_content-player,.__narraleaf_content-player *){border-style:var(--tw-border-style);border-width:1px}.border-2:where(.__narraleaf_content-player,.__narraleaf_content-player *){border-style:var(--tw-border-style);border-width:2px}.mask-repeat:where(.__narraleaf_content-player,.__narraleaf_content-player *){-webkit-mask-repeat:repeat;mask-repeat:repeat}.text-center:where(.__narraleaf_content-player,.__narraleaf_content-player *){text-align:center}.text-left:where(.__narraleaf_content-player,.__narraleaf_content-player *){text-align:left}.align-bottom:where(.__narraleaf_content-player,.__narraleaf_content-player *){vertical-align:bottom}.break-all:where(.__narraleaf_content-player,.__narraleaf_content-player *){word-break:break-all}.whitespace-pre-wrap:where(.__narraleaf_content-player,.__narraleaf_content-player *){white-space:pre-wrap}.italic:where(.__narraleaf_content-player,.__narraleaf_content-player *){font-style:italic}.ordinal:where(.__narraleaf_content-player,.__narraleaf_content-player *){--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:where(.__narraleaf_content-player,.__narraleaf_content-player *){text-decoration-line:underline}.decoration-dotted:where(.__narraleaf_content-player,.__narraleaf_content-player *){text-decoration-style:dotted}.opacity-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){opacity:0}.ring:where(.__narraleaf_content-player,.__narraleaf_content-player *){--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:where(.__narraleaf_content-player,.__narraleaf_content-player *){outline-style:var(--tw-outline-style);outline-width:1px}.grayscale:where(.__narraleaf_content-player,.__narraleaf_content-player *){--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:where(.__narraleaf_content-player,.__narraleaf_content-player *){--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:where(.__narraleaf_content-player,.__narraleaf_content-player *){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:where(.__narraleaf_content-player,.__narraleaf_content-player *){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:where(.__narraleaf_content-player,.__narraleaf_content-player *){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:where(.__narraleaf_content-player,.__narraleaf_content-player *){pointer-events:auto}.pointer-events-none:where(.__narraleaf_content-player,.__narraleaf_content-player *){pointer-events:none}.bottom-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){bottom:0}.left-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){left:0}.right-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){right:0}.top-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){top:0}.bg-cover:where(.__narraleaf_content-player,.__narraleaf_content-player *){background-size:cover}.bg-center:where(.__narraleaf_content-player,.__narraleaf_content-player *){background-position:50%}.pointer-events-auto-rest *:where(.__narraleaf_content-player,.__narraleaf_content-player *){pointer-events:auto}@keyframes __narraleaf_text_reveal{0%{opacity:0}to{opacity:1}}.__narraleaf_text_reveal:where(.__narraleaf_content-player,.__narraleaf_content-player *){animation:__narraleaf_text_reveal var(--nl-reveal-duration,0s) ease-out both}@media (prefers-reduced-motion:reduce){.__narraleaf_text_reveal:where(.__narraleaf_content-player,.__narraleaf_content-player *){animation:none}}}@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
|
|
88
|
-
`,document.head.insertBefore(o,document.head.firstChild)}export{
|
|
87
|
+
${this.stack}`:this.stack.slice(0,r)+this.composedMessage+this.stack.slice(r+this.message.length)}}get composedMessage(){return this.message+this.traceTail}},P=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},ke=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function lf(o,e){return ae.color(o,e)}function cf(o){return ae.bold(o)}function uf(o){return ae.italic(o)}var ta=class o extends we{constructor(e){super(),this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(e=>({style:{opacity:1-e}})),this.asTarget(e=>({style:{opacity:e}}))]}}copy(){return new o({duration:this.duration,easing:this.easing})}};var na=class o extends we{constructor(e){super(),this.duration=e.duration,this.offset=e.offset??[0,0],this.easing=e.easing}createTask(e){let{invertX:t,invertY:n}=e.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.offset[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.offset[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((i,r,s)=>({style:{opacity:i,translate:`${t?-r:r}px ${n?-s:s}px`}}))]}}copy(){return new o({duration:this.duration,offset:this.offset,easing:this.easing})}};var ia=class o extends we{constructor(e){super(),this.duration=e.duration,this.blur=e.blur??16,this.easing=e.easing}createTask(){let e=Math.max(0,this.blur);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-K(t),filter:`blur(${e*K(t)}px)`}})),this.asTarget(t=>({style:{opacity:K(t),filter:`blur(${e*(1-K(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var oa=class o extends we{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*K(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-K(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var ra=class o extends we{constructor(e){super(),this.duration=e.duration,this.ev=e.ev??4.6,this.lift=e.lift??.04,this.hold=e.hold,this.holdMs=e.holdMs,this.easing=e.easing}burnStyle(e){let t=K(e);if(t<=0)return{filter:"none"};let n=K(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=gr({duration:this.duration,hold:this.hold,holdMs:this.holdMs,easing:this.easing});return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asPrev(n=>({style:{opacity:n<.5?1:0,...this.burnStyle(t(n))}})),this.asTarget(n=>({style:{opacity:n<.5?0:1,...this.burnStyle(t(n))}}))]}}copy(){return new o({duration:this.duration,ev:this.ev,lift:this.lift,hold:this.hold,holdMs:this.holdMs,easing:this.easing})}};function M(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function Mn(o,e,t){return o<e?e:o>t?t:o}var ln=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${M(t)}deg`:du(t);return{mask:(r,s)=>{let a=-n+(s?1-K(r):K(r))*(100+n);return s?`linear-gradient(${i}, transparent ${M(a)}%, #000 ${M(a+n)}%)`:`linear-gradient(${i}, #000 ${M(a)}%, transparent ${M(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${M(t)}deg`,`${M(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let l=-n+K(s)*(50+n);if(!a){let c=u=>`linear-gradient(${u}, #000 ${M(l)}%, transparent ${M(l+n)}%)`;return`${c(i)}, ${c(r)}`}if(l<0){let c=K((l+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${M(50-l-n)}%, rgba(0,0,0,${M(c)}) 50%, transparent ${M(50+l+n)}%)`}return`linear-gradient(${i}, transparent ${M(50-l-n)}%, #000 ${M(50-l)}%, #000 ${M(50+l)}%, transparent ${M(50+l+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 l=(1-K(r))*150;return`radial-gradient(${i} at ${t}, transparent ${M(l-n)}%, #000 ${M(l)}%)`}let a=K(r)*150;return`radial-gradient(${i} at ${t}, #000 ${M(a-n)}%, transparent ${M(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 l=r==="counterclockwise"!=!!a,c=-i+K(s)*(360+i);if(l){let p=Math.max(0,360-c-i),d=Math.max(p,360-c);return`conic-gradient(from ${M(n)}deg at ${t}, transparent ${M(p)}deg, #000 ${M(d)}deg)`}let u=Math.max(0,c);return`conic-gradient(from ${M(n)}deg at ${t}, #000 ${M(u)}deg, transparent ${M(Math.max(u,c+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,l)=>{let c=-r+(l?1-K(a):K(a))*(s+r),u=Mn(c,0,s),p=Mn(c+r,0,s),d=`repeating-conic-gradient(from ${M(i)}deg at ${n}`;return l?`${d}, transparent 0deg, transparent ${M(u)}deg, #000 ${M(p)}deg, #000 ${M(s)}deg)`:`${d}, #000 0deg, #000 ${M(u)}deg, transparent ${M(p)}deg, transparent ${M(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,Math.round(e.slats??8)),i=Math.max(0,e.feather??0),r=Mn(e.stagger??0,-1,1),s=typeof t=="number"?`${M(t)}deg`:mu(t),a=100/n,l=Math.abs(r)/n,c=1-l*(n-1),u=(d,f)=>l*(r>=0!==f?d:n-1-d),p=(d,f,h)=>{let m=-i+(h?1-f:f)*(a+i),g=Mn(m,0,a),b=Mn(m+i,0,a),y=d*a;return h?`linear-gradient(${s}, transparent ${M(y+g)}%, #000 ${M(y+b)}%, #000 ${M(y+a)}%, transparent ${M(y+a)}%)`:`linear-gradient(${s}, transparent ${M(y)}%, #000 ${M(y)}%, #000 ${M(y+g)}%, transparent ${M(y+b)}%)`};return{mask:(d,f)=>{if(r!==0){let b=[];for(let y=0;y<n;y++)b.push(p(y,K((K(d)-u(y,!!f))/c),!!f));return b.join(", ")}let h=-i+(f?1-K(d):K(d))*(a+i),m=Mn(h,0,a),g=Mn(h+i,0,a);return f?`repeating-linear-gradient(${s}, transparent 0, transparent ${M(m)}%, #000 ${M(g)}%, #000 ${M(a)}%)`:`repeating-linear-gradient(${s}, #000 0, #000 ${M(m)}%, transparent ${M(g)}%, transparent ${M(a)}%)`}}}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=K(e.stagger??0)*.5,a=(l,c,u)=>{let p=-i+K(c)*(100+i);return u?`radial-gradient(circle farthest-corner at ${l}, transparent ${M(p)}%, #000 ${M(p+i)}%)`:`radial-gradient(circle farthest-corner at ${l}, #000 ${M(p)}%, transparent ${M(p+i)}%)`};return{size:`${M(100/n)}% ${M(100/t)}%`,repeat:"repeat",mask:(l,c)=>{let u=c?1-K(l):K(l);if(s<=0)return a("50% 50%",u,c);let p=K(u/(1-s)),d=K((u-s)/(1-s));return c?`${a("50% 50%",d,!0)}, ${a("0% 0%",p,!0)}`:`${a("50% 50%",p)}, ${a("0% 0%",d)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return pu(e.mask(t,n),e.size,e.repeat)}};var pf=.3,sa=class o extends we{constructor(e){super(),this.duration=e.duration,this.color=e.color??"#000000",this.hold=e.hold,this.holdMs=e.holdMs,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{...Xs(this.color),opacity:K(e)};let n={...Xs(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...ln.toStyle(this.pattern,e,!this.inverted)}:{...n,...ln.toStyle(this.uncover,e)}:{...n,...ln.toStyle(this.pattern,e,this.inverted)}}createTask(){let e={duration:this.duration,hold:this.hold??(this.holdMs===void 0?pf:void 0),holdMs:this.holdMs,easing:this.easing},t=1-(1-Hi(e))/2,n=.5,i=gr(e);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asPrev(r=>({style:{opacity:r<n?1:0}})),this.asTarget(r=>({style:{opacity:r<n?0:1}})),r=>({src:O.DefaultImagePlaceholder,style:this.coverStyle(i(r),r>=t)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,holdMs:this.holdMs,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var aa=class o extends we{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:ln.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var ni="http://www.w3.org/2000/svg",df="http://www.w3.org/1999/xlink",mf=.002,ff=1,hf=.12,gf=0,la=class o extends we{constructor(t){super();this.filterId=null;this.host=null;this.cut=null;this.duration=t.duration,this.rule=w.srcToURL(t.rule),this.feather=Math.min(ff,Math.max(mf,t.feather??hf)),this.inverted=t.inverted??!1,this.easing=t.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(t=>({style:this.styleAt(t)}))]}}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>this.dispose()),n.onCanceled(()=>this.dispose()),n}copy(){return new o({duration:this.duration,rule:this.rule,feather:this.feather,inverted:this.inverted,easing:this.easing})}styleAt(t){if(t>=1)return this.dispose(),{filter:""};let n=this.ensureScaffold();if(!n)return{filter:""};let i=t*(1+this.feather),r=(this.inverted?1:-1)/this.feather,s=(this.inverted?i-1:i)/this.feather;return this.cut?.setAttribute("k3",String(r)),this.cut?.setAttribute("k4",String(s)),{filter:`url(#${n})`}}ensureScaffold(){if(typeof document>"u")return null;if(this.filterId&&this.host)return this.filterId;let t=`nl-rule-${++gf}`,n=document.createElementNS(ni,"svg");n.setAttribute("aria-hidden","true"),n.setAttribute("data-element-type","rule-transition"),n.setAttribute("width","0"),n.setAttribute("height","0"),Object.assign(n.style,{position:"absolute",width:"0",height:"0",overflow:"hidden"});let i=document.createElementNS(ni,"filter");i.setAttribute("id",t),i.setAttribute("color-interpolation-filters","sRGB"),i.setAttribute("primitiveUnits","objectBoundingBox"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("width","100%"),i.setAttribute("height","100%");let r=document.createElementNS(ni,"feImage");r.setAttribute("href",this.rule),r.setAttributeNS(df,"xlink:href",this.rule),r.setAttribute("preserveAspectRatio","none"),r.setAttribute("x","0"),r.setAttribute("y","0"),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("result","rule");let s=document.createElementNS(ni,"feColorMatrix");s.setAttribute("in","rule"),s.setAttribute("type","luminanceToAlpha"),s.setAttribute("result","lum");let a=document.createElementNS(ni,"feComposite");a.setAttribute("in","lum"),a.setAttribute("in2","lum"),a.setAttribute("operator","arithmetic"),a.setAttribute("k1","0"),a.setAttribute("k2","0"),a.setAttribute("k3","0"),a.setAttribute("k4","0"),a.setAttribute("result","cut");let l=document.createElementNS(ni,"feComposite");return l.setAttribute("in","SourceGraphic"),l.setAttribute("in2","cut"),l.setAttribute("operator","in"),i.append(r,s,a,l),n.appendChild(i),document.body.appendChild(n),this.filterId=t,this.host=n,this.cut=a,t}dispose(){this.host?.remove(),this.host=null,this.cut=null,this.filterId=null}};var ca=class extends Si{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new Z(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var yr=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=Ke.isChained(e)?e.getActions():e;return Fe.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return O.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 Rt.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?Rt.normalizeState(n):Rt.mergeState(t.state,n),t._applyState().catch(r=>{e.logger.error("DevTools","Puppet backend threw while applying state",r)}),e.flush()}static async runPuppetCommand(e,t,n,i){try{await t._runCommand(n,i)||e.logger.weakWarn("DevTools",`Puppet command "${n}" was dropped: the puppet is not mounted.`)}catch(r){e.logger.error("DevTools",`Puppet backend threw while running "${n}"`,r)}}static listPuppetBackends(e){return e.listPuppetBackends()}static getCurrentDialog(e){if(e.isNvlMode()){let n=e.getNvlState();if(!n.activeDialogId||n.phase==="idle")return null;let i=e.getNvlDialog(n.activeDialogId);return i?{actionId:i.actionId||null,ended:n.phase==="awaitAdvance",mode:"nvl"}:null}let t=e.getAdvDialogState();return t?{actionId:t.actionId,ended:t.ended,mode:"adv"}:null}static onDialogStateChange(e,t){let n=[e.events.on(I.EventTypes["event:state.dialog.change"],t),e.events.on(I.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};yr.DynamicPersistent=zn;if(typeof document<"u"){let o=document.createElement("style");o.setAttribute("data-narraleaf-react",""),o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */@layer narraleaf-react{@layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*:where(.__narraleaf_content-player,.__narraleaf_content-player *),:where(.__narraleaf_content-player,.__narraleaf_content-player *):before,:where(.__narraleaf_content-player,.__narraleaf_content-player *):after,:where(.__narraleaf_content-player,.__narraleaf_content-player *)::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:where(.__narraleaf_content-player,.__narraleaf_content-player *){visibility:collapse}.invisible:where(.__narraleaf_content-player,.__narraleaf_content-player *){visibility:hidden}.visible:where(.__narraleaf_content-player,.__narraleaf_content-player *){visibility:visible}.absolute:where(.__narraleaf_content-player,.__narraleaf_content-player *){position:absolute}.fixed:where(.__narraleaf_content-player,.__narraleaf_content-player *){position:fixed}.relative:where(.__narraleaf_content-player,.__narraleaf_content-player *){position:relative}.static:where(.__narraleaf_content-player,.__narraleaf_content-player *){position:static}.isolate:where(.__narraleaf_content-player,.__narraleaf_content-player *){isolation:isolate}.z-20:where(.__narraleaf_content-player,.__narraleaf_content-player *){z-index:20}.container:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:100%}.\\!hidden:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:none!important}.block:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:block}.contents:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:contents}.flex:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:flex}.grid:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:grid}.hidden:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:none}.inline:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:inline}.inline-block:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:inline-block}.table:where(.__narraleaf_content-player,.__narraleaf_content-player *){display:table}.h-\\[80px\\]:where(.__narraleaf_content-player,.__narraleaf_content-player *){height:80px}.h-full:where(.__narraleaf_content-player,.__narraleaf_content-player *){height:100%}.h-max:where(.__narraleaf_content-player,.__narraleaf_content-player *){height:-moz-max-content;height:max-content}.w-1\\/2:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:50%}.w-\\[100px\\]:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:100px}.w-full:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:100%}.w-max:where(.__narraleaf_content-player,.__narraleaf_content-player *){width:-moz-max-content;width:max-content}.min-w-full:where(.__narraleaf_content-player,.__narraleaf_content-player *){min-width:100%}.flex-grow:where(.__narraleaf_content-player,.__narraleaf_content-player *),.grow:where(.__narraleaf_content-player,.__narraleaf_content-player *){flex-grow:1}.transform:where(.__narraleaf_content-player,.__narraleaf_content-player *){transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.resize:where(.__narraleaf_content-player,.__narraleaf_content-player *){resize:both}.flex-col:where(.__narraleaf_content-player,.__narraleaf_content-player *){flex-direction:column}.items-center:where(.__narraleaf_content-player,.__narraleaf_content-player *){align-items:center}.justify-center:where(.__narraleaf_content-player,.__narraleaf_content-player *){justify-content:center}.overflow-auto:where(.__narraleaf_content-player,.__narraleaf_content-player *){overflow:auto}.overflow-hidden:where(.__narraleaf_content-player,.__narraleaf_content-player *){overflow:hidden}.border:where(.__narraleaf_content-player,.__narraleaf_content-player *){border-style:var(--tw-border-style);border-width:1px}.border-2:where(.__narraleaf_content-player,.__narraleaf_content-player *){border-style:var(--tw-border-style);border-width:2px}.mask-repeat:where(.__narraleaf_content-player,.__narraleaf_content-player *){-webkit-mask-repeat:repeat;mask-repeat:repeat}.text-center:where(.__narraleaf_content-player,.__narraleaf_content-player *){text-align:center}.text-left:where(.__narraleaf_content-player,.__narraleaf_content-player *){text-align:left}.align-bottom:where(.__narraleaf_content-player,.__narraleaf_content-player *){vertical-align:bottom}.break-all:where(.__narraleaf_content-player,.__narraleaf_content-player *){word-break:break-all}.whitespace-pre-wrap:where(.__narraleaf_content-player,.__narraleaf_content-player *){white-space:pre-wrap}.italic:where(.__narraleaf_content-player,.__narraleaf_content-player *){font-style:italic}.ordinal:where(.__narraleaf_content-player,.__narraleaf_content-player *){--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:where(.__narraleaf_content-player,.__narraleaf_content-player *){text-decoration-line:underline}.decoration-dotted:where(.__narraleaf_content-player,.__narraleaf_content-player *){text-decoration-style:dotted}.opacity-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){opacity:0}.ring:where(.__narraleaf_content-player,.__narraleaf_content-player *){--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:where(.__narraleaf_content-player,.__narraleaf_content-player *){outline-style:var(--tw-outline-style);outline-width:1px}.grayscale:where(.__narraleaf_content-player,.__narraleaf_content-player *){--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:where(.__narraleaf_content-player,.__narraleaf_content-player *){--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:where(.__narraleaf_content-player,.__narraleaf_content-player *){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:where(.__narraleaf_content-player,.__narraleaf_content-player *){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:where(.__narraleaf_content-player,.__narraleaf_content-player *){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:where(.__narraleaf_content-player,.__narraleaf_content-player *){pointer-events:auto}.pointer-events-none:where(.__narraleaf_content-player,.__narraleaf_content-player *){pointer-events:none}.bottom-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){bottom:0}.left-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){left:0}.right-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){right:0}.top-0:where(.__narraleaf_content-player,.__narraleaf_content-player *){top:0}.bg-cover:where(.__narraleaf_content-player,.__narraleaf_content-player *){background-size:cover}.bg-center:where(.__narraleaf_content-player,.__narraleaf_content-player *){background-position:50%}.pointer-events-auto-rest *:where(.__narraleaf_content-player,.__narraleaf_content-player *){pointer-events:auto}@keyframes __narraleaf_text_reveal{0%{opacity:0}to{opacity:1}}.__narraleaf_text_reveal:where(.__narraleaf_content-player,.__narraleaf_content-player *){animation:__narraleaf_text_reveal var(--nl-reveal-duration,0s) ease-out both}@media (prefers-reduced-motion:reduce){.__narraleaf_text_reveal:where(.__narraleaf_content-player,.__narraleaf_content-player *){animation:none}}}@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
|
|
88
|
+
`,document.head.insertBefore(o,document.head.firstChild)}export{xn as Align,pn as AudioBusError,di as AudioBusMixer,pi as AudioBusTree,ds as Avatar,ia as BlurDissolve,gi as Camera,So as Character,ut as CommonPosition,Fn as CommonPositionType,Rr as Condition,Fe as Control,yt as Coord2D,Ui as Darkness,ot as DefaultAudioBusIds,xs as DefaultNvlContainer,pc as DefaultNvlDialogItem,yr as DevTools,Vd as Dialog,ta as Dissolve,Wm as ExposedStateType,ra as Exposure,na as FadeIn,sc as FixedAspectRatioContainer,ca as Gallery,Y as Game,Ro as GameMenu,iu as GameProviders,I as GameState,O as Image,we as ImageTransition,_t as Isolated,Wo as Item,qn as KeyBindingType,Fi as KeyMap,Z as Lambda,Kn as Layer,rd as Layout,Ii as LayoutRouterProvider,Wt as LiveGame,ln as Mask,so as MaxAudioBusDepth,Ir as Menu,Ti as NVLToken,Ut as Namespace,sn as Nametag,nn as Narrator,_o as Notifications,As as NvlContainer,Ld as NvlDialogList,bs as NvlProvider,ud as Page,hs as PageInjectContext,$e as Pause,Wn as Persistent,nu as Player,xi as Preference,Rt as Puppet,oa as Push,aa as Reveal,cl as RootPath,la as RuleReveal,Je as Scene,Ee as Script,Na as SeededBusPreferenceKeys,ve as Sentence,Si as Service,Se as Sound,Oa as SoundType,ju as Stage,ci as Storable,yi as Story,Pn as Text,pt as TextEvent,vi as TextTransition,Lp as Texts,Pp as TextsPreview,sa as ThroughColor,ie as Transform,Bt as Transition,Vr as Vfx,Or as Video,ae as Word,ao as acceptsAudioBus,cf as b,lf as c,ks as createDefaultPreloadStrategy,Dr as getActiveAudioBusTree,mp as getWordRenderer,uf as i,pp as registerWordRenderer,dp as unregisterWordRenderer,Jl as useAvatar,Kp as useDialog,Nd as useDialogOverlay,G as useGame,Cd as useIsNvlMode,wd as useIsNvlVisible,Dn as useKeyBinding,vd as useLiveGame,jt as useNvl,Ss as useNvlDialogs,Zp as useParams,Jp as usePathname,vn as usePreference,ed as useQueryParams,zt as useRouter,Od as useSuspendAdvance,cs as useUIMenuContext,qp as useVoiceState};
|