narraleaf-react 0.47.2 → 1.0.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.
@@ -10,7 +10,7 @@ export declare namespace TransformDefinitions {
10
10
  delay: number;
11
11
  at: TransformDefinitions.SequenceAtDefinition;
12
12
  } & {
13
- /**@deprecated */
13
+ /**@deprecated Has no effect: nothing reads it. */
14
14
  sync?: boolean;
15
15
  };
16
16
  /**
@@ -24,5 +24,10 @@ export type SoundPlayOptions = FadeOptions & {
24
24
  waitForEnd?: boolean;
25
25
  };
26
26
  export type ChainedActions = (Proxied<LogicAction.GameElement, Chained<LogicAction.Actions>> | LogicAction.Actions)[];
27
- export type ActionStatements = ChainedActions | string[];
27
+ /**
28
+ * What a scene, a menu choice, a condition branch or a control block runs. Each entry is read on
29
+ * its own: an action or chained element runs as itself, and a plain string is a line of narration,
30
+ * so the two can sit side by side in one list.
31
+ */
32
+ export type ActionStatements = (ChainedActions[number] | string)[];
28
33
  export type { TransitionAnimationType, TransitionTask, };
@@ -468,10 +468,10 @@ export declare class GameState {
468
468
  getStorable(): Storable;
469
469
  getSceneByName(name: string): Scene | null;
470
470
  getStory(): Story;
471
- setInterval(callback: () => void, delay: number): NodeJS.Timeout;
472
- clearInterval(interval: NodeJS.Timeout): void;
473
- setTimeout(callback: () => void, delay: number): NodeJS.Timeout;
474
- clearTimeout(timeout: NodeJS.Timeout): void;
471
+ setInterval(callback: () => void, delay: number): ReturnType<typeof setInterval>;
472
+ clearInterval(interval: ReturnType<typeof setInterval>): void;
473
+ setTimeout(callback: () => void, delay: number): ReturnType<typeof setTimeout>;
474
+ clearTimeout(timeout: ReturnType<typeof setTimeout>): void;
475
475
  forceAnimation(): Awaitable;
476
476
  /**
477
477
  * Mounts a new state to the game state manager
package/dist/main.js CHANGED
@@ -12,7 +12,7 @@ A returnable jump suspends the scene it is taken from, and a scene has one place
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
14
  reference, or store an id in place of the object.`);if(Array.isArray(o)||xa(o)){n.add(o);try{if(Array.isArray(o))return o.map((l,c)=>Sr(l,[...e,c],t+1,n,i,r,s));let a={};return Object.entries(o).forEach(([l,c])=>{a[l]=Sr(c,[...e,l],t+1,n,i,r,s)}),a}finally{n.delete(o)}}}return console.warn(`Value of type "${iu(o)}" cannot be saved and was stored as null
15
- at ${s}, ${vr(e)}`),null}function iu(o){return typeof o!="object"||o===null?typeof o:o.constructor?.name??"object"}function ka(o,e,t){let n=Ca(o,e,br);return n=Ca(n,t,()=>{}),n}function Ca(o,e,t){if(!Array.isArray(e)||!e.length)return o;let n=o;for(let i of e){if(!Array.isArray(i))continue;if(!i.length){n=t(n);continue}let r=n;for(let a=0;a<i.length-1&&r!==null&&typeof r=="object";a++)r=r[i[a]];if(r===null||typeof r!="object")continue;let s=i[i.length-1];r[s]=t(r[s])}return n}function br(o){return o instanceof Date?o:typeof o=="string"||typeof o=="number"?new Date(o):new Date(NaN)}function Pa(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function Tr(o,e,t=0){if(Object.is(o,e))return!0;if(t>oi)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)=>Tr(n,e[i],t+1));if(Pa(o)&&Pa(e)){let n=Object.keys(o);return n.length===Object.keys(e).length&&n.every(i=>Object.prototype.hasOwnProperty.call(e,i)&&Tr(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=$({},t),this.defaultContent=t}static isSerializable(e){return eo(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
15
+ at ${s}, ${vr(e)}`),null}function iu(o){return typeof o!="object"||o===null?typeof o:o.constructor?.name??"object"}function ka(o,e,t){let n=Ca(o,e,br);return n=Ca(n,t,()=>{}),n}function Ca(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 br(o){return o instanceof Date?o:typeof o=="string"||typeof o=="number"?new Date(o):new Date(NaN)}function Pa(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function Tr(o,e,t=0){if(Object.is(o,e))return!0;if(t>oi)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)=>Tr(n,e[i],t+1));if(Pa(o)&&Pa(e)){let n=Object.keys(o);return n.length===Object.keys(e).length&&n.every(i=>Object.prototype.hasOwnProperty.call(e,i)&&Tr(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=$({},t),this.defaultContent=t}static isSerializable(e){return eo(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
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=$({},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=wa(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=>ka(i.data,i.dates,i.undefineds),date:i=>br(i.data)}[e?.type];return n?n(e):(console.warn(`Unknown stored value type "${e?.type}", reading it as-is
17
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||Tr(t,n)||this.owner.reportChange({namespace:this.key,key:String(e),previous:t,next:n})}},pn=class pn{constructor(){this.events=new X;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 E(`Namespace ${e} is not initialized, did you forget to register it?
18
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 E("No listener provided when subscribing to storable changes");return this.events.on(pn.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(pn.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(pn.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(pn.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(pn.EventTypes["event:storable.restore"],{namespaces:[e]})}};pn.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var ri=pn;var qf={};var Vn=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 et=class extends q{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ht.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ht.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ht.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,l=>{l&&this.callee.fromData(l)},[s]),a}else if(this.type===Ht.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ht.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ht.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ht.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=S.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===Ht.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};et.ActionTypes=Ht;var tt={bgm:"bgm",sound:"sound",voice:"voice"},to=8,dn=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Un(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var ai=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:Un(l.volume)})};Object.values(tt).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 dn(`Audio bus id must be a non-empty string, got ${JSON.stringify(c)}.`);if(i.has(c))throw new dn(`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(tt).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new dn(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new dn(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>to)throw new dn(`Audio bus "${t.id}" nests deeper than ${to}: ${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<=to;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},Ar=ai.resolve();function ou(o){Ar=o}function Cr(){return Ar}function no(o,e){let t=Ar;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var Ea={[tt.bgm]:"bgmVolume",[tt.sound]:"soundVolume",[tt.voice]:"voiceVolume"};function Da(o){let e={};return Object.entries(Ea).forEach(([t,n])=>{e[t]={get:()=>Un(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var si=class si{constructor(e,t={}){this.declarations=e;this.events=new X;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,Un(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(si.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=ai.resolve(this.declarations()??[]),ou(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Un(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?Un(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Un(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(si.EventTypes["event:audioBus.volumeChange"],e)}};si.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var li=si;var La=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(La||{}),xe=class xe extends ue{static toSound(e){return e==null?null:typeof e=="string"?new xe({src:e}):e}static isSound(e){return e instanceof xe}static voice(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=xe.DefaultUserConfig.create(t),[i]=n.extract(xe.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e,t){return Cr().isUnder(this.config.type,tt.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(et.ActionTypes.play,[{end:this.state.volume,duration:e||0,waitForEnd:t?.waitForEnd===!0}])}stop(e){return this.pushAction(et.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(et.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(et.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(et.ActionTypes.setRate,[e])}pause(e){return this.pushAction(et.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(et.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(et.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:xe.StateSerializer.serialize(this.state)}}fromData(e){return this.state=xe.StateSerializer.deserialize(e.state),this}copy(){return new xe(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return xe.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new et(this.chain(),e,new C().setContent(t)))}};xe.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",xe.DefaultUserConfig=new z({src:xe.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultConfig=new z({src:xe.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultState=new z({volume:1,rate:1,paused:!1,muted:!1}),xe.StateSerializer=new je;var ge=xe;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(ne,B.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(P.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof Se){let n=t;if(t.is(Se,mt.setSrc)){let i=t.contentNode.getContent()[0];if(P.isImageSrc(i))return{type:"image",src:P.srcToURL(i),activeType:"scene"}}else{if(t.type===mt.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===mt.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 ge){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof O||P.isStaticImageData(e)){if(e instanceof O){if(!P.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(O.getSrcURL(e)))return this}else if(this.isSrcRegistered(P.srcToURL(e.src)))return this;this.src.push({type:"image",src:P.isStaticImageData(e)?P.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 ge?t:new ge({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 ge?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 Re=Cn;import*as ja from"howler";var ze=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 lt=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 Ra(o,e){let{render:t,data:n,...i}=e,r=$(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 be=class be{static isWord(e){return e instanceof be}static color(e,t){return be.isWord(e)?e.copy().assign({color:t}):new be(e,{color:t})}static bold(e){return be.isWord(e)?e.copy().assign({bold:!0}):new be(e,{bold:!0})}static italic(e){return be.isWord(e)?e.copy().assign({italic:!0}):new be(e,{italic:!0})}static emphasis(e,t={}){return be.isWord(e)?e.copy().assign({emphasis:t}):new be(e,{emphasis:t})}static custom(e,t,n={}){let i={...n,render:t};return be.isWord(e)?e.copy().assign(i):new be(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=Ra(be.defaultConfig,t)}evaluate(e){if(ze.isPause(this.text))return[this];if(lt.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>be.isWord(n)?n.inherit(this.config).evaluate(e):new be(n,this.config)).flat():be.isWord(t)?t.inherit(this.config).evaluate(e):[new be(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=Ra(this.config,e),this}copy(){return new be(this.text,this.config)}isPause(){return ze.isPause(this.text)}isTextEvent(){return lt.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};be.defaultConfig={},be.defaultColor="#000";var oe=be;var ct=class ct{static isSentence(e){return e instanceof ct}static toSentence(e){return ct.isSentence(e)?e:new ct(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 oe.isWord(e)?e:new oe(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[oe.isWord(e)?e:new oe(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(ct.isSingleWord):ct.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||oe.isWord(e)||ze.isPause(e)||lt.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=ct.format(e),this.config=$(ct.defaultConfig,{...t,voice:typeof t.voice=="string"?ge.voice(t.voice):ge.toSound(t.voice)}),this.state=ca(ct.defaultState)}toData(){return null}fromData(e){return this.state=$(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(...ct.formatStaticWord(i))}return t}copy(){return new ct([...this.text],this.config)}};ct.defaultConfig={voice:null,character:null,voiceId:null},ct.defaultState={};var fe=ct;var io=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 mn=class extends q{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")}};mn.ActionTypes=sa;var we=class o extends ue{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new mn(t,mn.ActionTypes.action,new C().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new mn(this.chain(),mn.ActionTypes.action,new C().setContent(e))]}};var ru={volume:1,limit:1/0},su=class Ma{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={...ru,...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 Ma(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}}},Na=!1;function au(o){Na=o}function tn(o,e){Na||(e!==void 0?console.warn(o,e):console.warn(o))}var lu=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){tn("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){tn("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){tn("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=>{tn("Failed to start HTMLAudioElement playback.",n)})}}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},Ia=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 lu(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){tn("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){tn("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 Ia(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new Ia(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}},uu=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))}},pu=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 uu(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}}},du=10*1024*1024,mu={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1,cacheReleaseDelay:0},Ga=class xr{constructor(e){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...mu,...e},au(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new pu(this.audioContext,this.options.cacheReleaseDelay),this.masterChannel=new su("__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=>{tn("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 h=u&&a!==void 0&&a>s?{start:xr.clampLoopStart(l,s,a),end:a}:null;p instanceof AudioBufferSourceNode?(p.loop=u,h&&(p.loopStart=h.start,p.loopEnd=h.end)):p instanceof HTMLAudioElement&&(p.loop=u);let f=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?.())};f.once("ended",g),f.once("stop",g)}return f}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=xr.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<du?"full":"stream"}catch(i){return tn("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=>{tn("Failed to close AudioContext during destroy().",e)}))}isDestroyed(){return this.destroyed}};var Ie=class Ie{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 Ga({maxChannels:Ie.MaxChannels,cacheReleaseDelay:Ie.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=Ie.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,Ie.BusRampTimeConstant),r.setValueAtTime(s,a+Ie.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${tt.sound}" instead.`)),this.channels.get(tt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=Ie.defaultFade(e)){let n=new S;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=Ie.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 E(`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 S;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 S;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new S;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}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 S;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 S;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 S.resolve(void 0);let n=this.state.get(e),i=Ie.clampToRegion(t,Ie.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),S.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{...Ie.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,S.resolve(void 0)):S.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime(),...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=Ie.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(Ie.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()}};Ie.MaxChannels=1024,Ie.BusRampTimeConstant=.02,Ie.BusRampSettle=Ie.BusRampTimeConstant*5,Ie.CacheGrace=5e3;var oo=Ie;function Fa(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 ro=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 Su from"html-to-image";var ke=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),st(()=>{this.preventAttach()})}static proxy(e){let t=new S,n=new S,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new E("Cannot create an 'any' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new E("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let 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 S,s=()=>{if(i){let a;i.onSkipControllerRegister(l=>{a=l.onAbort(()=>{r.abort()})}),i.then(l=>{a?.cancel(),n=l,i=e(l),i?st(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new V(()=>(i&&i.abort(),t))),i=e(t),i?st(()=>s()):st(()=>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()?st(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 E(`Attaching to this timeline violates the timeline's state.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "narraleaf-react",
3
- "version": "0.47.2",
3
+ "version": "1.0.0",
4
4
  "description": "A React visual novel player framework",
5
5
  "type": "module",
6
6
  "main": "./dist/main.js",
@@ -101,6 +101,14 @@
101
101
  "narraleaf",
102
102
  "nvl"
103
103
  ],
104
+ "homepage": "https://www.narraleaf.com/docs/narraleaf-react",
105
+ "repository": {
106
+ "type": "git",
107
+ "url": "git+https://github.com/NarraLeaf/narraleaf-react.git"
108
+ },
109
+ "bugs": {
110
+ "url": "https://github.com/NarraLeaf/narraleaf-react/issues"
111
+ },
104
112
  "author": "helloyork@icloud.com",
105
113
  "license": "MPL-2.0",
106
114
  "dependencies": {