@drincs/pixi-vn-ink 1.0.6 → 1.0.7

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.
@@ -1,73 +1,71 @@
1
- 'use strict';var v=require('zod'),pixiVn=require('@drincs/pixi-vn'),canvas=require('@drincs/pixi-vn/canvas'),characters=require('@drincs/pixi-vn/characters'),narration=require('@drincs/pixi-vn/narration'),sound=require('@drincs/pixi-vn/sound'),storage=require('@drincs/pixi-vn/storage'),virtual_pixiVnInk=require('virtual:pixi-vn-ink');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var v__default=/*#__PURE__*/_interopDefault(v);var Zc=Object.create;var su=Object.defineProperty;var ed=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var nd=Object.getPrototypeOf,id=Object.prototype.hasOwnProperty;var Wt=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var w=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var rd=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of td(e))!id.call(i,r)&&r!==t&&su(i,r,{get:()=>e[r],enumerable:!(n=ed(e,r))||n.enumerable});return i};var oa=(i,e,t)=>(t=i!=null?Zc(nd(i)):{},rd(su(t,"default",{value:i,enumerable:true}),i));var Va=w(Bi=>{Object.defineProperty(Bi,"__esModule",{value:true});Bi.CompilerOptions=void 0;var Na=class{constructor(e=null,t=[],n=false,r=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=n,this.errorHandler=r,this.fileHandler=a;}};Bi.CompilerOptions=Na;});var eh=w(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.DebugSourceRange=void 0;var Ia=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};Wi.DebugSourceRange=Ia;});var ln=w(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.ErrorType=void 0;var th;(function(i){i[i.Author=0]="Author",i[i.Warning=1]="Warning",i[i.Error=2]="Error";})(th||(ji.ErrorType=th={}));});var nh=w(qi=>{Object.defineProperty(qi,"__esModule",{value:true});qi.Argument=void 0;var ka=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};qi.Argument=ka;});var z=w(he=>{Object.defineProperty(he,"__esModule",{value:true});he.filterUndef=he.isEquatable=he.nullIfUndefined=he.asINamedContentOrNull=he.asBooleanOrThrows=he.asNumberOrThrows=he.asOrThrows=he.asOrNull=void 0;function Vp(i,e){return i instanceof e?ih(i):null}he.asOrNull=Vp;function Ip(i,e){if(i instanceof e)return ih(i);throw new Error(`${i} is not of type ${e}`)}he.asOrThrows=Ip;function kp(i){if(typeof i=="number")return i;throw new Error(`${i} is not a number`)}he.asNumberOrThrows=kp;function Rp(i){if(typeof i=="boolean")return i;throw new Error(`${i} is not a boolean`)}he.asBooleanOrThrows=Rp;function Lp(i){return i.hasValidName&&i.name?i:null}he.asINamedContentOrNull=Lp;function Bp(i){return typeof i>"u"?null:i}he.nullIfUndefined=Bp;function Wp(i){return typeof i=="object"&&typeof i.Equals=="function"}he.isEquatable=Wp;function ih(i,e){return i}function jp(i){return i!=null}he.filterUndef=jp;});var ee=w(Mi=>{Object.defineProperty(Mi,"__esModule",{value:true});Mi.ParsedObject=void 0;var rh=z(),Ra=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let n of t)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let n=(0, rh.asOrNull)(this,e);if(n!==null&&(t===null||t(n)===true))return n;if(this.content===null)return null;for(let r of this.content){let a=r.Find&&r.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,n)=>{let r=Array.isArray(n)?n:[],a=(0, rh.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&r.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,r);return r},this.Warning=(e,t=null)=>{this.Error(e,t,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,n=false){if(t===null&&(t=this),!(t._alreadyHadError&&!n||t._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(e,t,n);else throw new Error(`No parent object to send error to: ${e}`);n?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};Mi.ParsedObject=Ra;});var $i=w(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.AuthorWarning=void 0;var qp=ee(),La=class extends qp.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Gi.AuthorWarning=La;});var ke=w(Wn=>{Object.defineProperty(Wn,"__esModule",{value:true});Wn.Path=void 0;var un=class i{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof i.Component&&arguments[1]instanceof i){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new i(e)}else return i.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new i;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new i,n=0;for(let r=0;r<e._components.length&&e._components[r].isParent;++r)n++;for(let r=0;r<this._components.length-n;++r)t._components.push(this._components[r]);for(let r=n;r<e._components.length;++r)t._components.push(e._components[r]);return t}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let t=this._componentsString.split(".");for(let n of t)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new i.Component(parseInt(n))):this._components.push(new i.Component(n));}toString(){return this.componentsString}Equals(e){if(e==null||e._components.length!=this._components.length||e.isRelative!=this.isRelative)return false;for(let t=0,n=e._components.length;t<n;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new i;return t._components.push(...this._components),t._components.push(e),t}};Wn.Path=un;un.parentId="^";(function(i){class e{constructor(n){this.index=-1,this.name=null,typeof n=="string"?this.name=n:this.index=n;}get isIndex(){return this.index>=0}get isParent(){return this.name==i.parentId}static ToParent(){return new e(i.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}i.Component=e;})(un||(Wn.Path=un={}));});var jn=w(Ji=>{Object.defineProperty(Ji,"__esModule",{value:true});Ji.Debug=void 0;var sh;(function(i){function e(n,r,a){t(n instanceof r,a);}i.AssertType=e;function t(n,r){if(!n)throw typeof r<"u"&&console.warn(r),console.trace&&console.trace(),new Error("")}i.Assert=t;})(sh||(Ji.Debug=sh={}));});var Ce=w(hn=>{Object.defineProperty(hn,"__esModule",{value:true});hn.throwNullException=hn.NullException=void 0;var Hi=class extends Error{};hn.NullException=Hi;function Mp(i){throw new Hi(`${i} is null or undefined`)}hn.throwNullException=Mp;});var Re=w(Ui=>{Object.defineProperty(Ui,"__esModule",{value:true});Ui.InkObject=void 0;var cn=ke(),qn=ae(),Ba=jn(),dn=z(),zi=Ce(),Wa=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let n=t.ContentAtPath(e).obj;if(n){let r=n.debugMetadata;if(r!==null)return r.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new cn.Path;else {let e=[],t=this,n=(0, dn.asOrNull)(t.parent,qn.Container);for(;n!==null;){let r=(0, dn.asINamedContentOrNull)(t);if(r!=null&&r.hasValidName){if(r.name===null)return (0, zi.throwNullException)("namedChild.name");e.unshift(new cn.Path.Component(r.name));}else e.unshift(new cn.Path.Component(n.content.indexOf(t)));t=n,n=(0, dn.asOrNull)(n.parent,qn.Container);}this._path=new cn.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, zi.throwNullException)("path");if(e.isRelative){let t=(0, dn.asOrNull)(this,qn.Container);return t===null&&(Ba.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, dn.asOrNull)(this.parent,qn.Container),Ba.Debug.Assert(t!==null,"Expected parent to be a container"),Ba.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, zi.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, zi.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,n=Math.min(e.length,t.length),r=-1;for(let l=0;l<n;++l){let u=t.GetComponent(l),h=e.GetComponent(l);if(u.Equals(h))r=l;else break}if(r==-1)return e;let a=t.componentCount-1-r,s=[];for(let l=0;l<a;++l)s.push(cn.Path.Component.ToParent());for(let l=r+1;l<e.componentCount;++l)s.push(e.GetComponent(l));return new cn.Path(s,true)}CompactPathString(e){let t=null,n=null;return e.isRelative?(n=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(n=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),n.length<t.length?n:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, dn.asOrNull)(e,qn.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,n){e[t]&&(e[t]=null),e[t]=n,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};Ui.InkObject=Wa;});var Jt=w(Ki=>{Object.defineProperty(Ki,"__esModule",{value:true});Ki.StringBuilder=void 0;var ja=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=`
2
- `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(n,r)=>typeof t[r]<"u"?t[r]:n);}toString(){return this.string}Clear(){this.string="";}};Ki.StringBuilder=ja;});var Be=w(pn=>{Object.defineProperty(pn,"__esModule",{value:true});pn.InkList=pn.InkListItem=void 0;var at=Ce(),Gp=Jt(),Le=class i{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new i(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(e){if(e instanceof i){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new i(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!i.isLikeInkListItem(t))return i.Null;let n=t;return new i(n.originName,n.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};pn.InkListItem=Le;var qa=class i extends Map{constructor(){if(super(arguments[0]instanceof i?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof i){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, at.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, at.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var n;if(e==null||e=="")return new i;let r=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(r)return r.value===null?(0, at.throwNullException)("listValue.value"):new i(r.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof Le){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, at.throwNullException)("this.origins");for(let r of this.origins)if(r.name==n.originName){let a=r.TryGetValueForItem(n,0);if(a.exists){this.Add(n,a.result);return}else throw new Error("Could not add the item "+n+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let n=e,r=null;if(this.origins===null)return (0, at.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, at.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(r!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+r.name);r=a;}}if(r==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=i.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new Le(r.name,n),s=r.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(Le.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let n=e.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${e}`);this.set(n,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(n=>n.name==e?(t=n,false):true),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=Le.fromSerializedKey(e);if(t.originName===null)return (0, at.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:Le.Null,Value:0};for(let[t,n]of this){let r=Le.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:r,Value:n});}return e}get minItem(){let e={Key:Le.Null,Value:0};for(let[t,n]of this){let r=Le.fromSerializedKey(t);(e.Key.isNull||n<e.Value)&&(e={Key:r,Value:n});}return e}get inverse(){let e=new i;if(this.origins!=null)for(let t of this.origins)for(let[n,r]of t.items){let a=Le.fromSerializedKey(n);this.ContainsKey(a)||e.Add(a,r);}return e}get all(){let e=new i;if(this.origins!=null)for(let t of this.origins)for(let[n,r]of t.items){let a=Le.fromSerializedKey(n);e.set(a.serialized(),r);}return e}Union(e){let t=new i(this);for(let[n,r]of e)t.set(n,r);return t}Intersect(e){let t=new i;for(let[n,r]of this)e.has(n)&&t.set(n,r);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new i(this);for(let[n]of e)t.delete(n);return t}Contains(e){if(typeof e=="string")return this.ContainsItemNamed(e);let t=e;if(t.size==0||this.size==0)return false;for(let[n]of t)if(!this.has(n))return false;return true}GreaterThan(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>e.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<e.minItem.Value}LessThanOrEquals(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<=e.maxItem.Value&&this.minItem.Value<=e.minItem.Value}MaxAsList(){return this.Count>0?new i(this.maxItem):new i}MinAsList(){return this.Count>0?new i(this.minItem):new i}ListWithSubRange(e,t){if(this.Count==0)return new i;let n=this.orderedItems,r=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?r=e:e instanceof i&&e.Count>0&&(r=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof i&&t.Count>0&&(a=t.maxItem.Value);let s=new i;s.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=r&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(e){if(!(e instanceof i)||e.Count!=this.Count)return false;for(let[t]of this)if(!e.has(t))return false;return true}get orderedItems(){let e=new Array;for(let[t,n]of this){let r=Le.fromSerializedKey(t);e.push({Key:r,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, at.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, at.throwNullException)("y.Key.originName"):t.Value==n.Value?t.Key.originName.localeCompare(n.Key.originName):t.Value<n.Value?-1:t.Value>n.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new Gp.StringBuilder;for(let n=0;n<e.length;n++){n>0&&t.Append(", ");let r=e[n].Key;if(r.itemName===null)return (0, at.throwNullException)("item.itemName");t.Append(r.itemName);}return t.toString()}valueOf(){return NaN}};pn.InkList=qa;});var Mn=w(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.StoryException=void 0;var Ma=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};Xi.StoryException=Ma;});var fn=w(Pt=>{Object.defineProperty(Pt,"__esModule",{value:true});Pt.tryParseFloat=Pt.tryParseInt=Pt.tryGetValueFromMap=void 0;function $p(i,e,t){if(i===null)return {result:t,exists:false};let n=i.get(e);return typeof n>"u"?{result:t,exists:false}:{result:n,exists:true}}Pt.tryGetValueFromMap=$p;function Jp(i,e=0){let t=parseInt(i);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Pt.tryParseInt=Jp;function Hp(i,e=0){let t=parseFloat(i);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Pt.tryParseFloat=Hp;});var ne=w(ie=>{Object.defineProperty(ie,"__esModule",{value:true});ie.ValueType=ie.ListValue=ie.VariablePointerValue=ie.DivertTargetValue=ie.StringValue=ie.FloatValue=ie.IntValue=ie.BoolValue=ie.Value=ie.AbstractValue=void 0;var ah=Re(),oh=ke(),Ht=Be(),zp=Mn(),Gn=z(),lh=fn(),ze=Ce(),Yi=class i extends ah.InkObject{static Create(e,t){if(t){if(t===Q.Int&&Number.isInteger(Number(e)))return new lt(Number(e));if(t===Q.Float&&!isNaN(e))return new ut(Number(e))}if(typeof e=="boolean")return new gn(!!e);if(typeof e=="string")return new Et(String(e));if(Number.isInteger(Number(e)))return new lt(Number(e));if(isNaN(e)){if(e instanceof oh.Path)return new Qi((0, Gn.asOrThrows)(e,oh.Path));if(e instanceof Ht.InkList)return new Zi((0, Gn.asOrThrows)(e,Ht.InkList))}else return new ut(Number(e));return null}Copy(){return (0, Gn.asOrThrows)(i.Create(this.valueObject),ah.InkObject)}BadCastException(e){return new zp.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};ie.AbstractValue=Yi;var ot=class extends Yi{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, ze.throwNullException)("Value.value"):this.value.toString()}};ie.Value=ot;var gn=class extends ot{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return Q.Bool}Cast(e){if(this.value===null)return (0, ze.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Q.Int)return new lt(this.value?1:0);if(e==Q.Float)return new ut(this.value?1:0);if(e==Q.String)return new Et(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};ie.BoolValue=gn;var lt=class extends ot{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return Q.Int}Cast(e){if(this.value===null)return (0, ze.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Q.Bool)return new gn(this.value!==0);if(e==Q.Float)return new ut(this.value);if(e==Q.String)return new Et(""+this.value);throw this.BadCastException(e)}};ie.IntValue=lt;var ut=class extends ot{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return Q.Float}Cast(e){if(this.value===null)return (0, ze.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Q.Bool)return new gn(this.value!==0);if(e==Q.Int)return new lt(this.value);if(e==Q.String)return new Et(""+this.value);throw this.BadCastException(e)}};ie.FloatValue=ut;var Et=class extends ot{constructor(e){if(super(e||""),this._isNewline=this.value==`
3
- `,this._isInlineWhitespace=true,this.value===null)return (0, ze.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return Q.String}get isTruthy(){return this.value===null?(0, ze.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==Q.Int){let t=(0, lh.tryParseInt)(this.value);if(t.exists)return new lt(t.result);throw this.BadCastException(e)}if(e==Q.Float){let t=(0, lh.tryParseFloat)(this.value);if(t.exists)return new ut(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};ie.StringValue=Et;var Qi=class extends ot{constructor(e=null){super(e);}get valueType(){return Q.DivertTarget}get targetPath(){return this.value===null?(0, ze.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};ie.DivertTargetValue=Qi;var Ga=class i extends ot{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, ze.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return Q.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new i(this.variableName,this.contextIndex)}};ie.VariablePointerValue=Ga;var Zi=class i extends ot{get isTruthy(){return this.value===null?(0, ze.throwNullException)("this.value"):this.value.Count>0}get valueType(){return Q.List}Cast(e){if(this.value===null)return (0, ze.throwNullException)("Value.value");if(e==Q.Int){let t=this.value.maxItem;return t.Key.isNull?new lt(0):new lt(t.Value)}else if(e==Q.Float){let t=this.value.maxItem;return t.Key.isNull?new ut(0):new ut(t.Value)}else if(e==Q.String){let t=this.value.maxItem;return t.Key.isNull?new Et(""):new Et(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new Ht.InkList:e instanceof Ht.InkList?this.value=new Ht.InkList(e):e instanceof Ht.InkListItem&&typeof t=="number"&&(this.value=new Ht.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, Gn.asOrNull)(e,i),r=(0, Gn.asOrNull)(t,i);if(r&&r.value===null)return (0, ze.throwNullException)("newList.value");if(n&&n.value===null)return (0, ze.throwNullException)("oldList.value");n&&r&&r.value.Count==0&&r.value.SetInitialOriginNames(n.value.originNames);}};ie.ListValue=Zi;var Q;(function(i){i[i.Bool=-1]="Bool",i[i.Int=0]="Int",i[i.Float=1]="Float",i[i.List=2]="List",i[i.String=3]="String",i[i.DivertTarget=4]="DivertTarget",i[i.VariablePointer=5]="VariablePointer";})(Q||(ie.ValueType=Q={}));});var uh=w(er=>{Object.defineProperty(er,"__esModule",{value:true});er.SearchResult=void 0;var Up=ae(),$a=class i{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof Up.Container?this.obj:null}copy(){let e=new i;return e.obj=this.obj,e.approximate=this.approximate,e}};er.SearchResult=$a;});var ae=w(Jn=>{Object.defineProperty(Jn,"__esModule",{value:true});Jn.Container=void 0;var Kp=ne(),hh=Ce(),Xp=Jt(),mn=Re(),Yp=uh(),ch=ke(),dh=jn(),Qp=fn(),Tt=z(),$n=class i extends mn.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,n]of this.namedContent){let r=(0, Tt.asOrThrows)(n,mn.InkObject);e.set(t,r);}for(let t of this.content){let n=(0, Tt.asINamedContentOrNull)(t);n!=null&&n.hasValidName&&e.delete(n.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[n]of t)this.namedContent.delete(n);if(e!=null)for(let[,n]of e){let r=(0, Tt.asINamedContentOrNull)(n);r!=null&&this.AddToNamedContentOnly(r);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=i.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=i.CountFlags.Turns),this.countingAtStartOnly&&(e|=i.CountFlags.CountStartOnly),e==i.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&i.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&i.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&i.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof i;)t.content.length>0&&(e.push(new ch.Path.Component(0)),t=t.content[0]);return new ch.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let n of t)this.AddContent(n);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, Tt.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){dh.Debug.AssertType(e,mn.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, Tt.asOrThrows)(e,mn.InkObject);if(t.parent=this,e.name===null)return (0, hh.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let r=new Yp.SearchResult;r.approximate=false;let a=this,s=this;for(let o=t;o<n;++o){let l=e.GetComponent(o);if(a==null){r.approximate=true;break}let u=a.ContentWithPathComponent(l);if(u==null){r.approximate=true;break}let h=(0, Tt.asOrNull)(u,i);if(o<n-1&&h==null){r.approximate=true;break}s=u,a=h;}return r.obj=s,r}InsertContent(e,t){if(this.content.splice(t,0,e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}AddContentsOfContainer(e){this.content.push(...e.content);for(let t of e.content)t.parent=this,this.TryAddNamedContent(t);}ContentWithPathComponent(e){if(e.isIndex)return e.index>=0&&e.index<this.content.length?this.content[e.index]:null;if(e.isParent)return this.parent;{if(e.name===null)return (0, hh.throwNullException)("component.name");let t=(0, Qp.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, Tt.asOrThrows)(t.result,mn.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new Xp.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],n=arguments[2];function r(){for(let o=0;o<4*t;++o)e.Append(" ");}r(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==n&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof i?o.BuildStringOfHierarchy(e,t,n):(r(),o instanceof Kp.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
4
- `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof i)&&o==n&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, Tt.asOrThrows)(o,mn.InkObject))>=0||a.set(s,o);if(a.size>0){r(),e.AppendLine("-- named: --");for(let[,s]of a)dh.Debug.AssertType(s,i,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,r(),e.Append("]");}};Jn.Container=$n;(function(i){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(i.CountFlags||(i.CountFlags={}));})($n||(Jn.Container=$n={}));});var ye=w(zn=>{Object.defineProperty(zn,"__esModule",{value:true});zn.ControlCommand=void 0;var Zp=Re(),Hn=class i extends Zp.InkObject{get commandType(){return this._commandType}constructor(e=i.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new i(this.commandType)}static EvalStart(){return new i(i.CommandType.EvalStart)}static EvalOutput(){return new i(i.CommandType.EvalOutput)}static EvalEnd(){return new i(i.CommandType.EvalEnd)}static Duplicate(){return new i(i.CommandType.Duplicate)}static PopEvaluatedValue(){return new i(i.CommandType.PopEvaluatedValue)}static PopFunction(){return new i(i.CommandType.PopFunction)}static PopTunnel(){return new i(i.CommandType.PopTunnel)}static BeginString(){return new i(i.CommandType.BeginString)}static EndString(){return new i(i.CommandType.EndString)}static NoOp(){return new i(i.CommandType.NoOp)}static ChoiceCount(){return new i(i.CommandType.ChoiceCount)}static Turns(){return new i(i.CommandType.Turns)}static TurnsSince(){return new i(i.CommandType.TurnsSince)}static ReadCount(){return new i(i.CommandType.ReadCount)}static Random(){return new i(i.CommandType.Random)}static SeedRandom(){return new i(i.CommandType.SeedRandom)}static VisitIndex(){return new i(i.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new i(i.CommandType.SequenceShuffleIndex)}static StartThread(){return new i(i.CommandType.StartThread)}static Done(){return new i(i.CommandType.Done)}static End(){return new i(i.CommandType.End)}static ListFromInt(){return new i(i.CommandType.ListFromInt)}static ListRange(){return new i(i.CommandType.ListRange)}static ListRandom(){return new i(i.CommandType.ListRandom)}static BeginTag(){return new i(i.CommandType.BeginTag)}static EndTag(){return new i(i.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};zn.ControlCommand=Hn;(function(i){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(i.CommandType||(i.CommandType={}));})(Hn||(zn.ControlCommand=Hn={}));});var Ue=w(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.Expression=void 0;var ph=ae(),Ja=ye(),ef=ee(),Ha=class extends ef.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new ph.Container;return e.AddContent(Ja.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(Ja.ControlCommand.EvalOutput()),e.AddContent(Ja.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new ph.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let n=t.Copy();n&&e.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};tr.Expression=Ha;});var zt=w(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.Void=void 0;var tf=Re(),za=class extends tf.InkObject{toString(){return "Void"}};nr.Void=za;});var ht=w(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.NativeFunctionCall=void 0;var P=ne(),Un=Mn(),nf=zt(),ir=Be(),rf=Re(),Ke=z(),We=Ce(),B=class i extends rf.InkObject{static CallWithName(e){return new i(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, We.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(i._nativeFunctions===null?(0, We.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=i._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof nf.Void)throw new Un.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');a instanceof P.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),r=n[0].valueType;return r==P.ValueType.Int?this.CallType(n):r==P.ValueType.Float?this.CallType(n):r==P.ValueType.String?this.CallType(n):r==P.ValueType.DivertTarget?this.CallType(n):r==P.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, Ke.asOrThrows)(e[0],P.Value),n=t.valueType,r=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, We.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){let o=P.ValueType[n];throw new Un.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, Ke.asOrThrows)(e[1],P.Value),u=s;if(r.value===null||l.value===null)return (0, We.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(r.value,l.value);return P.Value.Create(h)}else {let o=s;if(r.value===null)return (0, We.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(r.value);return this.name===i.Int?P.Value.Create(l,P.ValueType.Int):this.name===i.Float?P.Value.Create(l,P.ValueType.Float):P.Value.Create(l,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof P.ListValue&&e[1]instanceof P.IntValue)return this.CallListIncrementOperation(e);let t=(0, Ke.asOrThrows)(e[0],P.Value),n=(0, Ke.asOrThrows)(e[1],P.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=P.ValueType.List||n.valueType!=P.ValueType.List)){if(this._operationFuncs===null)return (0, We.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(P.ValueType.Int);if(r===null)return (0, We.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, Ke.asBooleanOrThrows)(r(t.isTruthy?1:0,n.isTruthy?1:0));return new P.BoolValue(a)}if(t.valueType==P.ValueType.List&&n.valueType==P.ValueType.List)return this.CallType([t,n]);throw new Un.StoryException("Can not call use "+this.name+" operation on "+P.ValueType[t.valueType]+" and "+P.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, Ke.asOrThrows)(e[0],P.ListValue),n=(0, Ke.asOrThrows)(e[1],P.IntValue),r=new ir.InkList;if(t.value===null)return (0, We.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=ir.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, We.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(P.ValueType.Int);if(n.value===null)return (0, We.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(s,n.value),h=null;if(t.value.origins===null)return (0, We.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of t.value.origins)if(c.name==o.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(u,ir.InkListItem.Null);c.exists&&r.Add(c.result,u);}}return new P.ListValue(r)}CoerceValuesToSingleType(e){let t=P.ValueType.Int,n=null;for(let a of e){let s=(0, Ke.asOrThrows)(a,P.Value);s.valueType>t&&(t=s.valueType),s.valueType==P.ValueType.List&&(n=(0, Ke.asOrNull)(s,P.ListValue));}let r=[];if(P.ValueType[t]==P.ValueType[P.ValueType.List])for(let a of e){let s=(0, Ke.asOrThrows)(a,P.Value);if(s.valueType==P.ValueType.List)r.push(s);else if(s.valueType==P.ValueType.Int){let o=parseInt(s.valueObject);if(n=(0, Ke.asOrThrows)(n,P.ListValue),n.value===null)return (0, We.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, We.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,ir.InkListItem.Null);if(u.exists){let h=new P.ListValue(u.result,o);r.push(h);}else throw new Un.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=P.ValueType[s.valueType];throw new Un.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, Ke.asOrThrows)(a,P.Value).Cast(t);r.push(o);}return r}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)i.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];i.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=true,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,r)=>n+r),this.AddIntBinaryOp(this.Subtract,(n,r)=>n-r),this.AddIntBinaryOp(this.Multiply,(n,r)=>n*r),this.AddIntBinaryOp(this.Divide,(n,r)=>Math.floor(n/r)),this.AddIntBinaryOp(this.Mod,(n,r)=>n%r),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,r)=>n==r),this.AddIntBinaryOp(this.Greater,(n,r)=>n>r),this.AddIntBinaryOp(this.Less,(n,r)=>n<r),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,r)=>n>=r),this.AddIntBinaryOp(this.LessThanOrEquals,(n,r)=>n<=r),this.AddIntBinaryOp(this.NotEquals,(n,r)=>n!=r),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,r)=>n!=0&&r!=0),this.AddIntBinaryOp(this.Or,(n,r)=>n!=0||r!=0),this.AddIntBinaryOp(this.Max,(n,r)=>Math.max(n,r)),this.AddIntBinaryOp(this.Min,(n,r)=>Math.min(n,r)),this.AddIntBinaryOp(this.Pow,(n,r)=>Math.pow(n,r)),this.AddIntUnaryOp(this.Floor,i.Identity),this.AddIntUnaryOp(this.Ceiling,i.Identity),this.AddIntUnaryOp(this.Int,i.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,r)=>n+r),this.AddFloatBinaryOp(this.Subtract,(n,r)=>n-r),this.AddFloatBinaryOp(this.Multiply,(n,r)=>n*r),this.AddFloatBinaryOp(this.Divide,(n,r)=>n/r),this.AddFloatBinaryOp(this.Mod,(n,r)=>n%r),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,r)=>n==r),this.AddFloatBinaryOp(this.Greater,(n,r)=>n>r),this.AddFloatBinaryOp(this.Less,(n,r)=>n<r),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,r)=>n>=r),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,r)=>n<=r),this.AddFloatBinaryOp(this.NotEquals,(n,r)=>n!=r),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,r)=>n!=0&&r!=0),this.AddFloatBinaryOp(this.Or,(n,r)=>n!=0||r!=0),this.AddFloatBinaryOp(this.Max,(n,r)=>Math.max(n,r)),this.AddFloatBinaryOp(this.Min,(n,r)=>Math.min(n,r)),this.AddFloatBinaryOp(this.Pow,(n,r)=>Math.pow(n,r)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,i.Identity),this.AddStringBinaryOp(this.Add,(n,r)=>n+r),this.AddStringBinaryOp(this.Equal,(n,r)=>n===r),this.AddStringBinaryOp(this.NotEquals,(n,r)=>n!==r),this.AddStringBinaryOp(this.Has,(n,r)=>n.includes(r)),this.AddStringBinaryOp(this.Hasnt,(n,r)=>!n.includes(r)),this.AddListBinaryOp(this.Add,(n,r)=>n.Union(r)),this.AddListBinaryOp(this.Subtract,(n,r)=>n.Without(r)),this.AddListBinaryOp(this.Has,(n,r)=>n.Contains(r)),this.AddListBinaryOp(this.Hasnt,(n,r)=>!n.Contains(r)),this.AddListBinaryOp(this.Intersect,(n,r)=>n.Intersect(r)),this.AddListBinaryOp(this.Equal,(n,r)=>n.Equals(r)),this.AddListBinaryOp(this.Greater,(n,r)=>n.GreaterThan(r)),this.AddListBinaryOp(this.Less,(n,r)=>n.LessThan(r)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,r)=>n.GreaterThanOrEquals(r)),this.AddListBinaryOp(this.LessThanOrEquals,(n,r)=>n.LessThanOrEquals(r)),this.AddListBinaryOp(this.NotEquals,(n,r)=>!n.Equals(r)),this.AddListBinaryOp(this.And,(n,r)=>n.Count>0&&r.Count>0),this.AddListBinaryOp(this.Or,(n,r)=>n.Count>0||r.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let e=(n,r)=>n.Equals(r),t=(n,r)=>!n.Equals(r);this.AddOpToNativeFunc(this.Equal,2,P.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,P.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,n,r){if(this._nativeFunctions===null)return (0, We.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new i(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,r);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,P.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,P.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,P.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,P.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,P.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,P.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,P.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};rr.NativeFunctionCall=B;B.Add="+";B.Subtract="-";B.Divide="/";B.Multiply="*";B.Mod="%";B.Negate="_";B.Equal="==";B.Greater=">";B.Less="<";B.GreaterThanOrEquals=">=";B.LessThanOrEquals="<=";B.NotEquals="!=";B.Not="!";B.And="&&";B.Or="||";B.Min="MIN";B.Max="MAX";B.Pow="POW";B.Floor="FLOOR";B.Ceiling="CEILING";B.Int="INT";B.Float="FLOAT";B.Has="?";B.Hasnt="!?";B.Intersect="^";B.ListMin="LIST_MIN";B.ListMax="LIST_MAX";B.All="LIST_ALL";B.Count="LIST_COUNT";B.ValueOfList="LIST_VALUE";B.Invert="LIST_INVERT";B._nativeFunctions=null;});var ar=w(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.NumberExpression=void 0;var sf=Ue(),Ua=ne(),af=z(),Ka=class i extends sf.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new Ua.IntValue(this.value)):this.isFloat()?n.AddContent(new Ua.FloatValue(this.value)):this.isBool()&&n.AddContent(new Ua.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, af.asOrNull)(e,i);return t?t.subtype==this.subtype&&t.value==this.value:false}};sr.NumberExpression=Ka;});var Xa=w(or=>{Object.defineProperty(or,"__esModule",{value:true});or.UnaryExpression=void 0;var of=Ue(),lf=ht(),Cn=ar(),uf=z(),Kn=class extends of.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(lf.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};or.UnaryExpression=Kn;Kn.WithInner=(i,e)=>{let t=(0, uf.asOrNull)(i,Cn.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new Cn.NumberExpression(-t.value,"int");if(t.isFloat())return new Cn.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new Cn.NumberExpression(t.value==0,"bool");if(t.isFloat())return new Cn.NumberExpression(t.value==0,"bool");if(t.isBool())return new Cn.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new Kn(i,e)};});var Qa=w(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.BinaryExpression=void 0;var hf=Ue(),cf=ht(),df=Xa(),pf=z(),Ya=class extends hf.Expression{constructor(e,t,n){super(),this.opName=n,this.GenerateIntoContainer=r=>{this.leftExpression.GenerateIntoContainer(r),this.rightExpression.GenerateIntoContainer(r),this.opName=this.NativeNameForOp(this.opName),r.AddContent(cf.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=r=>r==="and"?"&&":r==="or"?"||":r==="mod"?"%":r==="has"?"?":r==="hasnt"?"!?":r,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, pf.asOrNull)(this.leftExpression,df.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};lr.BinaryExpression=Ya;});var Yn=w(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.CharacterSet=void 0;var Xn=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,n)=>{for(let r=t.charCodeAt(0);r<=n.charCodeAt(0);++r)this.Add(String.fromCharCode(r));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let n of t)this.Add(n);else for(let n of t.set)this.Add(n);return this},e&&this.AddCharacters(e);}};ur.CharacterSet=Xn;Xn.FromRange=(i,e)=>new Xn().AddRange(i,e);});var gh=w(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.CharacterRange=void 0;var fh=Yn(),Qn=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new fh.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let r=this.start.charCodeAt(0),a;r<=this.end.charCodeAt(0);r+=1)a=String.fromCharCode(r),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},n instanceof fh.CharacterSet)this._excludes=n.set;else for(let r of n)this._excludes.add(r);}get start(){return this._start}get end(){return this._end}};hr.CharacterRange=Qn;Qn.Define=(i,e,t=[])=>new Qn(i,e,t);});var dr=w(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.ChoicePoint=void 0;var ff=Re(),gf=ke(),Za=Ce(),eo=class extends ff.InkObject{constructor(e=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, Za.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Za.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new gf.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Za.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};cr.ChoicePoint=eo;});var Ut=w(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.PushPopType=void 0;var mh;(function(i){i[i.Tunnel=0]="Tunnel",i[i.Function=1]="Function",i[i.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(mh||(pr.PushPopType=mh={}));});var Zn=w(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.Pointer=void 0;var mf=ke(),to=class i{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new mf.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new i(this.container,this.index)}static StartOf(e){return new i(e,0)}static get Null(){return new i(null,-1)}};fr.Pointer=to;});var ct=w(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.Divert=void 0;var Cf=ke(),yf=Ut(),vf=Jt(),Sf=Re(),no=Zn(),Ch=ae(),gr=Ce(),io=class i extends Sf.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=no.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, gr.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, gr.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, gr.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof Ch.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=no.Pointer.StartOf(e instanceof Ch.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new Cf.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=no.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof e<"u"&&(this.pushesToStack=true,this.stackPushType=e);}Equals(e){let t=e;return t instanceof i&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, gr.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new vf.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==yf.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};mr.Divert=io;});var bt=w(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.SymbolType=void 0;var yh;(function(i){i[i.Knot=0]="Knot",i[i.List=1]="List",i[i.ListItem=2]="ListItem",i[i.Var=3]="Var",i[i.SubFlowAndWeave=4]="SubFlowAndWeave",i[i.Arg=5]="Arg",i[i.Temp=6]="Temp";})(yh||(Cr.SymbolType=yh={}));});var Ft=w(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.VariableAssignment=void 0;var Ef=Re(),ro=class extends Ef.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};yr.VariableAssignment=ro;});var yn=w(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.Choice=void 0;var bf=dr(),vr=ae(),Nt=ye(),so=ct(),vh=ne(),Df=ee(),Af=bt(),Sh=Ft(),ao=class extends Df.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,n){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new vr.Container,this._runtimeChoice=new bf.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Nt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new vh.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let r=new Sh.VariableAssignment("$r",true);this._outerContainer.AddContent(r),this._outerContainer.AddContent(Nt.ControlCommand.BeginString()),this._divertToStartContentOuter=new so.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new so.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new vr.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Nt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Nt.ControlCommand.BeginString());let r=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(r),this._outerContainer.AddContent(Nt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Nt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new vr.Container,this.startContent){this._returnToR2=new vh.DivertTargetValue,this._innerContentContainer.AddContent(Nt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Nt.ControlCommand.EvalEnd());let r=new Sh.VariableAssignment("$r",true);this._innerContentContainer.AddContent(r),this._divertToStartContentInner=new so.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new vr.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let r=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(r);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=e,this.choiceOnlyContent=t,this.innerContent=n,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(e){var t;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Af.SymbolType.SubFlowAndWeave);}};Sr.Choice=ao;});var Eh=w(br=>{Object.defineProperty(br,"__esModule",{value:true});br.StringParserElement=void 0;var Er=class i{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{i._uniqueIdCounter++,this.uniqueId=i._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};br.StringParserElement=Er;Er._uniqueIdCounter=1e3;});var Dh=w(Dr=>{Object.defineProperty(Dr,"__esModule",{value:true});Dr.StringParserState=void 0;var bh=Eh(),oo=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new bh.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(t),n.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],n=this._stack[this._numElements-1];t.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new bh.StringParserElement;this._numElements=1;}};Dr.StringParserState=oo;});var uo=w(Kt=>{Object.defineProperty(Kt,"__esModule",{value:true});Kt.StringParser=Kt.ParseSuccess=void 0;var lo=Yn(),wf=Dh();Kt.ParseSuccess=Symbol("ParseSuccessStruct");var ei=class i{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=n=>(this.state.Pop(n),null),this.CancelRule=n=>{this.state.Pop(n);},this.SucceedRule=(n,r=null)=>{let a=this.state.Peek(n),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(r,s,a),this.state.Squash();let o=r;return o===null&&(o=i.ParseSuccess),o},this.Expect=(n,r=null,a=null)=>{let s=this.ParseObject(n);if(s===null){r===null&&(r=n.name);let o,l=this.LineRemainder();l===null||l.length===0?o="end of line":o=`'${l}'`,this.Error(`Expected ${r} but saw ${o}`),a!==null&&(s=a());}return s},this.Error=(n,r=false)=>{this.ErrorOnLine(n,this.lineIndex+1,r);},this.ErrorWithParsedObject=(n,r,a=false)=>{this.ErrorOnLine(n,r.debugMetadata?r.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(n,r,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,r-1,a);else throw new Error(`${s} on line ${r}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
1
+ 'use strict';var y=require('zod'),pixiVn=require('@drincs/pixi-vn'),canvas=require('@drincs/pixi-vn/canvas'),characters=require('@drincs/pixi-vn/characters'),narration=require('@drincs/pixi-vn/narration'),sound=require('@drincs/pixi-vn/sound'),storage=require('@drincs/pixi-vn/storage'),virtual_pixiVnInk=require('virtual:pixi-vn-ink');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var y__default=/*#__PURE__*/_interopDefault(y);var kc=Object.create;var Gl=Object.defineProperty;var Rc=Object.getOwnPropertyDescriptor;var Lc=Object.getOwnPropertyNames;var Bc=Object.getPrototypeOf,Wc=Object.prototype.hasOwnProperty;var _t=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var x=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var jc=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lc(e))!Wc.call(i,r)&&r!==t&&Gl(i,r,{get:()=>e[r],enumerable:!(n=Rc(e,r))||n.enumerable});return i};var Us=(i,e,t)=>(t=i!=null?kc(Bc(i)):{},jc(Gl(t,"default",{value:i,enumerable:true}),i));var Ca=x(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.CompilerOptions=void 0;var ga=class{constructor(e=null,t=[],n=false,r=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=n,this.errorHandler=r,this.fileHandler=a;}};xi.CompilerOptions=ga;});var Ru=x(wi=>{Object.defineProperty(wi,"__esModule",{value:true});wi.DebugSourceRange=void 0;var ya=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};wi.DebugSourceRange=ya;});var Kt=x(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.ErrorType=void 0;var Lu;(function(i){i[i.Author=0]="Author",i[i.Warning=1]="Warning",i[i.Error=2]="Error";})(Lu||(_i.ErrorType=Lu={}));});var Bu=x(Oi=>{Object.defineProperty(Oi,"__esModule",{value:true});Oi.Argument=void 0;var va=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};Oi.Argument=va;});var H=x(le=>{Object.defineProperty(le,"__esModule",{value:true});le.filterUndef=le.isEquatable=le.nullIfUndefined=le.asINamedContentOrNull=le.asBooleanOrThrows=le.asNumberOrThrows=le.asOrThrows=le.asOrNull=void 0;function Qd(i,e){return i instanceof e?Wu(i):null}le.asOrNull=Qd;function Zd(i,e){if(i instanceof e)return Wu(i);throw new Error(`${i} is not of type ${e}`)}le.asOrThrows=Zd;function ep(i){if(typeof i=="number")return i;throw new Error(`${i} is not a number`)}le.asNumberOrThrows=ep;function tp(i){if(typeof i=="boolean")return i;throw new Error(`${i} is not a boolean`)}le.asBooleanOrThrows=tp;function np(i){return i.hasValidName&&i.name?i:null}le.asINamedContentOrNull=np;function ip(i){return typeof i>"u"?null:i}le.nullIfUndefined=ip;function rp(i){return typeof i=="object"&&typeof i.Equals=="function"}le.isEquatable=rp;function Wu(i,e){return i}function sp(i){return i!=null}le.filterUndef=sp;});var Q=x(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.ParsedObject=void 0;var ju=H(),Sa=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let n of t)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let n=(0, ju.asOrNull)(this,e);if(n!==null&&(t===null||t(n)===true))return n;if(this.content===null)return null;for(let r of this.content){let a=r.Find&&r.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,n)=>{let r=Array.isArray(n)?n:[],a=(0, ju.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&r.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,r);return r},this.Warning=(e,t=null)=>{this.Error(e,t,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,n=false){if(t===null&&(t=this),!(t._alreadyHadError&&!n||t._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(e,t,n);else throw new Error(`No parent object to send error to: ${e}`);n?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};Ti.ParsedObject=Sa;});var Fi=x(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.AuthorWarning=void 0;var ap=Q(),Ea=class extends ap.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Pi.AuthorWarning=Ea;});var Ae=x(_n=>{Object.defineProperty(_n,"__esModule",{value:true});_n.Path=void 0;var Xt=class i{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof i.Component&&arguments[1]instanceof i){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new i(e)}else return i.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new i;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new i,n=0;for(let r=0;r<e._components.length&&e._components[r].isParent;++r)n++;for(let r=0;r<this._components.length-n;++r)t._components.push(this._components[r]);for(let r=n;r<e._components.length;++r)t._components.push(e._components[r]);return t}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let t=this._componentsString.split(".");for(let n of t)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new i.Component(parseInt(n))):this._components.push(new i.Component(n));}toString(){return this.componentsString}Equals(e){if(e==null||e._components.length!=this._components.length||e.isRelative!=this.isRelative)return false;for(let t=0,n=e._components.length;t<n;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new i;return t._components.push(...this._components),t._components.push(e),t}};_n.Path=Xt;Xt.parentId="^";(function(i){class e{constructor(n){this.index=-1,this.name=null,typeof n=="string"?this.name=n:this.index=n;}get isIndex(){return this.index>=0}get isParent(){return this.name==i.parentId}static ToParent(){return new e(i.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}i.Component=e;})(Xt||(_n.Path=Xt={}));});var On=x(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.Debug=void 0;var qu;(function(i){function e(n,r,a){t(n instanceof r,a);}i.AssertType=e;function t(n,r){if(!n)throw typeof r<"u"&&console.warn(r),console.trace&&console.trace(),new Error("")}i.Assert=t;})(qu||(Ni.Debug=qu={}));});var pe=x(Yt=>{Object.defineProperty(Yt,"__esModule",{value:true});Yt.throwNullException=Yt.NullException=void 0;var Ii=class extends Error{};Yt.NullException=Ii;function op(i){throw new Ii(`${i} is null or undefined`)}Yt.throwNullException=op;});var xe=x(ki=>{Object.defineProperty(ki,"__esModule",{value:true});ki.InkObject=void 0;var Qt=Ae(),Tn=ie(),Da=On(),Zt=H(),Vi=pe(),ba=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let n=t.ContentAtPath(e).obj;if(n){let r=n.debugMetadata;if(r!==null)return r.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Qt.Path;else {let e=[],t=this,n=(0, Zt.asOrNull)(t.parent,Tn.Container);for(;n!==null;){let r=(0, Zt.asINamedContentOrNull)(t);if(r!=null&&r.hasValidName){if(r.name===null)return (0, Vi.throwNullException)("namedChild.name");e.unshift(new Qt.Path.Component(r.name));}else e.unshift(new Qt.Path.Component(n.content.indexOf(t)));t=n,n=(0, Zt.asOrNull)(n.parent,Tn.Container);}this._path=new Qt.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Vi.throwNullException)("path");if(e.isRelative){let t=(0, Zt.asOrNull)(this,Tn.Container);return t===null&&(Da.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, Zt.asOrNull)(this.parent,Tn.Container),Da.Debug.Assert(t!==null,"Expected parent to be a container"),Da.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Vi.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Vi.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,n=Math.min(e.length,t.length),r=-1;for(let l=0;l<n;++l){let u=t.GetComponent(l),h=e.GetComponent(l);if(u.Equals(h))r=l;else break}if(r==-1)return e;let a=t.componentCount-1-r,s=[];for(let l=0;l<a;++l)s.push(Qt.Path.Component.ToParent());for(let l=r+1;l<e.componentCount;++l)s.push(e.GetComponent(l));return new Qt.Path(s,true)}CompactPathString(e){let t=null,n=null;return e.isRelative?(n=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(n=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),n.length<t.length?n:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, Zt.asOrNull)(e,Tn.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,n){e[t]&&(e[t]=null),e[t]=n,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};ki.InkObject=ba;});var Nt=x(Ri=>{Object.defineProperty(Ri,"__esModule",{value:true});Ri.StringBuilder=void 0;var Aa=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=`
2
+ `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(n,r)=>typeof t[r]<"u"?t[r]:n);}toString(){return this.string}Clear(){this.string="";}};Ri.StringBuilder=Aa;});var _e=x(en=>{Object.defineProperty(en,"__esModule",{value:true});en.InkList=en.InkListItem=void 0;var Ke=pe(),lp=Nt(),we=class i{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new i(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(e){if(e instanceof i){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new i(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!i.isLikeInkListItem(t))return i.Null;let n=t;return new i(n.originName,n.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};en.InkListItem=we;var xa=class i extends Map{constructor(){if(super(arguments[0]instanceof i?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof i){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, Ke.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, Ke.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var n;if(e==null||e=="")return new i;let r=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(r)return r.value===null?(0, Ke.throwNullException)("listValue.value"):new i(r.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof we){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, Ke.throwNullException)("this.origins");for(let r of this.origins)if(r.name==n.originName){let a=r.TryGetValueForItem(n,0);if(a.exists){this.Add(n,a.result);return}else throw new Error("Could not add the item "+n+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let n=e,r=null;if(this.origins===null)return (0, Ke.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, Ke.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(r!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+r.name);r=a;}}if(r==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=i.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new we(r.name,n),s=r.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(we.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let n=e.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${e}`);this.set(n,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(n=>n.name==e?(t=n,false):true),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=we.fromSerializedKey(e);if(t.originName===null)return (0, Ke.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:we.Null,Value:0};for(let[t,n]of this){let r=we.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:r,Value:n});}return e}get minItem(){let e={Key:we.Null,Value:0};for(let[t,n]of this){let r=we.fromSerializedKey(t);(e.Key.isNull||n<e.Value)&&(e={Key:r,Value:n});}return e}get inverse(){let e=new i;if(this.origins!=null)for(let t of this.origins)for(let[n,r]of t.items){let a=we.fromSerializedKey(n);this.ContainsKey(a)||e.Add(a,r);}return e}get all(){let e=new i;if(this.origins!=null)for(let t of this.origins)for(let[n,r]of t.items){let a=we.fromSerializedKey(n);e.set(a.serialized(),r);}return e}Union(e){let t=new i(this);for(let[n,r]of e)t.set(n,r);return t}Intersect(e){let t=new i;for(let[n,r]of this)e.has(n)&&t.set(n,r);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new i(this);for(let[n]of e)t.delete(n);return t}Contains(e){if(typeof e=="string")return this.ContainsItemNamed(e);let t=e;if(t.size==0||this.size==0)return false;for(let[n]of t)if(!this.has(n))return false;return true}GreaterThan(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>e.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<e.minItem.Value}LessThanOrEquals(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<=e.maxItem.Value&&this.minItem.Value<=e.minItem.Value}MaxAsList(){return this.Count>0?new i(this.maxItem):new i}MinAsList(){return this.Count>0?new i(this.minItem):new i}ListWithSubRange(e,t){if(this.Count==0)return new i;let n=this.orderedItems,r=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?r=e:e instanceof i&&e.Count>0&&(r=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof i&&t.Count>0&&(a=t.maxItem.Value);let s=new i;s.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=r&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(e){if(!(e instanceof i)||e.Count!=this.Count)return false;for(let[t]of this)if(!e.has(t))return false;return true}get orderedItems(){let e=new Array;for(let[t,n]of this){let r=we.fromSerializedKey(t);e.push({Key:r,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, Ke.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, Ke.throwNullException)("y.Key.originName"):t.Value==n.Value?t.Key.originName.localeCompare(n.Key.originName):t.Value<n.Value?-1:t.Value>n.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new lp.StringBuilder;for(let n=0;n<e.length;n++){n>0&&t.Append(", ");let r=e[n].Key;if(r.itemName===null)return (0, Ke.throwNullException)("item.itemName");t.Append(r.itemName);}return t.toString()}valueOf(){return NaN}};en.InkList=xa;});var Pn=x(Li=>{Object.defineProperty(Li,"__esModule",{value:true});Li.StoryException=void 0;var wa=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};Li.StoryException=wa;});var tn=x(Ct=>{Object.defineProperty(Ct,"__esModule",{value:true});Ct.tryParseFloat=Ct.tryParseInt=Ct.tryGetValueFromMap=void 0;function up(i,e,t){if(i===null)return {result:t,exists:false};let n=i.get(e);return typeof n>"u"?{result:t,exists:false}:{result:n,exists:true}}Ct.tryGetValueFromMap=up;function hp(i,e=0){let t=parseInt(i);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ct.tryParseInt=hp;function cp(i,e=0){let t=parseFloat(i);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ct.tryParseFloat=cp;});var ee=x(te=>{Object.defineProperty(te,"__esModule",{value:true});te.ValueType=te.ListValue=te.VariablePointerValue=te.DivertTargetValue=te.StringValue=te.FloatValue=te.IntValue=te.BoolValue=te.Value=te.AbstractValue=void 0;var Mu=xe(),Gu=Ae(),It=_e(),dp=Pn(),Fn=H(),$u=tn(),Re=pe(),Bi=class i extends Mu.InkObject{static Create(e,t){if(t){if(t===Y.Int&&Number.isInteger(Number(e)))return new Ye(Number(e));if(t===Y.Float&&!isNaN(e))return new Qe(Number(e))}if(typeof e=="boolean")return new nn(!!e);if(typeof e=="string")return new ht(String(e));if(Number.isInteger(Number(e)))return new Ye(Number(e));if(isNaN(e)){if(e instanceof Gu.Path)return new Wi((0, Fn.asOrThrows)(e,Gu.Path));if(e instanceof It.InkList)return new ji((0, Fn.asOrThrows)(e,It.InkList))}else return new Qe(Number(e));return null}Copy(){return (0, Fn.asOrThrows)(i.Create(this.valueObject),Mu.InkObject)}BadCastException(e){return new dp.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};te.AbstractValue=Bi;var Xe=class extends Bi{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value.toString()}};te.Value=Xe;var nn=class extends Xe{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return Y.Bool}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Y.Int)return new Ye(this.value?1:0);if(e==Y.Float)return new Qe(this.value?1:0);if(e==Y.String)return new ht(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};te.BoolValue=nn;var Ye=class extends Xe{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return Y.Int}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Y.Bool)return new nn(this.value!==0);if(e==Y.Float)return new Qe(this.value);if(e==Y.String)return new ht(""+this.value);throw this.BadCastException(e)}};te.IntValue=Ye;var Qe=class extends Xe{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return Y.Float}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Y.Bool)return new nn(this.value!==0);if(e==Y.Int)return new Ye(this.value);if(e==Y.String)return new ht(""+this.value);throw this.BadCastException(e)}};te.FloatValue=Qe;var ht=class extends Xe{constructor(e){if(super(e||""),this._isNewline=this.value==`
3
+ `,this._isInlineWhitespace=true,this.value===null)return (0, Re.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return Y.String}get isTruthy(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==Y.Int){let t=(0, $u.tryParseInt)(this.value);if(t.exists)return new Ye(t.result);throw this.BadCastException(e)}if(e==Y.Float){let t=(0, $u.tryParseFloat)(this.value);if(t.exists)return new Qe(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};te.StringValue=ht;var Wi=class extends Xe{constructor(e=null){super(e);}get valueType(){return Y.DivertTarget}get targetPath(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};te.DivertTargetValue=Wi;var _a=class i extends Xe{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return Y.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new i(this.variableName,this.contextIndex)}};te.VariablePointerValue=_a;var ji=class i extends Xe{get isTruthy(){return this.value===null?(0, Re.throwNullException)("this.value"):this.value.Count>0}get valueType(){return Y.List}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==Y.Int){let t=this.value.maxItem;return t.Key.isNull?new Ye(0):new Ye(t.Value)}else if(e==Y.Float){let t=this.value.maxItem;return t.Key.isNull?new Qe(0):new Qe(t.Value)}else if(e==Y.String){let t=this.value.maxItem;return t.Key.isNull?new ht(""):new ht(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new It.InkList:e instanceof It.InkList?this.value=new It.InkList(e):e instanceof It.InkListItem&&typeof t=="number"&&(this.value=new It.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, Fn.asOrNull)(e,i),r=(0, Fn.asOrNull)(t,i);if(r&&r.value===null)return (0, Re.throwNullException)("newList.value");if(n&&n.value===null)return (0, Re.throwNullException)("oldList.value");n&&r&&r.value.Count==0&&r.value.SetInitialOriginNames(n.value.originNames);}};te.ListValue=ji;var Y;(function(i){i[i.Bool=-1]="Bool",i[i.Int=0]="Int",i[i.Float=1]="Float",i[i.List=2]="List",i[i.String=3]="String",i[i.DivertTarget=4]="DivertTarget",i[i.VariablePointer=5]="VariablePointer";})(Y||(te.ValueType=Y={}));});var Ju=x(qi=>{Object.defineProperty(qi,"__esModule",{value:true});qi.SearchResult=void 0;var pp=ie(),Oa=class i{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof pp.Container?this.obj:null}copy(){let e=new i;return e.obj=this.obj,e.approximate=this.approximate,e}};qi.SearchResult=Oa;});var ie=x(In=>{Object.defineProperty(In,"__esModule",{value:true});In.Container=void 0;var fp=ee(),Hu=pe(),mp=Nt(),rn=xe(),gp=Ju(),zu=Ae(),Uu=On(),Cp=tn(),yt=H(),Nn=class i extends rn.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,n]of this.namedContent){let r=(0, yt.asOrThrows)(n,rn.InkObject);e.set(t,r);}for(let t of this.content){let n=(0, yt.asINamedContentOrNull)(t);n!=null&&n.hasValidName&&e.delete(n.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[n]of t)this.namedContent.delete(n);if(e!=null)for(let[,n]of e){let r=(0, yt.asINamedContentOrNull)(n);r!=null&&this.AddToNamedContentOnly(r);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=i.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=i.CountFlags.Turns),this.countingAtStartOnly&&(e|=i.CountFlags.CountStartOnly),e==i.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&i.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&i.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&i.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof i;)t.content.length>0&&(e.push(new zu.Path.Component(0)),t=t.content[0]);return new zu.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let n of t)this.AddContent(n);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, yt.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Uu.Debug.AssertType(e,rn.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, yt.asOrThrows)(e,rn.InkObject);if(t.parent=this,e.name===null)return (0, Hu.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let r=new gp.SearchResult;r.approximate=false;let a=this,s=this;for(let o=t;o<n;++o){let l=e.GetComponent(o);if(a==null){r.approximate=true;break}let u=a.ContentWithPathComponent(l);if(u==null){r.approximate=true;break}let h=(0, yt.asOrNull)(u,i);if(o<n-1&&h==null){r.approximate=true;break}s=u,a=h;}return r.obj=s,r}InsertContent(e,t){if(this.content.splice(t,0,e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}AddContentsOfContainer(e){this.content.push(...e.content);for(let t of e.content)t.parent=this,this.TryAddNamedContent(t);}ContentWithPathComponent(e){if(e.isIndex)return e.index>=0&&e.index<this.content.length?this.content[e.index]:null;if(e.isParent)return this.parent;{if(e.name===null)return (0, Hu.throwNullException)("component.name");let t=(0, Cp.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, yt.asOrThrows)(t.result,rn.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new mp.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],n=arguments[2];function r(){for(let o=0;o<4*t;++o)e.Append(" ");}r(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==n&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof i?o.BuildStringOfHierarchy(e,t,n):(r(),o instanceof fp.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
4
+ `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof i)&&o==n&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, yt.asOrThrows)(o,rn.InkObject))>=0||a.set(s,o);if(a.size>0){r(),e.AppendLine("-- named: --");for(let[,s]of a)Uu.Debug.AssertType(s,i,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,r(),e.Append("]");}};In.Container=Nn;(function(i){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(i.CountFlags||(i.CountFlags={}));})(Nn||(In.Container=Nn={}));});var fe=x(kn=>{Object.defineProperty(kn,"__esModule",{value:true});kn.ControlCommand=void 0;var yp=xe(),Vn=class i extends yp.InkObject{get commandType(){return this._commandType}constructor(e=i.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new i(this.commandType)}static EvalStart(){return new i(i.CommandType.EvalStart)}static EvalOutput(){return new i(i.CommandType.EvalOutput)}static EvalEnd(){return new i(i.CommandType.EvalEnd)}static Duplicate(){return new i(i.CommandType.Duplicate)}static PopEvaluatedValue(){return new i(i.CommandType.PopEvaluatedValue)}static PopFunction(){return new i(i.CommandType.PopFunction)}static PopTunnel(){return new i(i.CommandType.PopTunnel)}static BeginString(){return new i(i.CommandType.BeginString)}static EndString(){return new i(i.CommandType.EndString)}static NoOp(){return new i(i.CommandType.NoOp)}static ChoiceCount(){return new i(i.CommandType.ChoiceCount)}static Turns(){return new i(i.CommandType.Turns)}static TurnsSince(){return new i(i.CommandType.TurnsSince)}static ReadCount(){return new i(i.CommandType.ReadCount)}static Random(){return new i(i.CommandType.Random)}static SeedRandom(){return new i(i.CommandType.SeedRandom)}static VisitIndex(){return new i(i.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new i(i.CommandType.SequenceShuffleIndex)}static StartThread(){return new i(i.CommandType.StartThread)}static Done(){return new i(i.CommandType.Done)}static End(){return new i(i.CommandType.End)}static ListFromInt(){return new i(i.CommandType.ListFromInt)}static ListRange(){return new i(i.CommandType.ListRange)}static ListRandom(){return new i(i.CommandType.ListRandom)}static BeginTag(){return new i(i.CommandType.BeginTag)}static EndTag(){return new i(i.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};kn.ControlCommand=Vn;(function(i){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(i.CommandType||(i.CommandType={}));})(Vn||(kn.ControlCommand=Vn={}));});var Le=x(Mi=>{Object.defineProperty(Mi,"__esModule",{value:true});Mi.Expression=void 0;var Ku=ie(),Ta=fe(),vp=Q(),Pa=class extends vp.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new Ku.Container;return e.AddContent(Ta.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(Ta.ControlCommand.EvalOutput()),e.AddContent(Ta.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new Ku.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let n=t.Copy();n&&e.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};Mi.Expression=Pa;});var Vt=x(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.Void=void 0;var Sp=xe(),Fa=class extends Sp.InkObject{toString(){return "Void"}};Gi.Void=Fa;});var Ze=x(Ji=>{Object.defineProperty(Ji,"__esModule",{value:true});Ji.NativeFunctionCall=void 0;var T=ee(),Rn=Pn(),Ep=Vt(),$i=_e(),Dp=xe(),Be=H(),Oe=pe(),B=class i extends Dp.InkObject{static CallWithName(e){return new i(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, Oe.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(i._nativeFunctions===null?(0, Oe.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=i._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof Ep.Void)throw new Rn.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');a instanceof T.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),r=n[0].valueType;return r==T.ValueType.Int?this.CallType(n):r==T.ValueType.Float?this.CallType(n):r==T.ValueType.String?this.CallType(n):r==T.ValueType.DivertTarget?this.CallType(n):r==T.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, Be.asOrThrows)(e[0],T.Value),n=t.valueType,r=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, Oe.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){let o=T.ValueType[n];throw new Rn.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, Be.asOrThrows)(e[1],T.Value),u=s;if(r.value===null||l.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(r.value,l.value);return T.Value.Create(h)}else {let o=s;if(r.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(r.value);return this.name===i.Int?T.Value.Create(l,T.ValueType.Int):this.name===i.Float?T.Value.Create(l,T.ValueType.Float):T.Value.Create(l,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof T.ListValue&&e[1]instanceof T.IntValue)return this.CallListIncrementOperation(e);let t=(0, Be.asOrThrows)(e[0],T.Value),n=(0, Be.asOrThrows)(e[1],T.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=T.ValueType.List||n.valueType!=T.ValueType.List)){if(this._operationFuncs===null)return (0, Oe.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(T.ValueType.Int);if(r===null)return (0, Oe.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, Be.asBooleanOrThrows)(r(t.isTruthy?1:0,n.isTruthy?1:0));return new T.BoolValue(a)}if(t.valueType==T.ValueType.List&&n.valueType==T.ValueType.List)return this.CallType([t,n]);throw new Rn.StoryException("Can not call use "+this.name+" operation on "+T.ValueType[t.valueType]+" and "+T.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, Be.asOrThrows)(e[0],T.ListValue),n=(0, Be.asOrThrows)(e[1],T.IntValue),r=new $i.InkList;if(t.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=$i.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, Oe.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(T.ValueType.Int);if(n.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(s,n.value),h=null;if(t.value.origins===null)return (0, Oe.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of t.value.origins)if(c.name==o.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(u,$i.InkListItem.Null);c.exists&&r.Add(c.result,u);}}return new T.ListValue(r)}CoerceValuesToSingleType(e){let t=T.ValueType.Int,n=null;for(let a of e){let s=(0, Be.asOrThrows)(a,T.Value);s.valueType>t&&(t=s.valueType),s.valueType==T.ValueType.List&&(n=(0, Be.asOrNull)(s,T.ListValue));}let r=[];if(T.ValueType[t]==T.ValueType[T.ValueType.List])for(let a of e){let s=(0, Be.asOrThrows)(a,T.Value);if(s.valueType==T.ValueType.List)r.push(s);else if(s.valueType==T.ValueType.Int){let o=parseInt(s.valueObject);if(n=(0, Be.asOrThrows)(n,T.ListValue),n.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, Oe.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,$i.InkListItem.Null);if(u.exists){let h=new T.ListValue(u.result,o);r.push(h);}else throw new Rn.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=T.ValueType[s.valueType];throw new Rn.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, Be.asOrThrows)(a,T.Value).Cast(t);r.push(o);}return r}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)i.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];i.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=true,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,r)=>n+r),this.AddIntBinaryOp(this.Subtract,(n,r)=>n-r),this.AddIntBinaryOp(this.Multiply,(n,r)=>n*r),this.AddIntBinaryOp(this.Divide,(n,r)=>Math.floor(n/r)),this.AddIntBinaryOp(this.Mod,(n,r)=>n%r),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,r)=>n==r),this.AddIntBinaryOp(this.Greater,(n,r)=>n>r),this.AddIntBinaryOp(this.Less,(n,r)=>n<r),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,r)=>n>=r),this.AddIntBinaryOp(this.LessThanOrEquals,(n,r)=>n<=r),this.AddIntBinaryOp(this.NotEquals,(n,r)=>n!=r),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,r)=>n!=0&&r!=0),this.AddIntBinaryOp(this.Or,(n,r)=>n!=0||r!=0),this.AddIntBinaryOp(this.Max,(n,r)=>Math.max(n,r)),this.AddIntBinaryOp(this.Min,(n,r)=>Math.min(n,r)),this.AddIntBinaryOp(this.Pow,(n,r)=>Math.pow(n,r)),this.AddIntUnaryOp(this.Floor,i.Identity),this.AddIntUnaryOp(this.Ceiling,i.Identity),this.AddIntUnaryOp(this.Int,i.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,r)=>n+r),this.AddFloatBinaryOp(this.Subtract,(n,r)=>n-r),this.AddFloatBinaryOp(this.Multiply,(n,r)=>n*r),this.AddFloatBinaryOp(this.Divide,(n,r)=>n/r),this.AddFloatBinaryOp(this.Mod,(n,r)=>n%r),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,r)=>n==r),this.AddFloatBinaryOp(this.Greater,(n,r)=>n>r),this.AddFloatBinaryOp(this.Less,(n,r)=>n<r),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,r)=>n>=r),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,r)=>n<=r),this.AddFloatBinaryOp(this.NotEquals,(n,r)=>n!=r),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,r)=>n!=0&&r!=0),this.AddFloatBinaryOp(this.Or,(n,r)=>n!=0||r!=0),this.AddFloatBinaryOp(this.Max,(n,r)=>Math.max(n,r)),this.AddFloatBinaryOp(this.Min,(n,r)=>Math.min(n,r)),this.AddFloatBinaryOp(this.Pow,(n,r)=>Math.pow(n,r)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,i.Identity),this.AddStringBinaryOp(this.Add,(n,r)=>n+r),this.AddStringBinaryOp(this.Equal,(n,r)=>n===r),this.AddStringBinaryOp(this.NotEquals,(n,r)=>n!==r),this.AddStringBinaryOp(this.Has,(n,r)=>n.includes(r)),this.AddStringBinaryOp(this.Hasnt,(n,r)=>!n.includes(r)),this.AddListBinaryOp(this.Add,(n,r)=>n.Union(r)),this.AddListBinaryOp(this.Subtract,(n,r)=>n.Without(r)),this.AddListBinaryOp(this.Has,(n,r)=>n.Contains(r)),this.AddListBinaryOp(this.Hasnt,(n,r)=>!n.Contains(r)),this.AddListBinaryOp(this.Intersect,(n,r)=>n.Intersect(r)),this.AddListBinaryOp(this.Equal,(n,r)=>n.Equals(r)),this.AddListBinaryOp(this.Greater,(n,r)=>n.GreaterThan(r)),this.AddListBinaryOp(this.Less,(n,r)=>n.LessThan(r)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,r)=>n.GreaterThanOrEquals(r)),this.AddListBinaryOp(this.LessThanOrEquals,(n,r)=>n.LessThanOrEquals(r)),this.AddListBinaryOp(this.NotEquals,(n,r)=>!n.Equals(r)),this.AddListBinaryOp(this.And,(n,r)=>n.Count>0&&r.Count>0),this.AddListBinaryOp(this.Or,(n,r)=>n.Count>0||r.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let e=(n,r)=>n.Equals(r),t=(n,r)=>!n.Equals(r);this.AddOpToNativeFunc(this.Equal,2,T.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,T.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,n,r){if(this._nativeFunctions===null)return (0, Oe.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new i(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,r);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};Ji.NativeFunctionCall=B;B.Add="+";B.Subtract="-";B.Divide="/";B.Multiply="*";B.Mod="%";B.Negate="_";B.Equal="==";B.Greater=">";B.Less="<";B.GreaterThanOrEquals=">=";B.LessThanOrEquals="<=";B.NotEquals="!=";B.Not="!";B.And="&&";B.Or="||";B.Min="MIN";B.Max="MAX";B.Pow="POW";B.Floor="FLOOR";B.Ceiling="CEILING";B.Int="INT";B.Float="FLOAT";B.Has="?";B.Hasnt="!?";B.Intersect="^";B.ListMin="LIST_MIN";B.ListMax="LIST_MAX";B.All="LIST_ALL";B.Count="LIST_COUNT";B.ValueOfList="LIST_VALUE";B.Invert="LIST_INVERT";B._nativeFunctions=null;});var zi=x(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.NumberExpression=void 0;var bp=Le(),Na=ee(),Ap=H(),Ia=class i extends bp.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new Na.IntValue(this.value)):this.isFloat()?n.AddContent(new Na.FloatValue(this.value)):this.isBool()&&n.AddContent(new Na.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, Ap.asOrNull)(e,i);return t?t.subtype==this.subtype&&t.value==this.value:false}};Hi.NumberExpression=Ia;});var Va=x(Ui=>{Object.defineProperty(Ui,"__esModule",{value:true});Ui.UnaryExpression=void 0;var xp=Le(),wp=Ze(),sn=zi(),_p=H(),Ln=class extends xp.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(wp.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};Ui.UnaryExpression=Ln;Ln.WithInner=(i,e)=>{let t=(0, _p.asOrNull)(i,sn.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new sn.NumberExpression(-t.value,"int");if(t.isFloat())return new sn.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new sn.NumberExpression(t.value==0,"bool");if(t.isFloat())return new sn.NumberExpression(t.value==0,"bool");if(t.isBool())return new sn.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new Ln(i,e)};});var Ra=x(Ki=>{Object.defineProperty(Ki,"__esModule",{value:true});Ki.BinaryExpression=void 0;var Op=Le(),Tp=Ze(),Pp=Va(),Fp=H(),ka=class extends Op.Expression{constructor(e,t,n){super(),this.opName=n,this.GenerateIntoContainer=r=>{this.leftExpression.GenerateIntoContainer(r),this.rightExpression.GenerateIntoContainer(r),this.opName=this.NativeNameForOp(this.opName),r.AddContent(Tp.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=r=>r==="and"?"&&":r==="or"?"||":r==="mod"?"%":r==="has"?"?":r==="hasnt"?"!?":r,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, Fp.asOrNull)(this.leftExpression,Pp.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};Ki.BinaryExpression=ka;});var Wn=x(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.CharacterSet=void 0;var Bn=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,n)=>{for(let r=t.charCodeAt(0);r<=n.charCodeAt(0);++r)this.Add(String.fromCharCode(r));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let n of t)this.Add(n);else for(let n of t.set)this.Add(n);return this},e&&this.AddCharacters(e);}};Xi.CharacterSet=Bn;Bn.FromRange=(i,e)=>new Bn().AddRange(i,e);});var Yu=x(Yi=>{Object.defineProperty(Yi,"__esModule",{value:true});Yi.CharacterRange=void 0;var Xu=Wn(),jn=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Xu.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let r=this.start.charCodeAt(0),a;r<=this.end.charCodeAt(0);r+=1)a=String.fromCharCode(r),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},n instanceof Xu.CharacterSet)this._excludes=n.set;else for(let r of n)this._excludes.add(r);}get start(){return this._start}get end(){return this._end}};Yi.CharacterRange=jn;jn.Define=(i,e,t=[])=>new jn(i,e,t);});var Zi=x(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.ChoicePoint=void 0;var Np=xe(),Ip=Ae(),La=pe(),Ba=class extends Np.InkObject{constructor(e=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, La.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, La.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new Ip.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, La.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};Qi.ChoicePoint=Ba;});var kt=x(er=>{Object.defineProperty(er,"__esModule",{value:true});er.PushPopType=void 0;var Qu;(function(i){i[i.Tunnel=0]="Tunnel",i[i.Function=1]="Function",i[i.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Qu||(er.PushPopType=Qu={}));});var qn=x(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.Pointer=void 0;var Vp=Ae(),Wa=class i{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new Vp.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new i(this.container,this.index)}static StartOf(e){return new i(e,0)}static get Null(){return new i(null,-1)}};tr.Pointer=Wa;});var et=x(ir=>{Object.defineProperty(ir,"__esModule",{value:true});ir.Divert=void 0;var kp=Ae(),Rp=kt(),Lp=Nt(),Bp=xe(),ja=qn(),Zu=ie(),nr=pe(),qa=class i extends Bp.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=ja.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, nr.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, nr.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, nr.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof Zu.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=ja.Pointer.StartOf(e instanceof Zu.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new kp.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=ja.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof e<"u"&&(this.pushesToStack=true,this.stackPushType=e);}Equals(e){let t=e;return t instanceof i&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, nr.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new Lp.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==Rp.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};ir.Divert=qa;});var ct=x(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.SymbolType=void 0;var eh;(function(i){i[i.Knot=0]="Knot",i[i.List=1]="List",i[i.ListItem=2]="ListItem",i[i.Var=3]="Var",i[i.SubFlowAndWeave=4]="SubFlowAndWeave",i[i.Arg=5]="Arg",i[i.Temp=6]="Temp";})(eh||(rr.SymbolType=eh={}));});var vt=x(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.VariableAssignment=void 0;var Wp=xe(),Ma=class extends Wp.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};sr.VariableAssignment=Ma;});var an=x(or=>{Object.defineProperty(or,"__esModule",{value:true});or.Choice=void 0;var jp=Zi(),ar=ie(),St=fe(),Ga=et(),th=ee(),qp=Q(),Mp=ct(),nh=vt(),$a=class extends qp.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,n){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new ar.Container,this._runtimeChoice=new jp.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(St.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new th.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let r=new nh.VariableAssignment("$r",true);this._outerContainer.AddContent(r),this._outerContainer.AddContent(St.ControlCommand.BeginString()),this._divertToStartContentOuter=new Ga.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Ga.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new ar.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(St.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(St.ControlCommand.BeginString());let r=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(r),this._outerContainer.AddContent(St.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(St.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new ar.Container,this.startContent){this._returnToR2=new th.DivertTargetValue,this._innerContentContainer.AddContent(St.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(St.ControlCommand.EvalEnd());let r=new nh.VariableAssignment("$r",true);this._innerContentContainer.AddContent(r),this._divertToStartContentInner=new Ga.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new ar.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let r=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(r);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=e,this.choiceOnlyContent=t,this.innerContent=n,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(e){var t;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Mp.SymbolType.SubFlowAndWeave);}};or.Choice=$a;});var ih=x(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.StringParserElement=void 0;var lr=class i{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{i._uniqueIdCounter++,this.uniqueId=i._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};ur.StringParserElement=lr;lr._uniqueIdCounter=1e3;});var sh=x(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.StringParserState=void 0;var rh=ih(),Ja=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new rh.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(t),n.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],n=this._stack[this._numElements-1];t.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new rh.StringParserElement;this._numElements=1;}};hr.StringParserState=Ja;});var za=x(Rt=>{Object.defineProperty(Rt,"__esModule",{value:true});Rt.StringParser=Rt.ParseSuccess=void 0;var Ha=Wn(),Gp=sh();Rt.ParseSuccess=Symbol("ParseSuccessStruct");var Mn=class i{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=n=>(this.state.Pop(n),null),this.CancelRule=n=>{this.state.Pop(n);},this.SucceedRule=(n,r=null)=>{let a=this.state.Peek(n),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(r,s,a),this.state.Squash();let o=r;return o===null&&(o=i.ParseSuccess),o},this.Expect=(n,r=null,a=null)=>{let s=this.ParseObject(n);if(s===null){r===null&&(r=n.name);let o,l=this.LineRemainder();l===null||l.length===0?o="end of line":o=`'${l}'`,this.Error(`Expected ${r} but saw ${o}`),a!==null&&(s=a());}return s},this.Error=(n,r=false)=>{this.ErrorOnLine(n,this.lineIndex+1,r);},this.ErrorWithParsedObject=(n,r,a=false)=>{this.ErrorOnLine(n,r.debugMetadata?r.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(n,r,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,r-1,a);else throw new Error(`${s} on line ${r}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
5
5
  \r`)),this.SetFlag=(n,r)=>{r?this.state.customFlags|=n:this.state.customFlags&=~n;},this.GetFlag=n=>!!(this.state.customFlags&n),this.ParseObject=n=>{let r=this.BeginRule(),a=this.state.stackHeight,s=n();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return s===null?this.FailRule(r):(this.SucceedRule(r,s),s)},this.Parse=n=>{let r=this.BeginRule(),a=n();return a===null?(this.FailRule(r),null):(this.SucceedRule(r,a),a)},this.OneOf=n=>{for(let r of n){let a=this.ParseObject(r);if(a!==null)return a}return null},this.OneOrMore=n=>{let r=[],a=null;do a=this.ParseObject(n),a!==null&&r.push(a);while(a!==null);return r.length>0?r:null},this.Optional=n=>()=>{let r=this.ParseObject(n);return r===null?i.ParseSuccess:r},this.Exclude=n=>()=>this.ParseObject(n)&&i.ParseSuccess,this.OptionalExclude=n=>()=>(this.ParseObject(n),i.ParseSuccess),this.String=n=>()=>this.ParseString(n),this.TryAddResultToList=(n,r,a=true)=>{if(n!==i.ParseSuccess){if(a&&Array.isArray(n)){let s=n;if(s!==null){for(let o of s)r.push(o);return}}r.push(n);}},this.Interleave=(n,r,a=null,s=true)=>{let o=this.BeginRule(),l=[],u=this.ParseObject(n);if(u===null)return this.FailRule(o);this.TryAddResultToList(u,l,s);let h=null,c=null;do{if(a!==null&&this.Peek(a)!==null||(h=this.ParseObject(r),h===null))break;if(this.TryAddResultToList(h,l,s),c=null,h!==null){if(c=this.ParseObject(n),c===null)break;this.TryAddResultToList(c,l,s);}}while((h!==null||c!==null)&&!(h===i.ParseSuccess&&c==i.ParseSuccess)&&this.remainingLength>0);return l.length===0?this.FailRule(o):this.SucceedRule(o,l)},this.ParseString=n=>{if(n.length>this.remainingLength)return null;let r=this.BeginRule(),a=this.index,s=this.characterInLineIndex,o=this.lineIndex,l=true;for(let u=0;u<n.length;u+=1){let h=n[u];if(this._chars[a]!==h){l=false;break}h===`
6
6
  `&&(o++,s=-1),a++,s++;}return this.index=a,this.characterInLineIndex=s,this.lineIndex=o,l?this.SucceedRule(r,n):this.FailRule(r)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){let n=this._chars[this.index];return n===`
7
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,r=-1)=>this.ParseCharactersFromString(n,false,r),this.ParseUntilCharactersFromCharSet=(n,r=-1)=>this.ParseCharactersFromCharSet(n,false,r),this.ParseCharactersFromString=(n,r=-1,a=-1)=>{let s=new lo.CharacterSet(n);return typeof r=="number"?this.ParseCharactersFromCharSet(s,true,r):this.ParseCharactersFromCharSet(s,r,a)},this.ParseCharactersFromCharSet=(n,r=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,h=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===r&&h<a;)this._chars[o]===`
7
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,r=-1)=>this.ParseCharactersFromString(n,false,r),this.ParseUntilCharactersFromCharSet=(n,r=-1)=>this.ParseCharactersFromCharSet(n,false,r),this.ParseCharactersFromString=(n,r=-1,a=-1)=>{let s=new Ha.CharacterSet(n);return typeof r=="number"?this.ParseCharactersFromCharSet(s,true,r):this.ParseCharactersFromCharSet(s,r,a)},this.ParseCharactersFromCharSet=(n,r=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,h=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===r&&h<a;)this._chars[o]===`
8
8
  `&&(u+=1,l=-1),o+=1,l+=1,h+=1;return this.index=o,this.characterInLineIndex=l,this.lineIndex=u,this.index>s?this._chars.slice(s,this.index).join(""):null},this.Peek=n=>{let r=this.BeginRule(),a=n();return this.CancelRule(r),a},this.ParseInt=()=>{let n=this.index,r=this.characterInLineIndex,a=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");let s=this.ParseCharactersFromCharSet(i.numbersCharacterSet);if(s===null)return this.index=n,this.characterInLineIndex=r,null;let o;return Number.isNaN(Number(s))?(this.Error("Failed to read integer value: "+s+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(o=Number(s),a?-o:o)},this.ParseFloat=()=>{let n=this.index,r=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let s=this.ParseCharactersFromCharSet(i.numbersCharacterSet);return +`${a}.${s}`}return this.index=n,this.characterInLineIndex=r,null},this.ParseNewline=()=>{let n=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
9
9
  `)===null?this.FailRule(n):this.SucceedRule(n,`
10
- `)};let t=this.PreProcessInputString(e);this.state=new wf.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,n=null){let r=this.BeginRule(),a=new lo.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let s="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(s+=l),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(t!==null&&t.set.has(u)){s+=u,u===`
11
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(r,String(s)):this.FailRule(r)}};Kt.StringParser=ei;ei.ParseSuccess=Kt.ParseSuccess;ei.numbersCharacterSet=new lo.CharacterSet("0123456789");});var Ah=w(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.CommentEliminator=void 0;var ho=Yn(),xf=uo(),co=class extends xf.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new ho.CharacterSet(`/\r
12
- `),this._commentBlockEndCharacter=new ho.CharacterSet("*"),this._newlineCharacters=new ho.CharacterSet(`
10
+ `)};let t=this.PreProcessInputString(e);this.state=new Gp.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,n=null){let r=this.BeginRule(),a=new Ha.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let s="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(s+=l),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(t!==null&&t.set.has(u)){s+=u,u===`
11
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(r,String(s)):this.FailRule(r)}};Rt.StringParser=Mn;Mn.ParseSuccess=Rt.ParseSuccess;Mn.numbersCharacterSet=new Ha.CharacterSet("0123456789");});var ah=x(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.CommentEliminator=void 0;var Ua=Wn(),$p=za(),Ka=class extends $p.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Ua.CharacterSet(`/\r
12
+ `),this._commentBlockEndCharacter=new Ua.CharacterSet("*"),this._newlineCharacters=new Ua.CharacterSet(`
13
13
  \r`),this.Process=()=>{let e=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return e!==null?e.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let e=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return e!==null?e.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>this.ParseString("//")===null?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(this.ParseString("/*")===null)return null;let e=this.lineIndex,t=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),t!=null?`
14
- `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};Ar.CommentEliminator=co;});var xr=w(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.Conditional=void 0;var _f=ae(),wh=ye(),Of=ee(),po=class extends Of.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new _f.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let r of this.branches){let a=r.runtimeObject;n.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(wh.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=wh.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=t;}super.ResolveReferences(e);}};wr.Conditional=po;});var Vt=w(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.Text=void 0;var Pf=ee(),Tf=ne(),fo=class extends Pf.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new Tf.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};_r.Text=fo;});var Pr=w(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.ConstantDeclaration=void 0;var Ff=ee(),Nf=bt(),go=class extends Ff.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,Nf.SymbolType.Var);}};Or.ConstantDeclaration=go;});var vn=w(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.FlowLevel=void 0;var xh;(function(i){i[i.Story=0]="Story",i[i.Knot=1]="Knot",i[i.Stitch=2]="Stitch",i[i.WeavePoint=3]="WeavePoint";})(xh||(Tr.FlowLevel=xh={}));});var ti=w(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.Gather=void 0;var Vf=ae(),If=ee(),kf=bt(),mo=class extends If.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let n=new Vf.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let r of this.content)n.AddContent(r.runtimeObject);return n},this.toString=()=>{var n,r;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((r=this.identifier)===null||r===void 0?void 0:r.name)+")":"gather"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,kf.SymbolType.SubFlowAndWeave);}};Fr.Gather=mo;});var Xt=w(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.Path=void 0;var Nr=z(),_h=dt(),Sn=vn(),Rf=Yt(),Co=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Sn.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(Nr.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Sn.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let r=this.ResolveBaseTarget(n);return r===null?null:this.components.length>1?this.ResolveTailComponents(r):r},this.ResolveBaseTarget=n=>{let r=this.firstComponent,a=n;for(;a;){let s=a===n,o=this.GetChildFromContext(a,r,null,s);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=n=>{let r=n;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let s=this.components[a].name,o,l=(0, Nr.asOrNull)(r,_h.FlowBase);if(l!==null?o=l.flowLevel+1:o=Sn.FlowLevel.WeavePoint,r=this.GetChildFromContext(r,s,o),r===null)break}return r},this.GetChildFromContext=(n,r,a,s=false)=>{let o=a===null,l=(0, Nr.asOrNull)(n,Rf.Weave);if(r&&l!==null&&(o||a===Sn.FlowLevel.WeavePoint))return l.WeavePointNamed(r);let u=(0, Nr.asOrNull)(n,_h.FlowBase);if(r&&u!==null){let h=s||u.flowLevel===Sn.FlowLevel.Knot;return u.ContentWithNameAtLevel(r,a,h)}return null},Object.values(Sn.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};Vr.Path=Co;});var So=w(Ir=>{Object.defineProperty(Ir,"__esModule",{value:true});Ir.ReturnType=void 0;var Lf=ee(),Bf=ae(),yo=ye(),Wf=zt(),vo=class extends Lf.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new Bf.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(yo.ControlCommand.EvalStart()),t.AddContent(new Wf.Void),t.AddContent(yo.ControlCommand.EvalEnd())),t.AddContent(yo.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Ir.ReturnType=vo;});var ni=w(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.ClosestFlowBase=void 0;function jf(i){let e=i.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}kr.ClosestFlowBase=jf;});var Lr=w(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.Identifier=void 0;var Eo=class i{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new i("DONE")}};Rr.Identifier=Eo;});var dt=w(Br=>{Object.defineProperty(Br,"__esModule",{value:true});Br.FlowBase=void 0;var qf=yn(),bo=bn(),Mf=En(),pt=vn(),Gf=ti(),$f=ee(),Jf=Xt(),Hf=So(),zf=ae(),Uf=ct(),Kf=Ft(),Do=bt(),Xf=Yt(),Yf=ni(),Qf=Lr(),Oh=z(),Ao=class i extends $f.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,n=null,r=false,a=false){super(),this.isFunction=r,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(s,o)=>{var l,u;let h=[],c=[];this._subFlowsByName=new Map;for(let f of s){let y=(0, Oh.asOrNull)(f,i);y?(this._firstChildFlow===null&&(this._firstChildFlow=y),c.push(f),!((l=y.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=y.identifier)===null||u===void 0?void 0:u.name,y)):h.push(f);}o&&h.push(new Gf.Gather(null,1),new bo.Divert(new Jf.Path(Qf.Identifier.Done())));let p=[];return h.length>0&&(this._rootWeave=new Xf.Weave(h,0),p.push(this._rootWeave)),c.length>0&&p.push(...c),p},this.ResolveVariableWithName=(s,o)=>{var l;let u={},h=o===null?this:(0, Yf.ClosestFlowBase)(o);if(h){if(h.args!==null){for(let c of h.args)if(((l=c.identifier)===null||l===void 0?void 0:l.name)===s)return u.found=true,u.isArgument=true,u.ownerFlow=h,u}if(h!==this.story&&h.variableDeclarations.has(s))return u.found=true,u.ownerFlow=h,u.isTemporary=true,u}return this.story.variableDeclarations.has(s)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let l=this.variableDeclarations.get(o),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${u}`,s,false);return}this.variableDeclarations.set(s.variableName,s);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,s]of this._subFlowsByName)s.hasOwnProperty("ResolveWeavePointNaming")&&s.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var s;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===pt.FlowLevel.Knot||this.flowLevel===pt.FlowLevel.Stitch)&&(o=this.Find(Hf.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let l=new zf.Container;l.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(l.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(l);let u=0;for(;this.content!==null&&u<this.content.length;){let h=this.content[u];if(h instanceof i){let c=h,p=c.runtimeObject;u===0&&!c.hasParameters&&this.flowLevel===pt.FlowLevel.Knot&&(this._startingSubFlowDivert=new Uf.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=p);let f=p,y=l.namedContent.get(f.name)||null;if(y){let C=`${this.GetType()} already contains flow named '${f.name}' (at ${y.debugMetadata})`;this.Error(C,c);}l.AddToNamedContentOnly(f);}else h&&l.AddContent(h.runtimeObject);u+=1;}return this.flowLevel!==pt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let l=this.args.length-1;l>=0;--l){let u=((o=this.args[l].identifier)===null||o===void 0?void 0:o.name)||null,h=new Kf.VariableAssignment(u,true);s.AddContent(h);}},this.ContentWithNameAtLevel=(s,o=null,l=false)=>{var u;if((o===this.flowLevel||o===null)&&s===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===pt.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(s),c))return c;if(o===pt.FlowLevel.WeavePoint)return l?this.DeepSearchForAnyLevelContent(s):null}if(o!==null&&o<this.flowLevel)return null;let h=this._subFlowsByName.get(s)||null;return h&&(o===null||o===h.flowLevel)?h:l?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,pt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(s,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==pt.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[l,u]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${l}' within the function '${this.identifier}'`,u);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(bo.Divert)();for(let l of s)!l.isFunctionCall&&!(l.parent instanceof Mf.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(qf.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},this.WarningInTermination=s=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";s.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let l=(0, Oh.asOrNull)(s,bo.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let r of this.args)e.CheckForNamingCollisions(this,r.identifier,Do.SymbolType.Arg,"argument");for(let r=0;r<this.args.length;r+=1)for(let a=r+1;a<this.args.length;a+=1)((t=this.args[r].identifier)===null||t===void 0?void 0:t.name)==((n=this.args[a].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[r].identifier}'`);}if(this.flowLevel!==pt.FlowLevel.Story){let r=this.flowLevel===pt.FlowLevel.Knot?Do.SymbolType.Knot:Do.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,r);}}};Br.FlowBase=Ao;});var jr=w(Wr=>{Object.defineProperty(Wr,"__esModule",{value:true});Wr.ContentList=void 0;var Zf=ae(),eg=ee(),tg=Vt(),ng=z(),wo=class extends eg.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let r=(0, ng.asOrNull)(this.content[n],tg.Text);if(r===null)break;if(r.text=r.text.replace(new RegExp(/[ \t]/g),""),r.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new Zf.Container;if(this.content!==null)for(let r of this.content){let a=r.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};Wr.ContentList=wo;});var Dn=w(qr=>{Object.defineProperty(qr,"__esModule",{value:true});qr.VariableReference=void 0;var ig=Re(),rg=ke(),xo=class extends ig.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new rg.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};qr.VariableReference=xo;});var An=w(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.VariableReference=void 0;var sg=jr(),ag=Ue(),Ph=dt(),og=Xt(),lg=Dn(),ug=Yt(),hg=Lr(),Th=z(),_o=class extends ag.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(Th.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new hg.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=t=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new lg.VariableReference(this.name),this.path.length===1||this.path.length===2){let r="",a="";this.path.length===1?r=this.path[0]:(a=this.path[0],r=this.path[1]),this.story.ResolveListItem(a,r,this)&&(this.isListItemReference=true);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new og.Path(this.pathIdentifiers),n=t.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let r=(0, Th.asOrNull)(n,Ph.FlowBase);r&&r.isFunction&&(this.parent instanceof ug.Weave||this.parent instanceof sg.ContentList||this.parent instanceof Ph.FlowBase)&&this.Warning(`'${r.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${r.identifier}()`);return}if(this.path.length>1){let r=`Could not find target for read count: ${t}`;this.path.length<=2&&(r+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(r);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};Mr.VariableReference=_o;});var ii=w(Hr=>{Object.defineProperty(Hr,"__esModule",{value:true});Hr.FunctionCall=void 0;var ft=ye(),cg=bn(),dg=En(),pg=Ue(),fg=Be(),gg=ne(),$r=ht(),Fh=ar(),mg=Xt(),Cg=ne(),yg=An(),Gr=z(),Jr=class i extends pg.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(e,t){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=n=>{let r=this.story.ResolveList(this.name),a=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),n.AddContent(ft.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(ft.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, Gr.asOrNull)(this.args[0],dg.DivertTarget),o=(0, Gr.asOrNull)(this.args[0],yg.VariableReference);if(this.args.length!==1||s===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}s?(this._divertTargetToCount=s,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(ft.ControlCommand.TurnsSince()):n.AddContent(ft.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let s=0;s<this.args.length;s+=1){let o=(0, Gr.asOrNull)(this.args[s],Fh.NumberExpression);if(o&&!o.isInt()){let l=s===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[s].GenerateIntoContainer(n);}n.AddContent(ft.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, Gr.asOrNull)(this.args[0],Fh.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(ft.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let s=0;s<this.args.length;s+=1)this.args[s].GenerateIntoContainer(n);n.AddContent(ft.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(n),n.AddContent(ft.ControlCommand.ListRandom());else if($r.NativeFunctionCall.CallExistsWithName(this.name)){let s=$r.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${i.name} should take ${s.numberOfParameters} parameter`;s.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(n);n.AddContent($r.NativeFunctionCall.CallWithName(this.name));}else if(r!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)n.AddContent(new Cg.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(ft.ControlCommand.ListFromInt());else {let s=new fg.InkList;s.SetInitialOriginName(this.name),n.AddContent(new gg.ListValue(s));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(ft.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new cg.Divert(new mg.Path(e),t),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,n=t.runtimeDivert.variableDivertName!=null;if(n){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let r=t.targetContent;if(r===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!r.containerForCounting)throw new Error;r.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${i.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Hr.FunctionCall=Jr;Jr.IsBuiltIn=i=>$r.NativeFunctionCall.CallExistsWithName(i)?true:i==="CHOICE_COUNT"||i==="TURNS_SINCE"||i==="TURNS"||i==="RANDOM"||i==="SEED_RANDOM"||i==="LIST_VALUE"||i==="LIST_RANDOM"||i==="READ_COUNT";});var Po=w(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.MultipleConditionExpression=void 0;var vg=Ue(),Sg=ht(),Oo=class extends vg.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let n=true;for(let r of this.subExpressions)r.GenerateIntoContainer(t),n||t.AddContent(Sg.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};zr.MultipleConditionExpression=Oo;});var En=w(Ur=>{Object.defineProperty(Ur,"__esModule",{value:true});Ur.DivertTarget=void 0;var Eg=Qa(),bg=yn(),Dg=xr(),Ag=Vo(),wg=ne(),To=Ue(),xg=dt(),Nh=ii(),_g=Po(),Vh=An(),Fo=z(),No=class i extends To.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new wg.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, Fo.asOrNull)(t,i);if(!n||!this.divert.target||!n.divert.target)return false;let r=this.divert.target.dotSeparatedComponents,a=n.divert.target.dotSeparatedComponents;return r===a},this.divert=this.AddContent(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof To.Expression;){let r=false,a=false,s=t.parent;if(s instanceof Eg.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?r=true:(o.leftExpression instanceof i||o.leftExpression instanceof Vh.VariableReference)&&(o.rightExpression instanceof i||o.rightExpression instanceof Vh.VariableReference)||(r=true),a=true;}else if(s instanceof Nh.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(r=true),a=true;}else (s instanceof To.Expression||s instanceof _g.MultipleConditionExpression||s instanceof bg.Choice&&s.condition===t||s instanceof Dg.Conditional||s instanceof Ag.ConditionalSingleBranch)&&(r=true,a=true);if(r&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;t=s;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let n=this.divert.targetContent;if(n!==null){let r=n.containerForCounting;if(r!==null){let s=(0, Fo.asOrNull)(this.parent,Nh.FunctionCall);s&&s.isTurnsSince||(r.visitsShouldBeCounted=true),r.turnIndexShouldBeCounted=true;}let a=(0, Fo.asOrNull)(n,xg.FlowBase);if(a!=null&&a.args!==null)for(let s of a.args)s.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${s.identifier}').`);}}};Ur.DivertTarget=No;});var bn=w(Kr=>{Object.defineProperty(Kr,"__esModule",{value:true});Kr.Divert=void 0;var Og=ae(),ri=ye(),Pg=ct(),Io=En(),ko=dt(),Tg=ii(),Fg=ee(),Ih=Xt(),Ng=ke(),kh=Ut(),Vg=ne(),Rh=An(),Ig=ni(),si=z(),Ro=class extends Fg.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return ri.ControlCommand.End();if(this.isDone)return ri.ControlCommand.Done();this.runtimeDivert=new Pg.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let n=this.args!==null&&this.args.length>0;if(n||this.isFunctionCall||this.isTunnel||this.isThread){let r=new Og.Container;if(n){this.isFunctionCall||r.AddContent(ri.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let s=0;s<this.args.length;++s){let o=this.args[s],l=null;if(a&&s<a.length&&(l=a[s]),l&&l.isByReference){let u=(0, si.asOrNull)(o,Rh.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let h=new Ih.Path(u.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let p=new Vg.VariablePointerValue(u.name);r.AddContent(p);}else o.GenerateIntoContainer(r);}this.isFunctionCall||r.AddContent(ri.ControlCommand.EvalEnd());}return this.isThread?r.AddContent(ri.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?kh.PushPopType.Function:kh.PushPopType.Tunnel),r.AddContent(this.runtimeDivert),r}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let r=(0, si.asOrNull)((0, Ig.ClosestFlowBase)(this),ko.FlowBase);if(r){let a=r.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});s&&!s.isDivertTarget&&this.Error(`Since '${s.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${s.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let r=(0, si.asOrNull)(this.targetContent,ko.FlowBase);if(n===0&&(r===null||!r.hasParameters))return;if(r===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(r!==null&&(r.args===null||!r.args&&n>0)){this.Error(`target (${r.name}) doesn't take parameters`);return}else if(this.parent instanceof Io.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=r.args.length;if(a!==n){let s;n===0?s="but there weren't any passed to it":n<a?s=`but only got ${n}`:s=`but got ${n}`,this.Error(`to '${r.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=r.args[s],l=this.args[s];if(o.isDivertTarget){let u=(0, si.asOrNull)(l,Rh.VariableReference);if(!(l instanceof Io.DivertTarget)&&u===null)this.Error(`Target '${r.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${l}`,l);else if(u){let h=new Ih.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(r===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let r=this.target?this.target.firstComponent:null,a=n.externals.get(r);if(!a)throw new Error("external not found");let s=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==s&&this.Error(`incorrect number of arguments sent to external function '${r}'. Expected ${s} but got ${o}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, si.asOrNull)(this.targetContent,ko.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof Io.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let n=this.targetContent!==null,r=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(r=Tg.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),r||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new Ng.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!r&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,n=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,n):super.Error(`Divert ${e}`,t,n);}};Kr.Divert=Ro;});var Lh=w(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.GatherPointToResolve=void 0;var Lo=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};Xr.GatherPointToResolve=Lo;});var Bh=w(Yr=>{Object.defineProperty(Yr,"__esModule",{value:true});Yr.SequenceDivertToResolve=void 0;var Bo=class{constructor(e,t){this.divert=e,this.targetContent=t;}};Yr.SequenceDivertToResolve=Bo;});var Wo=w(Qr=>{Object.defineProperty(Qr,"__esModule",{value:true});Qr.SequenceType=void 0;var Wh;(function(i){i[i.Stopping=1]="Stopping",i[i.Cycle=2]="Cycle",i[i.Shuffle=4]="Shuffle",i[i.Once=8]="Once";})(Wh||(Qr.SequenceType=Wh={}));});var Mo=w(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.Sequence=void 0;var jh=ae(),nt=ye(),jo=ct(),ai=ne(),Zr=ht(),kg=ee(),Rg=Bh(),es=Wo(),Lg=Yt(),qo=class extends kg.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new jh.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(nt.ControlCommand.EvalStart()),n.AddContent(nt.ControlCommand.VisitIndex());let r=(this.sequenceType&es.SequenceType.Once)>0,a=(this.sequenceType&es.SequenceType.Cycle)>0,s=(this.sequenceType&es.SequenceType.Stopping)>0,o=(this.sequenceType&es.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(r&&(l+=1),s||r?(n.AddContent(new ai.IntValue(l-1)),n.AddContent(Zr.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new ai.IntValue(this.sequenceElements.length)),n.AddContent(Zr.NativeFunctionCall.CallWithName("%"))),o){let h=nt.ControlCommand.NoOp();if(r||s){let p=s?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(nt.ControlCommand.Duplicate()),n.AddContent(new ai.IntValue(p)),n.AddContent(Zr.NativeFunctionCall.CallWithName("=="));let f=new jo.Divert;f.isConditional=true,n.AddContent(f),this.AddDivertToResolve(f,h);}let c=this.sequenceElements.length;s&&(c-=1),n.AddContent(new ai.IntValue(c)),n.AddContent(nt.ControlCommand.SequenceShuffleIndex()),(r||s)&&n.AddContent(h);}n.AddContent(nt.ControlCommand.EvalEnd());let u=nt.ControlCommand.NoOp();for(let h=0;h<l;h+=1){n.AddContent(nt.ControlCommand.EvalStart()),n.AddContent(nt.ControlCommand.Duplicate()),n.AddContent(new ai.IntValue(h)),n.AddContent(Zr.NativeFunctionCall.CallWithName("==")),n.AddContent(nt.ControlCommand.EvalEnd());let c=new jo.Divert;c.isConditional=true,n.AddContent(c);let p;h<this.sequenceElements.length?p=this.sequenceElements[h].runtimeObject:p=new jh.Container,p.name=`s${h}`,p.InsertContent(nt.ControlCommand.PopEvaluatedValue(),0);let f=new jo.Divert;p.AddContent(f),n.AddToNamedContentOnly(p),this.AddDivertToResolve(c,p),this.AddDivertToResolve(f,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,r)=>{this._sequenceDivertsToResolve.push(new Rg.SequenceDivertToResolve(n,r));},this.sequenceType=t,this.sequenceElements=[];for(let n of e){let r=n.content,a=null;r===null||r.length===0?a=n:a=new Lg.Weave(r),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};ts.Sequence=qo;});var $o=w(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.TunnelOnwards=void 0;var Bg=ae(),oi=ye(),Wg=ct(),jg=ne(),qg=ee(),Mg=zt(),Gg=z(),$g=Dn(),Go=class extends qg.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new Bg.Container;if(e.AddContent(oi.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(s==-1&&u.commandType===oi.ControlCommand.CommandType.EvalStart?s=l:u.commandType===oi.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=s+1;l<o;l+=1){let u=n.content[l];u.parent=null,e.AddContent(n.content[l]);}}}let r=(0, Gg.asOrNull)(t,Wg.Divert);if(r!=null&&r.hasVariableTarget){let a=new $g.VariableReference(r.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new jg.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new Mg.Void);return e.AddContent(oi.ControlCommand.EvalEnd()),e.AddContent(oi.ControlCommand.PopTunnel()),e},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};ns.TunnelOnwards=Go;});var zo=w(is=>{Object.defineProperty(is,"__esModule",{value:true});is.ListDefinition=void 0;var Jo=Be(),Ho=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let n=new Jo.InkListItem(this.name,e);this._items.set(n.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?false:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[n,r]of this._itemNameToValues)if(r==e)return t=new Jo.InkListItem(this.name,n),{result:t,exists:true};return t=Jo.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(e.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};is.ListDefinition=Ho;});var ss=w(rs=>{Object.defineProperty(rs,"__esModule",{value:true});rs.ListDefinition=void 0;var Jg=Be(),Hg=Be(),zg=zo(),Ug=ne(),Kg=ee(),Xg=bt(),Uo=class extends Kg.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let n of this.itemDefinitions)t.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):t.set(n.name,n.seriesValue);return new zg.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,r;let a=new Jg.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new Hg.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((r=this.identifier)===null||r===void 0?void 0:r.name)||""),new Ug.ListValue(a)};let t=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(t=n.explicitValue),n.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,Xg.SymbolType.List);}};rs.ListDefinition=Uo;});var Xo=w(as=>{Object.defineProperty(as,"__esModule",{value:true});as.VariableAssignment=void 0;var Yg=ae(),Qg=ni(),Zg=ss(),em=ee(),qh=bt(),tm=Ft(),nm=An(),im=z(),Ko=class extends em.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:n,listDef:r,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, Qg.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new Yg.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new tm.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!n,r instanceof Zg.ListDefinition?(this.listDefinition=this.AddContent(r),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?qh.SymbolType.Var:qh.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, im.asOrNull)(this.expression,nm.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};as.VariableAssignment=Ko;});var Yt=w(us=>{Object.defineProperty(us,"__esModule",{value:true});us.Weave=void 0;var Mh=$i(),Xe=yn(),os=xr(),rm=Pr(),sm=ae(),ls=bn(),am=ct(),om=En(),lm=dt(),gt=ti(),um=Lh(),hm=ee(),Yo=Mo(),cm=Vt(),dm=$o(),pm=Xo(),Ye=z(),Qo=class i extends hm.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let n=this.content.length-1;n>=0;--n){e=this.content[n];let r=(0, Ye.asOrNull)(e,cm.Text);if(!(r&&r.text===`
15
- `)&&!this.IsGlobalDeclaration(e))break}let t=(0, Ye.asOrNull)(e,i);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var n,r,a;let s=[...this.FindAll(gt.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(Xe.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof gt.Gather?"gather":"choice",h=l;this.Error(`A ${u} with the same label name '${o.name}' already exists in this context on line ${h.debugMetadata?h.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((r=o.identifier)===null||r===void 0)&&r.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;n<this.content.length;){let r=this.content[n];if(r instanceof Xe.Choice||r instanceof gt.Gather){let s=r.indentationDepth-1;if(s>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let c=(0, Ye.asOrNull)(this.content[n],Xe.Choice)||(0, Ye.asOrNull)(this.content[n],gt.Gather);if(c!==null&&c.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let l=n-o,u=this.content.slice(o,o+l);this.content.splice(o,l);let h=new i(u,s);this.InsertContent(o,h),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let r of n)if(r instanceof Xe.Choice||r instanceof gt.Gather)return r.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new sm.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof Xe.Choice||n instanceof gt.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof i){let r=n;this.AddRuntimeForNestedWeave(r),this.gatherPointsToResolve.splice(0,0,...r.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let r=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),r){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let s of this.looseEnds){let o=s;if(o instanceof gt.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof ls.Divert)l=o.runtimeObject;else {l=new am.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new um.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof gt.Gather)this.AddRuntimeForGather(n);else if(n instanceof Xe.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof gt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let r=n;if(this.currentContainer.AddContent(r.runtimeObject),!r.innerContentContainer)throw new Error;r.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(r.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, Ye.asOrNull)(n,Xe.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=n;},this.AddRuntimeForNestedWeave=n=>{this.AddGeneralRuntimeContent(n.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=n=>{if(n!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(n);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let n=null,r=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, Ye.asOrNull)(s,i);o&&(!a&&n===null&&(n=o),a&&r===null&&(r=o)),(s instanceof Yo.Sequence||s instanceof os.Conditional)&&(a=true);}if(!(n===null&&r===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],l=false;if(a){if(o instanceof Xe.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof Xe.Choice)){let u=n||r;u!==null&&(u.ReceiveLooseEnd(o),l=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(o),l=true;l&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let r=this.namedWeavePoints.get(n);return r||null},this.IsGlobalDeclaration=n=>{let r=(0, Ye.asOrNull)(n,pm.VariableAssignment);return !!(r&&r.isGlobalDeclaration&&r.isDeclaration||(0, Ye.asOrNull)(n,rm.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let r=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||r.push(l);let s=(0, Ye.asOrNull)(a.parent,i);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let l=o+1;l<s.content.length;l+=1){let u=s.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof Xe.Choice||u instanceof gt.Gather||u instanceof i)break;r.push(u);}}return r},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof Mh.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let s=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(s,a,n);}else {for(let a of this.content)if(a instanceof Xe.Choice||a instanceof ls.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let r=null;for(let s=n.parent;s!==null;s=s.parent)if(s instanceof Yo.Sequence||s instanceof os.Conditional){r=(0, Ye.asOrNull)(s,os.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";r!==null&&r.FindAll(Xe.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,r,a)=>{let s=false,o=r;for(let l of n){if(l.Find(ls.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof om.DivertTarget))!==null&&(s=true),l.Find(dm.TunnelOnwards)()!=null){s=true;break}o=l;}if(!s){if(o instanceof Mh.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return true;for(let r=n.content.length-1;r>=0;--r){let a=(0, Ye.asOrNull)(n.content[r],ls.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let r of this.ancestry){let a=(0, Ye.asOrNull)(r,lm.FlowBase);if(a)n.push(a);else break}for(let[r,a]of this.namedWeavePoints)for(let s of n){let o=s.ContentWithNameAtLevel(r);if(o&&o!==a){let l=`${a.GetType()} '${r}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(l,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof Yo.Sequence||n instanceof os.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};us.Weave=Qo;});var Vo=w(cs=>{Object.defineProperty(cs,"__esModule",{value:true});cs.ConditionalSingleBranch=void 0;var Gh=ae(),hs=ye(),$h=ct(),fm=ee(),gm=ht(),mm=ne(),Cm=Vt(),ym=Yt(),vm=z(),Zo=class extends fm.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let r of this._innerWeave.content){let a=(0, vm.asOrNull)(r,Cm.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new Gh.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(hs.ControlCommand.Duplicate()),this._conditionalDivert=new $h.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let r=this.ownExpression!==null;r&&t.AddContent(hs.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(gm.NativeFunctionCall.CallWithName("==")),r&&t.AddContent(hs.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new mm.StringValue(`
16
- `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(hs.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new $h.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new Gh.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new ym.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};cs.ConditionalSingleBranch=Zo;});var Hh=w(ds=>{Object.defineProperty(ds,"__esModule",{value:true});ds.CustomFlags=void 0;var Jh;(function(i){i[i.ParsingString=1]="ParsingString",i[i.TagActive=2]="TagActive";})(Jh||(ds.CustomFlags=Jh={}));});var zh=w(ps=>{Object.defineProperty(ps,"__esModule",{value:true});ps.DebugMetadata=void 0;var el=class i{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new i;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumber<e.startLineNumber?(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>e.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<e.endLineNumber?(t.endLineNumber=e.endLineNumber,t.endCharacterNumber=e.endCharacterNumber):(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=Math.max(this.endCharacterNumber,e.endCharacterNumber)),t}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};ps.DebugMetadata=el;});var Uh=w(fs=>{Object.defineProperty(fs,"__esModule",{value:true});fs.ExternalDeclaration=void 0;var Sm=ee(),tl=class extends Sm.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};fs.ExternalDeclaration=tl;});var Kh=w(gs=>{Object.defineProperty(gs,"__esModule",{value:true});gs.FlowDecl=void 0;var nl=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};gs.FlowDecl=nl;});var rl=w(ms=>{Object.defineProperty(ms,"__esModule",{value:true});ms.Wrap=void 0;var Em=ee(),il=class extends Em.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};ms.Wrap=il;});var Xh=w(Cs=>{Object.defineProperty(Cs,"__esModule",{value:true});Cs.Glue=void 0;var bm=rl(),sl=class extends bm.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};Cs.Glue=sl;});var vs=w(ys=>{Object.defineProperty(ys,"__esModule",{value:true});ys.Glue=void 0;var Dm=Re(),al=class extends Dm.InkObject{toString(){return "Glue"}};ys.Glue=al;});var Qh=w(Ss=>{Object.defineProperty(Ss,"__esModule",{value:true});Ss.IncDecExpression=void 0;var Am=jr(),Yh=Ue(),wm=dt(),xm=ht(),_m=ne(),Om=Ft(),Pm=Dn(),Tm=Yt(),ol=class extends Yh.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=r=>{var a,s;r.AddContent(new Pm.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(r):r.AddContent(new _m.IntValue(1)),r.AddContent(xm.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new Om.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),r.AddContent(this._runtimeAssignment);},this.toString=()=>{var r,a;return this.expression?`${(r=this.varIdentifier)===null||r===void 0?void 0:r.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof Yh.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!n):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let n=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof Tm.Weave)&&!(this.parent instanceof wm.FlowBase)&&!(this.parent instanceof Am.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Ss.IncDecExpression=ol;});var ul=w(Es=>{Object.defineProperty(Es,"__esModule",{value:true});Es.IncludedFile=void 0;var Fm=ee(),ll=class extends Fm.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Es.IncludedFile=ll;});var Zh=w(bs=>{Object.defineProperty(bs,"__esModule",{value:true});bs.InfixOperator=void 0;var hl=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};bs.InfixOperator=hl;});var dl=w(Ds=>{Object.defineProperty(Ds,"__esModule",{value:true});Ds.Knot=void 0;var Nm=dt(),ec=vn(),cl=class extends Nm.FlowBase{get flowLevel(){return ec.FlowLevel.Knot}constructor(e,t,n,r){super(e,t,n,r);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let n in this.subFlowsByName){let r=t.ContentWithNameAtLevel(n,ec.FlowLevel.Knot,false);if(r){let a=this.subFlowsByName.get(n),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${r.debugMetadata})`;this.Error(s,a);}}}};Ds.Knot=cl;});var tc=w(As=>{Object.defineProperty(As,"__esModule",{value:true});As.List=void 0;var Vm=Ue(),Im=Be(),km=Be(),Rm=ne(),pl=class extends Vm.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,r;let a=new Im.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((n=s?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";o.length>1?(l=o[0],u=o[1]):u=o[0];let h=this.story.ResolveListItem(l,u,this);if(h===null)l===null?this.Error(`Could not find list definition that contains item '${s}'`):this.Error(`Could not find list item ${s}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${s}`);return}l||(l=((r=h.parent.identifier)===null||r===void 0?void 0:r.name)||null);let c=new km.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(c,h.seriesValue);}}t.AddContent(new Rm.ListValue(a));};}get typeName(){return "List"}};As.List=pl;});var gl=w(ws=>{Object.defineProperty(ws,"__esModule",{value:true});ws.ListElementDefinition=void 0;var Lm=ee(),Bm=bt(),fl=class extends Lm.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,n=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=n,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,Bm.SymbolType.ListItem);}};ws.ListElementDefinition=fl;});var ml=w(xs=>{Object.defineProperty(xs,"__esModule",{value:true});xs.StatementLevel=void 0;var nc;(function(i){i[i.InnerBlock=0]="InnerBlock",i[i.Stitch=1]="Stitch",i[i.Knot=2]="Knot",i[i.Top=3]="Top";})(nc||(xs.StatementLevel=nc={}));});var yl=w(_s=>{Object.defineProperty(_s,"__esModule",{value:true});_s.Stitch=void 0;var Wm=dt(),jm=vn(),Cl=class extends Wm.FlowBase{get flowLevel(){return jm.FlowLevel.Stitch}constructor(e,t,n,r){super(e,t,n,r),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};_s.Stitch=Cl;});var Ps=w(Os=>{Object.defineProperty(Os,"__esModule",{value:true});Os.Tag=void 0;var qm=Re(),vl=class extends qm.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Os.Tag=vl;});var El=w(Ts=>{Object.defineProperty(Ts,"__esModule",{value:true});Ts.Choice=void 0;var Mm=ke(),Gm=Ce(),$m=Re(),Sl=class i extends $m.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, Gm.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new Mm.Path(e);}Clone(){let e=new i;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};Ts.Choice=Sl;});var Dl=w(Fs=>{Object.defineProperty(Fs,"__esModule",{value:true});Fs.ListDefinitionsOrigin=void 0;var Jm=Be(),Hm=ne(),zm=Ce(),bl=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[n,r]of t.items){let a=Jm.InkListItem.fromSerializedKey(n),s=new Hm.ListValue(a,r);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,s),this._allUnambiguousListValueCache.set(a.fullName,s);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let n=this._lists.get(e);return n?{result:n,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, zm.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Fs.ListDefinitionsOrigin=bl;});var xn=w(ks=>{Object.defineProperty(ks,"__esModule",{value:true});ks.JsonSerialisation=void 0;var Ns=ae(),je=ne(),ic=vs(),q=ye(),wn=Ut(),rc=ct(),sc=dr(),Al=Dn(),ac=Ft(),wl=ht(),oc=zt(),lc=Ps(),Um=ke(),uc=El(),Km=zo(),Xm=Dl(),Vs=Be(),oe=z(),Qt=Ce(),Is=class i{static JArrayToRuntimeObjList(e,t=false){let n=e.length;t&&n--;let r=[];for(let a=0;a<n;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, Qt.throwNullException)("runtimeObj");r.push(o);}return r}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[n,r]of t)e.WritePropertyStart(n),this.WriteRuntimeObject(e,r),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let n of t)this.WriteRuntimeObject(e,n);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[n,r]of t)e.WriteIntProperty(n,r);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let n=(0, oe.asOrNull)(t,Ns.Container);if(n){this.WriteRuntimeContainer(e,n);return}let r=(0, oe.asOrNull)(t,rc.Divert);if(r){let g="->";r.isExternal?g="x()":r.pushesToStack&&(r.stackPushType==wn.PushPopType.Function?g="f()":r.stackPushType==wn.PushPopType.Tunnel&&(g="->t->"));let E;r.hasVariableTarget?E=r.variableDivertName:E=r.targetPathString,e.WriteObjectStart(),e.WriteProperty(g,E),r.hasVariableTarget&&e.WriteProperty("var",true),r.isConditional&&e.WriteProperty("c",true),r.externalArgs>0&&e.WriteIntProperty("exArgs",r.externalArgs),e.WriteObjectEnd();return}let a=(0, oe.asOrNull)(t,sc.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, oe.asOrNull)(t,je.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, oe.asOrNull)(t,je.IntValue);if(o){e.WriteInt(o.value);return}let l=(0, oe.asOrNull)(t,je.FloatValue);if(l){e.WriteFloat(l.value);return}let u=(0, oe.asOrNull)(t,je.StringValue);if(u){u.isNewline?e.Write(`
17
- `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(u.value),e.WriteStringEnd());return}let h=(0, oe.asOrNull)(t,je.ListValue);if(h){this.WriteInkList(e,h);return}let c=(0, oe.asOrNull)(t,je.DivertTargetValue);if(c){if(e.WriteObjectStart(),c.value===null)return (0, Qt.throwNullException)("divTargetVal.value");e.WriteProperty("^->",c.value.componentsString),e.WriteObjectEnd();return}let p=(0, oe.asOrNull)(t,je.VariablePointerValue);if(p){e.WriteObjectStart(),e.WriteProperty("^var",p.value),e.WriteIntProperty("ci",p.contextIndex),e.WriteObjectEnd();return}if((0, oe.asOrNull)(t,ic.Glue)){e.Write("<>");return}let y=(0, oe.asOrNull)(t,q.ControlCommand);if(y){e.Write(i._controlCommandNames[y.commandType]);return}let C=(0, oe.asOrNull)(t,wl.NativeFunctionCall);if(C){let g=C.name;g=="^"&&(g="L^"),e.Write(g);return}let A=(0, oe.asOrNull)(t,Al.VariableReference);if(A){e.WriteObjectStart();let g=A.pathStringForCount;g!=null?e.WriteProperty("CNT?",g):e.WriteProperty("VAR?",A.name),e.WriteObjectEnd();return}let b=(0, oe.asOrNull)(t,ac.VariableAssignment);if(b){e.WriteObjectStart();let g=b.isGlobal?"VAR=":"temp=";e.WriteProperty(g,b.variableName),b.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, oe.asOrNull)(t,oc.Void)){e.Write("void");return}let d=(0, oe.asOrNull)(t,lc.Tag);if(d){e.WriteObjectStart(),e.WriteProperty("#",d.text),e.WriteObjectEnd();return}let S=(0, oe.asOrNull)(t,uc.Choice);if(S){this.WriteChoice(e,S);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let r=this.JTokenToRuntimeObject(e[n]);if(r===null)return (0, Qt.throwNullException)("inkObject");t.set(n,r);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let n in e)e.hasOwnProperty(n)&&t.set(n,parseInt(e[n]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return je.Value.Create(e);if(typeof e=="string"){let t=e.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(t);if(n)return new je.FloatValue(parseFloat(n[0]));let r=t[0];if(r=="^")return new je.StringValue(t.substring(1));if(r==`
18
- `&&t.length==1)return new je.StringValue(`
19
- `);if(t=="<>")return new ic.Glue;for(let a=0;a<i._controlCommandNames.length;++a){let s=i._controlCommandNames[a];if(t==s)return new q.ControlCommand(a)}if(t=="L^"&&(t="^"),wl.NativeFunctionCall.CallExistsWithName(t))return wl.NativeFunctionCall.CallWithName(t);if(t=="->->")return q.ControlCommand.PopTunnel();if(t=="~ret")return q.ControlCommand.PopFunction();if(t=="void")return new oc.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new je.DivertTargetValue(new Um.Path(n.toString()));if(t["^var"]){n=t["^var"];let h=new je.VariablePointerValue(n.toString());return "ci"in t&&(n=t.ci,h.contextIndex=parseInt(n)),h}let r=false,a=false,s=wn.PushPopType.Function,o=false;if((n=t["->"])?r=true:(n=t["f()"])?(r=true,a=true,s=wn.PushPopType.Function):(n=t["->t->"])?(r=true,a=true,s=wn.PushPopType.Tunnel):(n=t["x()"])&&(r=true,o=true,a=false,s=wn.PushPopType.Function),r){let h=new rc.Divert;h.pushesToStack=a,h.stackPushType=s,h.isExternal=o;let c=n.toString();return (n=t.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!t.c,o&&(n=t.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=t["*"]){let h=new sc.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=t.flg)&&(h.flags=parseInt(n)),h}if(n=t["VAR?"])return new Al.VariableReference(n.toString());if(n=t["CNT?"]){let h=new Al.VariableReference;return h.pathStringForCount=n.toString(),h}let l=false,u=false;if((n=t["VAR="])?(l=true,u=true):(n=t["temp="])&&(l=true,u=false),l){let h=n.toString(),c=!t.re,p=new ac.VariableAssignment(h,c);return p.isGlobal=u,p}if(t["#"]!==void 0)return n=t["#"],new lc.Tag(n.toString());if(n=t.list){let h=n,c=new Vs.InkList;if(n=t.origins){let p=n;c.SetInitialOriginNames(p);}for(let p in h)if(h.hasOwnProperty(p)){let f=h[p],y=new Vs.InkListItem(p),C=parseInt(f);c.Add(y,C);}return new je.ListValue(c)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,n){return JSON.stringify(e,(r,a)=>t?.some(s=>s===r)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=false){if(e.WriteArrayStart(),t===null)return (0, Qt.throwNullException)("container");for(let l of t.content)this.WriteRuntimeObject(e,l);let r=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!n,o=r!=null||a>0||s;if(o&&e.WriteObjectStart(),r!=null)for(let[l,u]of r){let h=l,c=(0, oe.asOrNull)(u,Ns.Container);e.WritePropertyStart(h),this.WriteRuntimeContainer(e,c,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),s&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new Ns.Container;t.content=this.JArrayToRuntimeObjList(e,true);let n=e[e.length-1];if(n!=null){let r=new Map;for(let a in n)if(a=="#f")t.countFlags=parseInt(n[a]);else if(a=="#n")t.name=n[a].toString();else {let s=this.JTokenToRuntimeObject(n[a]),o=(0, oe.asOrNull)(s,Ns.Container);o&&(o.name=a),r.set(a,s);}t.namedOnlyContent=r;}return t}static JObjectToChoice(e){let t=new uc.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t.isInvisibleDefault=!!e.isInvisibleDefault,t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),e.WriteProperty("isInvisibleDefault",t.isInvisibleDefault),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, Qt.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[r,a]of n){let s=Vs.InkListItem.fromSerializedKey(r),o=a;if(s.itemName===null)return (0, Qt.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(s.originName?s.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(s.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let r of n.originNames)e.Write(r);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let r={};for(let[a,s]of n.items){let o=Vs.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Qt.throwNullException)("item.itemName");r[o.itemName]=s;}t[n.name]=r;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let r in t)if(t.hasOwnProperty(r)){let a=r.toString(),s=t[r],o=new Map;for(let u in s)if(t.hasOwnProperty(r)){let h=s[u];o.set(u,parseInt(h));}let l=new Km.ListDefinition(a,o);n.push(l);}return new Xm.ListDefinitionsOrigin(n)}};ks.JsonSerialisation=Is;Is._controlCommandNames=(()=>{let i=[];i[q.ControlCommand.CommandType.EvalStart]="ev",i[q.ControlCommand.CommandType.EvalOutput]="out",i[q.ControlCommand.CommandType.EvalEnd]="/ev",i[q.ControlCommand.CommandType.Duplicate]="du",i[q.ControlCommand.CommandType.PopEvaluatedValue]="pop",i[q.ControlCommand.CommandType.PopFunction]="~ret",i[q.ControlCommand.CommandType.PopTunnel]="->->",i[q.ControlCommand.CommandType.BeginString]="str",i[q.ControlCommand.CommandType.EndString]="/str",i[q.ControlCommand.CommandType.NoOp]="nop",i[q.ControlCommand.CommandType.ChoiceCount]="choiceCnt",i[q.ControlCommand.CommandType.Turns]="turn",i[q.ControlCommand.CommandType.TurnsSince]="turns",i[q.ControlCommand.CommandType.ReadCount]="readc",i[q.ControlCommand.CommandType.Random]="rnd",i[q.ControlCommand.CommandType.SeedRandom]="srnd",i[q.ControlCommand.CommandType.VisitIndex]="visit",i[q.ControlCommand.CommandType.SequenceShuffleIndex]="seq",i[q.ControlCommand.CommandType.StartThread]="thread",i[q.ControlCommand.CommandType.Done]="done",i[q.ControlCommand.CommandType.End]="end",i[q.ControlCommand.CommandType.ListFromInt]="listInt",i[q.ControlCommand.CommandType.ListRange]="range",i[q.ControlCommand.CommandType.ListRandom]="lrnd",i[q.ControlCommand.CommandType.BeginTag]="#",i[q.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<q.ControlCommand.CommandType.TOTAL_VALUES;++e)if(i[e]==null)throw new Error("Control command not accounted for in serialisation");return i})();});var Ol=w(hi=>{Object.defineProperty(hi,"__esModule",{value:true});hi.CallStack=void 0;var xl=Ut(),hc=ke(),Ym=ci(),cc=xn(),Qm=ne(),Zm=Jt(),li=Zn(),eC=jn(),dc=fn(),_l=Ce(),ui=class i{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){eC.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=li.Pointer.Null,arguments[0]instanceof Ym.Story){let e=arguments[0];this._startOfRoot=li.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new i.Thread),this._threads[0].callstack.push(new i.Element(xl.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let r of n){let a=r,s=new i.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=li.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let n of this._threads)n.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==xl.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let r=new i.Element(e,this.currentElement.currentPointer,false);r.evaluationStackHeightWhenPushed=t,r.functionStartInOutputStream=n,this.callStack.push(r);}CanPop(e=null){return this.canPop?e==null?true:this.currentElement.type==e:false}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let n=this.callStack[t-1],r=(0, dc.tryGetValueFromMap)(n.temporaryVariables,e,null);return r.exists?r.result:null}SetTemporaryVariable(e,t,n,r=-1){r==-1&&(r=this.currentElementIndex+1);let a=this.callStack[r-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, dc.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&Qm.ListValue.RetainListOriginsForAssignment(s.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new Zm.StringBuilder;for(let t=0;t<this._threads.length;t++){let n=this._threads[t],r=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
20
- `,t+1,this._threads.length,r?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==xl.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=n.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, _l.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};hi.CallStack=ui;(function(i){class e{constructor(r,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=r;}Copy(){let r=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return r.temporaryVariables=new Map(this.temporaryVariables),r.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,r.functionStartInOutputStream=this.functionStartInOutputStream,r}}i.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=li.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let r=arguments[0],a=arguments[1];this.threadIndex=parseInt(r.threadIndex);let s=r.callstack;for(let l of s){let u=l,h=parseInt(u.type),c=li.Pointer.Null,p,f=u.cPath;if(typeof f<"u"){p=f.toString();let b=a.ContentAtPath(new hc.Path(p));if(c.container=b.container,c.index=parseInt(u.idx),b.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+p+". Has the story changed since this save data was created?");b.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+p+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+p+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let y=!!u.exp,C=new e(h,c,y),A=u.temp;typeof A<"u"?C.temporaryVariables=cc.JsonSerialisation.JObjectToDictionaryRuntimeObjs(A):C.temporaryVariables.clear(),this.callstack.push(C);}let o=r.previousContentObject;if(typeof o<"u"){let l=new hc.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let r=new t;r.threadIndex=this.threadIndex;for(let a of this.callstack)r.callstack.push(a.Copy());return r.previousPointer=this.previousPointer.copy(),r}WriteJson(r){r.WriteObjectStart(),r.WritePropertyStart("callstack"),r.WriteArrayStart();for(let a of this.callstack){if(r.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, _l.throwNullException)("el.currentPointer.container");r.WriteProperty("cPath",a.currentPointer.container.path.componentsString),r.WriteIntProperty("idx",a.currentPointer.index);}r.WriteProperty("exp",a.inExpressionEvaluation),r.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(r.WritePropertyStart("temp"),cc.JsonSerialisation.WriteDictionaryRuntimeObjs(r,a.temporaryVariables),r.WritePropertyEnd()),r.WriteObjectEnd();}if(r.WriteArrayEnd(),r.WritePropertyEnd(),r.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, _l.throwNullException)("this.previousPointer.Resolve()");r.WriteProperty("previousContentObject",a.path.toString());}r.WriteObjectEnd();}}i.Thread=t;})(ui||(hi.CallStack=ui={}));});var fc=w(Ls=>{Object.defineProperty(Ls,"__esModule",{value:true});Ls.VariablesState=void 0;var ge=ne(),tC=Mn(),pc=xn(),ve=z(),di=fn(),It=Ce();function nC(){return class{}}var Rs=class i extends nC(){variableChangedEvent(e,t){for(let n of this.variableChangedEventCallbacks)n(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let n=this._globalVariables.get(t);this.variableChangedEvent(t,n);}if(this.patch!=null)for(let t of this.patch.changedVariables){let n=this.patch.TryGetGlobal(t,null);n.exists&&e.set(t,n);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,n]of e)this.variableChangedEvent(t,n);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(e),typeof n>"u"&&(n=this._defaultGlobalVariables.get(e)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new tC.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=ge.Value.Create(t);if(n==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,n);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(r,a){return a in r?r[a]:r.$(a)},set(r,a,s){return a in r?r[a]=s:r.$(a,s),!0},ownKeys(r){return [...new Set([...r._defaultGlobalVariables.keys(),...r._globalVariables.keys()])]},getOwnPropertyDescriptor(r,a){return {enumerable:!0,configurable:!0,value:r.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, It.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,n]of this._defaultGlobalVariables){let r=e[t];if(typeof r<"u"){let a=pc.JsonSerialisation.JTokenToRuntimeObject(r);if(a===null)return (0, It.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let r=t,a=n;if(i.dontSaveDefaultValues&&this._defaultGlobalVariables.has(r)){let s=this._defaultGlobalVariables.get(r);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(r),pc.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, It.throwNullException)("obj1");if(t===null)return (0, It.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let n=(0, ve.asOrNull)(e,ge.BoolValue);if(n!==null)return n.value===(0, ve.asOrThrows)(t,ge.BoolValue).value;let r=(0, ve.asOrNull)(e,ge.IntValue);if(r!==null)return r.value===(0, ve.asOrThrows)(t,ge.IntValue).value;let a=(0, ve.asOrNull)(e,ge.FloatValue);if(a!==null)return a.value===(0, ve.asOrThrows)(t,ge.FloatValue).value;let s=(0, ve.asOrNull)(e,ge.Value),o=(0, ve.asOrNull)(t,ge.Value);if(s!==null&&o!==null)return (0, ve.isEquatable)(s.valueObject)&&(0, ve.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let n=this.GetRawVariableWithName(e,t),r=(0, ve.asOrNull)(n,ge.VariablePointerValue);return r!==null&&(n=this.ValueAtVariablePointer(r)),n}TryGetDefaultVariableValue(e){let t=(0, di.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let n=null;if(t==0||t==-1){let r=null;if(this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists)||(r=(0, di.tryGetValueFromMap)(this._globalVariables,e,null),r.exists)||this._defaultGlobalVariables!==null&&(r=(0, di.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),r.exists))return r.result;if(this._listDefsOrigin===null)return (0, It.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(e,t),n}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let n=e.variableName;if(n===null)return (0, It.throwNullException)("name");let r=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let s=(0, ve.asOrNull)(t,ge.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, ve.asOrNull)(this.GetRawVariableWithName(n,r),ge.VariablePointerValue),s!=null&&(n=s.variableName,r=s.contextIndex,a=r==0);while(s!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,r);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, ve.asOrThrows)(e,ge.ListValue),r=(0, ve.asOrThrows)(t,ge.ListValue);n.value&&r.value&&r.value.Count==0&&r.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(e,t){let n=null;if(this.patch===null&&(n=(0, di.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, di.tryGetValueFromMap)(this._globalVariables,e,null))),ge.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, It.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&n!==null&&t!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, It.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let n=this.GetRawVariableWithName(e.variableName,t),r=(0, ve.asOrNull)(n,ge.VariablePointerValue);return r??new ge.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Ls.VariablesState=Rs;Rs.dontSaveDefaultValues=true;});var Tl=w(Bs=>{Object.defineProperty(Bs,"__esModule",{value:true});Bs.PRNG=void 0;var Pl=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};Bs.PRNG=Pl;});var gc=w(Ws=>{Object.defineProperty(Ws,"__esModule",{value:true});Ws.StatePatch=void 0;var Fl=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:true}:{result:t,exists:false}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:true}:{result:t,exists:false}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:true}:{result:t,exists:false}}};Ws.StatePatch=Fl;});var Nl=w(fi=>{Object.defineProperty(fi,"__esModule",{value:true});fi.SimpleJson=void 0;var pi=class i{static TextToDictionary(e){return new i.Reader(e).ToDictionary()}static TextToArray(e){return new i.Reader(e).ToArray()}};fi.SimpleJson=pi;(function(i){class e{constructor(r){if(JSON.parse("0",(s,o,l)=>l!=null)){let s=(o,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(r,s);}else {let s=r.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}i.Reader=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(r){this.WriteObjectStart(),r(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let r={};if(this.state===i.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=r,this._collectionStack.push(r);}else this.state===i.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(r),this._collectionStack.push(r)):(this.Assert(this.state===i.Writer.State.None),this._jsonObject=r,this._collectionStack.push(r));this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===i.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(r,a){if(this.WritePropertyStart(r),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}this.WritePropertyEnd();}WriteIntProperty(r,a){this.WritePropertyStart(r),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(r,a){this.WritePropertyStart(r),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(r){this.Assert(this.state===i.Writer.State.Object),this._propertyNameStack.push(r),this.IncrementChildCount(),this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===i.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===i.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Property)),this._stateStack.push(new i.Writer.StateElement(i.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===i.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(r){this.Assert(this.state===i.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=r;}WriteArrayStart(){this.StartNewObject(true);let r=[];if(this.state===i.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=r,this._collectionStack.push(r);}else this.state===i.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(r),this._collectionStack.push(r)):(this.Assert(this.state===i.Writer.State.None),this._jsonObject=r,this._collectionStack.push(r));this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===i.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(r,a=true){if(r===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(r);}WriteBool(r){r!==null&&(this.StartNewObject(false),this._addToCurrentObject(r));}WriteInt(r){r!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(r)));}WriteFloat(r){r!==null&&(this.StartNewObject(false),r==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):r==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(r)?this._addToCurrentObject(0):this._addToCurrentObject(r));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new i.Writer.StateElement(i.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==i.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(r,a=true){if(this.Assert(this.state===i.Writer.State.String),r===null){console.error("Warning: trying to write a null string");return}this._currentString+=r;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(r){r?this.Assert(this.state===i.Writer.State.None||this.state===i.Writer.State.Property||this.state===i.Writer.State.Array):this.Assert(this.state===i.Writer.State.Property||this.state===i.Writer.State.Array),this.state===i.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===i.Writer.State.Array||this.state===i.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:i.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let r=this._stateStack.pop();r.childCount++,this._stateStack.push(r);}Assert(r){if(!r)throw Error("Assert failed while writing JSON")}_addToCurrentObject(r){this.Assert(this.currentCollection!==null),this.state===i.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(r)):this.state===i.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=r,this._propertyNameStack.pop());}}i.Writer=t,(function(n){(function(s){s[s.None=0]="None",s[s.Object=1]="Object",s[s.Array=2]="Array",s[s.Property=3]="Property",s[s.PropertyName=4]="PropertyName",s[s.String=5]="String";})(n.State||(n.State={}));class a{constructor(o){this.type=i.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;})(t=i.Writer||(i.Writer={}));})(pi||(fi.SimpleJson=pi={}));});var Cc=w(qs=>{Object.defineProperty(qs,"__esModule",{value:true});qs.Flow=void 0;var mc=Ol(),js=xn(),iC=Ce(),Vl=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new mc.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=js.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=js.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let r=n.choiceThreads;typeof r<"u"&&this.LoadFlowChoiceThreads(r,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),e.WriteProperty("outputStream",n=>js.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, iC.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let r of this.currentChoices)js.JsonSerialisation.WriteChoice(n,r);n.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let n of this.currentChoices){let r=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(r!==null)n.threadAtGeneration=r.Copy();else {let a=e[`${n.originalThreadIndex}`];n.threadAtGeneration=new mc.CallStack.Thread(a,t);}}}};qs.Flow=Vl;});var Sc=w(Gs=>{Object.defineProperty(Gs,"__esModule",{value:true});Gs.StoryState=void 0;var rC=Ol(),sC=fc(),ce=ne(),kt=Ut(),aC=Ps(),Il=vs(),yc=ke(),Te=ye(),kl=Jt(),Rt=xn(),oC=Tl(),lC=zt(),_n=Zn(),gi=fn(),le=z(),uC=jn(),Qe=Ce(),hC=ci(),cC=gc(),vc=Nl(),Ms=Cc(),dC=Be(),Rl=class i{ToJson(e=false){let t=new vc.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=vc.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let n=this.story.ContentAtPath(new yc.Path(e)).container;if(n===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(n,0),t.exists)return t.result}return t=(0, gi.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, Qe.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let r=this._patch.TryGetVisitCount(e,0);if(r.exists)return r.result}let t=e.path.toString(),n=(0, gi.tryGetValueFromMap)(this._visitCounts,t,null);return n.exists?n.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let r=this.VisitCountForContainer(e);r++,this._patch.SetVisitCount(e,r);return}let t=e.path.toString(),n=(0, gi.tryGetValueFromMap)(this._visitCounts,t,null);n.exists?this._visitCounts.set(t,n.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let r=this._patch.TryGetTurnIndex(e,0);if(r.exists)return this.currentTurnIndex-r.result}let t=e.path.toString(),n=(0, gi.tryGetValueFromMap)(this._turnIndices,t,0);return n.exists?this.currentTurnIndex-n.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, Qe.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, Qe.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new kl.StringBuilder,t=false;for(let n of this.outputStream){let r=(0, le.asOrNull)(n,ce.StringValue);if(!t&&r!==null)e.Append(r.value);else {let a=(0, le.asOrNull)(n,Te.ControlCommand);a!==null&&(a.commandType==Te.ControlCommand.CommandType.BeginTag?t=true:a.commandType==Te.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new kl.StringBuilder,n=-1,r=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&n==-1&&(n=a),o||(s!=`
14
+ `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};cr.CommentEliminator=Ka;});var pr=x(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.Conditional=void 0;var Jp=ie(),oh=fe(),Hp=Q(),Xa=class extends Hp.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new Jp.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let r of this.branches){let a=r.runtimeObject;n.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(oh.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=oh.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=t;}super.ResolveReferences(e);}};dr.Conditional=Xa;});var Et=x(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.Text=void 0;var zp=Q(),Up=ee(),Ya=class extends zp.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new Up.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};fr.Text=Ya;});var gr=x(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.ConstantDeclaration=void 0;var Kp=Q(),Xp=ct(),Qa=class extends Kp.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,Xp.SymbolType.Var);}};mr.ConstantDeclaration=Qa;});var on=x(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.FlowLevel=void 0;var lh;(function(i){i[i.Story=0]="Story",i[i.Knot=1]="Knot",i[i.Stitch=2]="Stitch",i[i.WeavePoint=3]="WeavePoint";})(lh||(Cr.FlowLevel=lh={}));});var Gn=x(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.Gather=void 0;var Yp=ie(),Qp=Q(),Zp=ct(),Za=class extends Qp.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let n=new Yp.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let r of this.content)n.AddContent(r.runtimeObject);return n},this.toString=()=>{var n,r;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((r=this.identifier)===null||r===void 0?void 0:r.name)+")":"gather"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Zp.SymbolType.SubFlowAndWeave);}};yr.Gather=Za;});var Lt=x(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.Path=void 0;var vr=H(),uh=tt(),ln=on(),ef=Bt(),eo=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?ln.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(vr.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===ln.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let r=this.ResolveBaseTarget(n);return r===null?null:this.components.length>1?this.ResolveTailComponents(r):r},this.ResolveBaseTarget=n=>{let r=this.firstComponent,a=n;for(;a;){let s=a===n,o=this.GetChildFromContext(a,r,null,s);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=n=>{let r=n;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let s=this.components[a].name,o,l=(0, vr.asOrNull)(r,uh.FlowBase);if(l!==null?o=l.flowLevel+1:o=ln.FlowLevel.WeavePoint,r=this.GetChildFromContext(r,s,o),r===null)break}return r},this.GetChildFromContext=(n,r,a,s=false)=>{let o=a===null,l=(0, vr.asOrNull)(n,ef.Weave);if(r&&l!==null&&(o||a===ln.FlowLevel.WeavePoint))return l.WeavePointNamed(r);let u=(0, vr.asOrNull)(n,uh.FlowBase);if(r&&u!==null){let h=s||u.flowLevel===ln.FlowLevel.Knot;return u.ContentWithNameAtLevel(r,a,h)}return null},Object.values(ln.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};Sr.Path=eo;});var io=x(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.ReturnType=void 0;var tf=Q(),nf=ie(),to=fe(),rf=Vt(),no=class extends tf.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new nf.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(to.ControlCommand.EvalStart()),t.AddContent(new rf.Void),t.AddContent(to.ControlCommand.EvalEnd())),t.AddContent(to.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Er.ReturnType=no;});var $n=x(Dr=>{Object.defineProperty(Dr,"__esModule",{value:true});Dr.ClosestFlowBase=void 0;function sf(i){let e=i.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}Dr.ClosestFlowBase=sf;});var Ar=x(br=>{Object.defineProperty(br,"__esModule",{value:true});br.Identifier=void 0;var ro=class i{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new i("DONE")}};br.Identifier=ro;});var tt=x(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.FlowBase=void 0;var af=an(),so=hn(),of=un(),nt=on(),lf=Gn(),uf=Q(),hf=Lt(),cf=io(),df=ie(),pf=et(),ff=vt(),ao=ct(),mf=Bt(),gf=$n(),Cf=Ar(),hh=H(),oo=class i extends uf.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,n=null,r=false,a=false){super(),this.isFunction=r,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(s,o)=>{var l,u;let h=[],c=[];this._subFlowsByName=new Map;for(let f of s){let v=(0, hh.asOrNull)(f,i);v?(this._firstChildFlow===null&&(this._firstChildFlow=v),c.push(f),!((l=v.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=v.identifier)===null||u===void 0?void 0:u.name,v)):h.push(f);}o&&h.push(new lf.Gather(null,1),new so.Divert(new hf.Path(Cf.Identifier.Done())));let p=[];return h.length>0&&(this._rootWeave=new mf.Weave(h,0),p.push(this._rootWeave)),c.length>0&&p.push(...c),p},this.ResolveVariableWithName=(s,o)=>{var l;let u={},h=o===null?this:(0, gf.ClosestFlowBase)(o);if(h){if(h.args!==null){for(let c of h.args)if(((l=c.identifier)===null||l===void 0?void 0:l.name)===s)return u.found=true,u.isArgument=true,u.ownerFlow=h,u}if(h!==this.story&&h.variableDeclarations.has(s))return u.found=true,u.ownerFlow=h,u.isTemporary=true,u}return this.story.variableDeclarations.has(s)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let l=this.variableDeclarations.get(o),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${u}`,s,false);return}this.variableDeclarations.set(s.variableName,s);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,s]of this._subFlowsByName)s.hasOwnProperty("ResolveWeavePointNaming")&&s.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var s;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===nt.FlowLevel.Knot||this.flowLevel===nt.FlowLevel.Stitch)&&(o=this.Find(cf.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let l=new df.Container;l.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(l.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(l);let u=0;for(;this.content!==null&&u<this.content.length;){let h=this.content[u];if(h instanceof i){let c=h,p=c.runtimeObject;u===0&&!c.hasParameters&&this.flowLevel===nt.FlowLevel.Knot&&(this._startingSubFlowDivert=new pf.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=p);let f=p,v=l.namedContent.get(f.name)||null;if(v){let g=`${this.GetType()} already contains flow named '${f.name}' (at ${v.debugMetadata})`;this.Error(g,c);}l.AddToNamedContentOnly(f);}else h&&l.AddContent(h.runtimeObject);u+=1;}return this.flowLevel!==nt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let l=this.args.length-1;l>=0;--l){let u=((o=this.args[l].identifier)===null||o===void 0?void 0:o.name)||null,h=new ff.VariableAssignment(u,true);s.AddContent(h);}},this.ContentWithNameAtLevel=(s,o=null,l=false)=>{var u;if((o===this.flowLevel||o===null)&&s===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===nt.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(s),c))return c;if(o===nt.FlowLevel.WeavePoint)return l?this.DeepSearchForAnyLevelContent(s):null}if(o!==null&&o<this.flowLevel)return null;let h=this._subFlowsByName.get(s)||null;return h&&(o===null||o===h.flowLevel)?h:l?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,nt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(s,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==nt.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[l,u]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${l}' within the function '${this.identifier}'`,u);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(so.Divert)();for(let l of s)!l.isFunctionCall&&!(l.parent instanceof of.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(af.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},this.WarningInTermination=s=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";s.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let l=(0, hh.asOrNull)(s,so.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let r of this.args)e.CheckForNamingCollisions(this,r.identifier,ao.SymbolType.Arg,"argument");for(let r=0;r<this.args.length;r+=1)for(let a=r+1;a<this.args.length;a+=1)((t=this.args[r].identifier)===null||t===void 0?void 0:t.name)==((n=this.args[a].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[r].identifier}'`);}if(this.flowLevel!==nt.FlowLevel.Story){let r=this.flowLevel===nt.FlowLevel.Knot?ao.SymbolType.Knot:ao.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,r);}}};xr.FlowBase=oo;});var _r=x(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.ContentList=void 0;var yf=ie(),vf=Q(),Sf=Et(),Ef=H(),lo=class extends vf.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let r=(0, Ef.asOrNull)(this.content[n],Sf.Text);if(r===null)break;if(r.text=r.text.replace(new RegExp(/[ \t]/g),""),r.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new yf.Container;if(this.content!==null)for(let r of this.content){let a=r.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};wr.ContentList=lo;});var cn=x(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.VariableReference=void 0;var Df=xe(),bf=Ae(),uo=class extends Df.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new bf.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};Or.VariableReference=uo;});var dn=x(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.VariableReference=void 0;var Af=_r(),xf=Le(),ch=tt(),wf=Lt(),_f=cn(),Of=Bt(),Tf=Ar(),dh=H(),ho=class extends xf.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(dh.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new Tf.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=t=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new _f.VariableReference(this.name),this.path.length===1||this.path.length===2){let r="",a="";this.path.length===1?r=this.path[0]:(a=this.path[0],r=this.path[1]),this.story.ResolveListItem(a,r,this)&&(this.isListItemReference=true);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new wf.Path(this.pathIdentifiers),n=t.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let r=(0, dh.asOrNull)(n,ch.FlowBase);r&&r.isFunction&&(this.parent instanceof Of.Weave||this.parent instanceof Af.ContentList||this.parent instanceof ch.FlowBase)&&this.Warning(`'${r.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${r.identifier}()`);return}if(this.path.length>1){let r=`Could not find target for read count: ${t}`;this.path.length<=2&&(r+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(r);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};Tr.VariableReference=ho;});var Jn=x(Ir=>{Object.defineProperty(Ir,"__esModule",{value:true});Ir.FunctionCall=void 0;var it=fe(),Pf=hn(),Ff=un(),Nf=Le(),If=_e(),Vf=ee(),Fr=Ze(),ph=zi(),kf=Lt(),Rf=ee(),Lf=dn(),Pr=H(),Nr=class i extends Nf.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(e,t){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=n=>{let r=this.story.ResolveList(this.name),a=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),n.AddContent(it.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(it.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, Pr.asOrNull)(this.args[0],Ff.DivertTarget),o=(0, Pr.asOrNull)(this.args[0],Lf.VariableReference);if(this.args.length!==1||s===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}s?(this._divertTargetToCount=s,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(it.ControlCommand.TurnsSince()):n.AddContent(it.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let s=0;s<this.args.length;s+=1){let o=(0, Pr.asOrNull)(this.args[s],ph.NumberExpression);if(o&&!o.isInt()){let l=s===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[s].GenerateIntoContainer(n);}n.AddContent(it.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, Pr.asOrNull)(this.args[0],ph.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(it.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let s=0;s<this.args.length;s+=1)this.args[s].GenerateIntoContainer(n);n.AddContent(it.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(n),n.AddContent(it.ControlCommand.ListRandom());else if(Fr.NativeFunctionCall.CallExistsWithName(this.name)){let s=Fr.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${i.name} should take ${s.numberOfParameters} parameter`;s.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(n);n.AddContent(Fr.NativeFunctionCall.CallWithName(this.name));}else if(r!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)n.AddContent(new Rf.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(it.ControlCommand.ListFromInt());else {let s=new If.InkList;s.SetInitialOriginName(this.name),n.AddContent(new Vf.ListValue(s));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(it.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new Pf.Divert(new kf.Path(e),t),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,n=t.runtimeDivert.variableDivertName!=null;if(n){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let r=t.targetContent;if(r===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!r.containerForCounting)throw new Error;r.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${i.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Ir.FunctionCall=Nr;Nr.IsBuiltIn=i=>Fr.NativeFunctionCall.CallExistsWithName(i)?true:i==="CHOICE_COUNT"||i==="TURNS_SINCE"||i==="TURNS"||i==="RANDOM"||i==="SEED_RANDOM"||i==="LIST_VALUE"||i==="LIST_RANDOM"||i==="READ_COUNT";});var po=x(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.MultipleConditionExpression=void 0;var Bf=Le(),Wf=Ze(),co=class extends Bf.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let n=true;for(let r of this.subExpressions)r.GenerateIntoContainer(t),n||t.AddContent(Wf.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Vr.MultipleConditionExpression=co;});var un=x(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.DivertTarget=void 0;var jf=Ra(),qf=an(),Mf=pr(),Gf=Co(),$f=ee(),fo=Le(),Jf=tt(),fh=Jn(),Hf=po(),mh=dn(),mo=H(),go=class i extends fo.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new $f.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, mo.asOrNull)(t,i);if(!n||!this.divert.target||!n.divert.target)return false;let r=this.divert.target.dotSeparatedComponents,a=n.divert.target.dotSeparatedComponents;return r===a},this.divert=this.AddContent(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof fo.Expression;){let r=false,a=false,s=t.parent;if(s instanceof jf.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?r=true:(o.leftExpression instanceof i||o.leftExpression instanceof mh.VariableReference)&&(o.rightExpression instanceof i||o.rightExpression instanceof mh.VariableReference)||(r=true),a=true;}else if(s instanceof fh.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(r=true),a=true;}else (s instanceof fo.Expression||s instanceof Hf.MultipleConditionExpression||s instanceof qf.Choice&&s.condition===t||s instanceof Mf.Conditional||s instanceof Gf.ConditionalSingleBranch)&&(r=true,a=true);if(r&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;t=s;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let n=this.divert.targetContent;if(n!==null){let r=n.containerForCounting;if(r!==null){let s=(0, mo.asOrNull)(this.parent,fh.FunctionCall);s&&s.isTurnsSince||(r.visitsShouldBeCounted=true),r.turnIndexShouldBeCounted=true;}let a=(0, mo.asOrNull)(n,Jf.FlowBase);if(a!=null&&a.args!==null)for(let s of a.args)s.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${s.identifier}').`);}}};kr.DivertTarget=go;});var hn=x(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.Divert=void 0;var zf=ie(),Hn=fe(),Uf=et(),yo=un(),vo=tt(),Kf=Jn(),Xf=Q(),gh=Lt(),Yf=Ae(),Ch=kt(),Qf=ee(),yh=dn(),Zf=$n(),zn=H(),So=class extends Xf.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return Hn.ControlCommand.End();if(this.isDone)return Hn.ControlCommand.Done();this.runtimeDivert=new Uf.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let n=this.args!==null&&this.args.length>0;if(n||this.isFunctionCall||this.isTunnel||this.isThread){let r=new zf.Container;if(n){this.isFunctionCall||r.AddContent(Hn.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let s=0;s<this.args.length;++s){let o=this.args[s],l=null;if(a&&s<a.length&&(l=a[s]),l&&l.isByReference){let u=(0, zn.asOrNull)(o,yh.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let h=new gh.Path(u.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let p=new Qf.VariablePointerValue(u.name);r.AddContent(p);}else o.GenerateIntoContainer(r);}this.isFunctionCall||r.AddContent(Hn.ControlCommand.EvalEnd());}return this.isThread?r.AddContent(Hn.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Ch.PushPopType.Function:Ch.PushPopType.Tunnel),r.AddContent(this.runtimeDivert),r}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let r=(0, zn.asOrNull)((0, Zf.ClosestFlowBase)(this),vo.FlowBase);if(r){let a=r.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});s&&!s.isDivertTarget&&this.Error(`Since '${s.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${s.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let r=(0, zn.asOrNull)(this.targetContent,vo.FlowBase);if(n===0&&(r===null||!r.hasParameters))return;if(r===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(r!==null&&(r.args===null||!r.args&&n>0)){this.Error(`target (${r.name}) doesn't take parameters`);return}else if(this.parent instanceof yo.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=r.args.length;if(a!==n){let s;n===0?s="but there weren't any passed to it":n<a?s=`but only got ${n}`:s=`but got ${n}`,this.Error(`to '${r.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=r.args[s],l=this.args[s];if(o.isDivertTarget){let u=(0, zn.asOrNull)(l,yh.VariableReference);if(!(l instanceof yo.DivertTarget)&&u===null)this.Error(`Target '${r.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${l}`,l);else if(u){let h=new gh.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(r===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let r=this.target?this.target.firstComponent:null,a=n.externals.get(r);if(!a)throw new Error("external not found");let s=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==s&&this.Error(`incorrect number of arguments sent to external function '${r}'. Expected ${s} but got ${o}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, zn.asOrNull)(this.targetContent,vo.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof yo.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let n=this.targetContent!==null,r=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(r=Kf.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),r||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new Yf.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!r&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,n=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,n):super.Error(`Divert ${e}`,t,n);}};Rr.Divert=So;});var vh=x(Lr=>{Object.defineProperty(Lr,"__esModule",{value:true});Lr.GatherPointToResolve=void 0;var Eo=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};Lr.GatherPointToResolve=Eo;});var Sh=x(Br=>{Object.defineProperty(Br,"__esModule",{value:true});Br.SequenceDivertToResolve=void 0;var Do=class{constructor(e,t){this.divert=e,this.targetContent=t;}};Br.SequenceDivertToResolve=Do;});var bo=x(Wr=>{Object.defineProperty(Wr,"__esModule",{value:true});Wr.SequenceType=void 0;var Eh;(function(i){i[i.Stopping=1]="Stopping",i[i.Cycle=2]="Cycle",i[i.Shuffle=4]="Shuffle",i[i.Once=8]="Once";})(Eh||(Wr.SequenceType=Eh={}));});var wo=x(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.Sequence=void 0;var Dh=ie(),Je=fe(),Ao=et(),Un=ee(),jr=Ze(),em=Q(),tm=Sh(),qr=bo(),nm=Bt(),xo=class extends em.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new Dh.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(Je.ControlCommand.EvalStart()),n.AddContent(Je.ControlCommand.VisitIndex());let r=(this.sequenceType&qr.SequenceType.Once)>0,a=(this.sequenceType&qr.SequenceType.Cycle)>0,s=(this.sequenceType&qr.SequenceType.Stopping)>0,o=(this.sequenceType&qr.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(r&&(l+=1),s||r?(n.AddContent(new Un.IntValue(l-1)),n.AddContent(jr.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new Un.IntValue(this.sequenceElements.length)),n.AddContent(jr.NativeFunctionCall.CallWithName("%"))),o){let h=Je.ControlCommand.NoOp();if(r||s){let p=s?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(Je.ControlCommand.Duplicate()),n.AddContent(new Un.IntValue(p)),n.AddContent(jr.NativeFunctionCall.CallWithName("=="));let f=new Ao.Divert;f.isConditional=true,n.AddContent(f),this.AddDivertToResolve(f,h);}let c=this.sequenceElements.length;s&&(c-=1),n.AddContent(new Un.IntValue(c)),n.AddContent(Je.ControlCommand.SequenceShuffleIndex()),(r||s)&&n.AddContent(h);}n.AddContent(Je.ControlCommand.EvalEnd());let u=Je.ControlCommand.NoOp();for(let h=0;h<l;h+=1){n.AddContent(Je.ControlCommand.EvalStart()),n.AddContent(Je.ControlCommand.Duplicate()),n.AddContent(new Un.IntValue(h)),n.AddContent(jr.NativeFunctionCall.CallWithName("==")),n.AddContent(Je.ControlCommand.EvalEnd());let c=new Ao.Divert;c.isConditional=true,n.AddContent(c);let p;h<this.sequenceElements.length?p=this.sequenceElements[h].runtimeObject:p=new Dh.Container,p.name=`s${h}`,p.InsertContent(Je.ControlCommand.PopEvaluatedValue(),0);let f=new Ao.Divert;p.AddContent(f),n.AddToNamedContentOnly(p),this.AddDivertToResolve(c,p),this.AddDivertToResolve(f,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,r)=>{this._sequenceDivertsToResolve.push(new tm.SequenceDivertToResolve(n,r));},this.sequenceType=t,this.sequenceElements=[];for(let n of e){let r=n.content,a=null;r===null||r.length===0?a=n:a=new nm.Weave(r),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};Mr.Sequence=xo;});var Oo=x(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.TunnelOnwards=void 0;var im=ie(),Kn=fe(),rm=et(),sm=ee(),am=Q(),om=Vt(),lm=H(),um=cn(),_o=class extends am.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new im.Container;if(e.AddContent(Kn.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(s==-1&&u.commandType===Kn.ControlCommand.CommandType.EvalStart?s=l:u.commandType===Kn.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=s+1;l<o;l+=1){let u=n.content[l];u.parent=null,e.AddContent(n.content[l]);}}}let r=(0, lm.asOrNull)(t,rm.Divert);if(r!=null&&r.hasVariableTarget){let a=new um.VariableReference(r.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new sm.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new om.Void);return e.AddContent(Kn.ControlCommand.EvalEnd()),e.AddContent(Kn.ControlCommand.PopTunnel()),e},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};Gr.TunnelOnwards=_o;});var Fo=x($r=>{Object.defineProperty($r,"__esModule",{value:true});$r.ListDefinition=void 0;var To=_e(),Po=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let n=new To.InkListItem(this.name,e);this._items.set(n.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?false:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[n,r]of this._itemNameToValues)if(r==e)return t=new To.InkListItem(this.name,n),{result:t,exists:true};return t=To.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(e.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};$r.ListDefinition=Po;});var Hr=x(Jr=>{Object.defineProperty(Jr,"__esModule",{value:true});Jr.ListDefinition=void 0;var hm=_e(),cm=_e(),dm=Fo(),pm=ee(),fm=Q(),mm=ct(),No=class extends fm.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let n of this.itemDefinitions)t.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):t.set(n.name,n.seriesValue);return new dm.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,r;let a=new hm.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new cm.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((r=this.identifier)===null||r===void 0?void 0:r.name)||""),new pm.ListValue(a)};let t=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(t=n.explicitValue),n.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,mm.SymbolType.List);}};Jr.ListDefinition=No;});var Vo=x(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.VariableAssignment=void 0;var gm=ie(),Cm=$n(),ym=Hr(),vm=Q(),bh=ct(),Sm=vt(),Em=dn(),Dm=H(),Io=class extends vm.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:n,listDef:r,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, Cm.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new gm.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Sm.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!n,r instanceof ym.ListDefinition?(this.listDefinition=this.AddContent(r),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?bh.SymbolType.Var:bh.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, Dm.asOrNull)(this.expression,Em.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};zr.VariableAssignment=Io;});var Bt=x(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.Weave=void 0;var Ah=Fi(),We=an(),Ur=pr(),bm=gr(),Am=ie(),Kr=hn(),xm=et(),wm=un(),_m=tt(),rt=Gn(),Om=vh(),Tm=Q(),ko=wo(),Pm=Et(),Fm=Oo(),Nm=Vo(),je=H(),Ro=class i extends Tm.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let n=this.content.length-1;n>=0;--n){e=this.content[n];let r=(0, je.asOrNull)(e,Pm.Text);if(!(r&&r.text===`
15
+ `)&&!this.IsGlobalDeclaration(e))break}let t=(0, je.asOrNull)(e,i);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var n,r,a;let s=[...this.FindAll(rt.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(We.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof rt.Gather?"gather":"choice",h=l;this.Error(`A ${u} with the same label name '${o.name}' already exists in this context on line ${h.debugMetadata?h.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((r=o.identifier)===null||r===void 0)&&r.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;n<this.content.length;){let r=this.content[n];if(r instanceof We.Choice||r instanceof rt.Gather){let s=r.indentationDepth-1;if(s>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let c=(0, je.asOrNull)(this.content[n],We.Choice)||(0, je.asOrNull)(this.content[n],rt.Gather);if(c!==null&&c.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let l=n-o,u=this.content.slice(o,o+l);this.content.splice(o,l);let h=new i(u,s);this.InsertContent(o,h),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let r of n)if(r instanceof We.Choice||r instanceof rt.Gather)return r.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new Am.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof We.Choice||n instanceof rt.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof i){let r=n;this.AddRuntimeForNestedWeave(r),this.gatherPointsToResolve.splice(0,0,...r.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let r=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),r){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let s of this.looseEnds){let o=s;if(o instanceof rt.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof Kr.Divert)l=o.runtimeObject;else {l=new xm.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new Om.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof rt.Gather)this.AddRuntimeForGather(n);else if(n instanceof We.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof rt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let r=n;if(this.currentContainer.AddContent(r.runtimeObject),!r.innerContentContainer)throw new Error;r.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(r.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, je.asOrNull)(n,We.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=n;},this.AddRuntimeForNestedWeave=n=>{this.AddGeneralRuntimeContent(n.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=n=>{if(n!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(n);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let n=null,r=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, je.asOrNull)(s,i);o&&(!a&&n===null&&(n=o),a&&r===null&&(r=o)),(s instanceof ko.Sequence||s instanceof Ur.Conditional)&&(a=true);}if(!(n===null&&r===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],l=false;if(a){if(o instanceof We.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof We.Choice)){let u=n||r;u!==null&&(u.ReceiveLooseEnd(o),l=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(o),l=true;l&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let r=this.namedWeavePoints.get(n);return r||null},this.IsGlobalDeclaration=n=>{let r=(0, je.asOrNull)(n,Nm.VariableAssignment);return !!(r&&r.isGlobalDeclaration&&r.isDeclaration||(0, je.asOrNull)(n,bm.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let r=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||r.push(l);let s=(0, je.asOrNull)(a.parent,i);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let l=o+1;l<s.content.length;l+=1){let u=s.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof We.Choice||u instanceof rt.Gather||u instanceof i)break;r.push(u);}}return r},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof Ah.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let s=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(s,a,n);}else {for(let a of this.content)if(a instanceof We.Choice||a instanceof Kr.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let r=null;for(let s=n.parent;s!==null;s=s.parent)if(s instanceof ko.Sequence||s instanceof Ur.Conditional){r=(0, je.asOrNull)(s,Ur.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";r!==null&&r.FindAll(We.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,r,a)=>{let s=false,o=r;for(let l of n){if(l.Find(Kr.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof wm.DivertTarget))!==null&&(s=true),l.Find(Fm.TunnelOnwards)()!=null){s=true;break}o=l;}if(!s){if(o instanceof Ah.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return true;for(let r=n.content.length-1;r>=0;--r){let a=(0, je.asOrNull)(n.content[r],Kr.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let r of this.ancestry){let a=(0, je.asOrNull)(r,_m.FlowBase);if(a)n.push(a);else break}for(let[r,a]of this.namedWeavePoints)for(let s of n){let o=s.ContentWithNameAtLevel(r);if(o&&o!==a){let l=`${a.GetType()} '${r}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(l,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof ko.Sequence||n instanceof Ur.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};Xr.Weave=Ro;});var Co=x(Qr=>{Object.defineProperty(Qr,"__esModule",{value:true});Qr.ConditionalSingleBranch=void 0;var xh=ie(),Yr=fe(),wh=et(),Im=Q(),Vm=Ze(),km=ee(),Rm=Et(),Lm=Bt(),Bm=H(),Lo=class extends Im.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let r of this._innerWeave.content){let a=(0, Bm.asOrNull)(r,Rm.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new xh.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(Yr.ControlCommand.Duplicate()),this._conditionalDivert=new wh.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let r=this.ownExpression!==null;r&&t.AddContent(Yr.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(Vm.NativeFunctionCall.CallWithName("==")),r&&t.AddContent(Yr.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new km.StringValue(`
16
+ `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Yr.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new wh.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new xh.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new Lm.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};Qr.ConditionalSingleBranch=Lo;});var Oh=x(Zr=>{Object.defineProperty(Zr,"__esModule",{value:true});Zr.CustomFlags=void 0;var _h;(function(i){i[i.ParsingString=1]="ParsingString",i[i.TagActive=2]="TagActive";})(_h||(Zr.CustomFlags=_h={}));});var Th=x(es=>{Object.defineProperty(es,"__esModule",{value:true});es.DebugMetadata=void 0;var Bo=class i{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new i;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumber<e.startLineNumber?(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>e.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<e.endLineNumber?(t.endLineNumber=e.endLineNumber,t.endCharacterNumber=e.endCharacterNumber):(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=Math.max(this.endCharacterNumber,e.endCharacterNumber)),t}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};es.DebugMetadata=Bo;});var Ph=x(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.ExternalDeclaration=void 0;var Wm=Q(),Wo=class extends Wm.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};ts.ExternalDeclaration=Wo;});var Fh=x(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.FlowDecl=void 0;var jo=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};ns.FlowDecl=jo;});var Mo=x(is=>{Object.defineProperty(is,"__esModule",{value:true});is.Wrap=void 0;var jm=Q(),qo=class extends jm.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};is.Wrap=qo;});var Nh=x(rs=>{Object.defineProperty(rs,"__esModule",{value:true});rs.Glue=void 0;var qm=Mo(),Go=class extends qm.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};rs.Glue=Go;});var as=x(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.Glue=void 0;var Mm=xe(),$o=class extends Mm.InkObject{toString(){return "Glue"}};ss.Glue=$o;});var Vh=x(os=>{Object.defineProperty(os,"__esModule",{value:true});os.IncDecExpression=void 0;var Gm=_r(),Ih=Le(),$m=tt(),Jm=Ze(),Hm=ee(),zm=vt(),Um=cn(),Km=Bt(),Jo=class extends Ih.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=r=>{var a,s;r.AddContent(new Um.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(r):r.AddContent(new Hm.IntValue(1)),r.AddContent(Jm.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new zm.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),r.AddContent(this._runtimeAssignment);},this.toString=()=>{var r,a;return this.expression?`${(r=this.varIdentifier)===null||r===void 0?void 0:r.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof Ih.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!n):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let n=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof Km.Weave)&&!(this.parent instanceof $m.FlowBase)&&!(this.parent instanceof Gm.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};os.IncDecExpression=Jo;});var zo=x(ls=>{Object.defineProperty(ls,"__esModule",{value:true});ls.IncludedFile=void 0;var Xm=Q(),Ho=class extends Xm.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};ls.IncludedFile=Ho;});var kh=x(us=>{Object.defineProperty(us,"__esModule",{value:true});us.InfixOperator=void 0;var Uo=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};us.InfixOperator=Uo;});var Xo=x(hs=>{Object.defineProperty(hs,"__esModule",{value:true});hs.Knot=void 0;var Ym=tt(),Rh=on(),Ko=class extends Ym.FlowBase{get flowLevel(){return Rh.FlowLevel.Knot}constructor(e,t,n,r){super(e,t,n,r);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let n in this.subFlowsByName){let r=t.ContentWithNameAtLevel(n,Rh.FlowLevel.Knot,false);if(r){let a=this.subFlowsByName.get(n),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${r.debugMetadata})`;this.Error(s,a);}}}};hs.Knot=Ko;});var Lh=x(cs=>{Object.defineProperty(cs,"__esModule",{value:true});cs.List=void 0;var Qm=Le(),Zm=_e(),eg=_e(),tg=ee(),Yo=class extends Qm.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,r;let a=new Zm.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((n=s?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";o.length>1?(l=o[0],u=o[1]):u=o[0];let h=this.story.ResolveListItem(l,u,this);if(h===null)l===null?this.Error(`Could not find list definition that contains item '${s}'`):this.Error(`Could not find list item ${s}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${s}`);return}l||(l=((r=h.parent.identifier)===null||r===void 0?void 0:r.name)||null);let c=new eg.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(c,h.seriesValue);}}t.AddContent(new tg.ListValue(a));};}get typeName(){return "List"}};cs.List=Yo;});var Zo=x(ds=>{Object.defineProperty(ds,"__esModule",{value:true});ds.ListElementDefinition=void 0;var ng=Q(),ig=ct(),Qo=class extends ng.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,n=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=n,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,ig.SymbolType.ListItem);}};ds.ListElementDefinition=Qo;});var el=x(ps=>{Object.defineProperty(ps,"__esModule",{value:true});ps.StatementLevel=void 0;var Bh;(function(i){i[i.InnerBlock=0]="InnerBlock",i[i.Stitch=1]="Stitch",i[i.Knot=2]="Knot",i[i.Top=3]="Top";})(Bh||(ps.StatementLevel=Bh={}));});var nl=x(fs=>{Object.defineProperty(fs,"__esModule",{value:true});fs.Stitch=void 0;var rg=tt(),sg=on(),tl=class extends rg.FlowBase{get flowLevel(){return sg.FlowLevel.Stitch}constructor(e,t,n,r){super(e,t,n,r),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};fs.Stitch=tl;});var gs=x(ms=>{Object.defineProperty(ms,"__esModule",{value:true});ms.Tag=void 0;var ag=xe(),il=class extends ag.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};ms.Tag=il;});var sl=x(Cs=>{Object.defineProperty(Cs,"__esModule",{value:true});Cs.Choice=void 0;var og=Ae(),lg=pe(),ug=xe(),rl=class i extends ug.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, lg.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new og.Path(e);}Clone(){let e=new i;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};Cs.Choice=rl;});var ol=x(ys=>{Object.defineProperty(ys,"__esModule",{value:true});ys.ListDefinitionsOrigin=void 0;var hg=_e(),cg=ee(),dg=pe(),al=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[n,r]of t.items){let a=hg.InkListItem.fromSerializedKey(n),s=new cg.ListValue(a,r);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,s),this._allUnambiguousListValueCache.set(a.fullName,s);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let n=this._lists.get(e);return n?{result:n,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, dg.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};ys.ListDefinitionsOrigin=al;});var fn=x(Ds=>{Object.defineProperty(Ds,"__esModule",{value:true});Ds.JsonSerialisation=void 0;var vs=ie(),Te=ee(),Wh=as(),j=fe(),pn=kt(),jh=et(),qh=Zi(),ll=cn(),Mh=vt(),ul=Ze(),Gh=Vt(),$h=gs(),pg=Ae(),Jh=sl(),fg=Fo(),mg=ol(),Ss=_e(),re=H(),Wt=pe(),Es=class i{static JArrayToRuntimeObjList(e,t=false){let n=e.length;t&&n--;let r=[];for(let a=0;a<n;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, Wt.throwNullException)("runtimeObj");r.push(o);}return r}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[n,r]of t)e.WritePropertyStart(n),this.WriteRuntimeObject(e,r),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let n of t)this.WriteRuntimeObject(e,n);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[n,r]of t)e.WriteIntProperty(n,r);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let n=(0, re.asOrNull)(t,vs.Container);if(n){this.WriteRuntimeContainer(e,n);return}let r=(0, re.asOrNull)(t,jh.Divert);if(r){let m="->";r.isExternal?m="x()":r.pushesToStack&&(r.stackPushType==pn.PushPopType.Function?m="f()":r.stackPushType==pn.PushPopType.Tunnel&&(m="->t->"));let S;r.hasVariableTarget?S=r.variableDivertName:S=r.targetPathString,e.WriteObjectStart(),e.WriteProperty(m,S),r.hasVariableTarget&&e.WriteProperty("var",true),r.isConditional&&e.WriteProperty("c",true),r.externalArgs>0&&e.WriteIntProperty("exArgs",r.externalArgs),e.WriteObjectEnd();return}let a=(0, re.asOrNull)(t,qh.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, re.asOrNull)(t,Te.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, re.asOrNull)(t,Te.IntValue);if(o){e.WriteInt(o.value);return}let l=(0, re.asOrNull)(t,Te.FloatValue);if(l){e.WriteFloat(l.value);return}let u=(0, re.asOrNull)(t,Te.StringValue);if(u){u.isNewline?e.Write(`
17
+ `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(u.value),e.WriteStringEnd());return}let h=(0, re.asOrNull)(t,Te.ListValue);if(h){this.WriteInkList(e,h);return}let c=(0, re.asOrNull)(t,Te.DivertTargetValue);if(c){if(e.WriteObjectStart(),c.value===null)return (0, Wt.throwNullException)("divTargetVal.value");e.WriteProperty("^->",c.value.componentsString),e.WriteObjectEnd();return}let p=(0, re.asOrNull)(t,Te.VariablePointerValue);if(p){e.WriteObjectStart(),e.WriteProperty("^var",p.value),e.WriteIntProperty("ci",p.contextIndex),e.WriteObjectEnd();return}if((0, re.asOrNull)(t,Wh.Glue)){e.Write("<>");return}let v=(0, re.asOrNull)(t,j.ControlCommand);if(v){e.Write(i._controlCommandNames[v.commandType]);return}let g=(0, re.asOrNull)(t,ul.NativeFunctionCall);if(g){let m=g.name;m=="^"&&(m="L^"),e.Write(m);return}let A=(0, re.asOrNull)(t,ll.VariableReference);if(A){e.WriteObjectStart();let m=A.pathStringForCount;m!=null?e.WriteProperty("CNT?",m):e.WriteProperty("VAR?",A.name),e.WriteObjectEnd();return}let D=(0, re.asOrNull)(t,Mh.VariableAssignment);if(D){e.WriteObjectStart();let m=D.isGlobal?"VAR=":"temp=";e.WriteProperty(m,D.variableName),D.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, re.asOrNull)(t,Gh.Void)){e.Write("void");return}let d=(0, re.asOrNull)(t,$h.Tag);if(d){e.WriteObjectStart(),e.WriteProperty("#",d.text),e.WriteObjectEnd();return}let E=(0, re.asOrNull)(t,Jh.Choice);if(E){this.WriteChoice(e,E);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let r=this.JTokenToRuntimeObject(e[n]);if(r===null)return (0, Wt.throwNullException)("inkObject");t.set(n,r);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let n in e)e.hasOwnProperty(n)&&t.set(n,parseInt(e[n]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return Te.Value.Create(e);if(typeof e=="string"){let t=e.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(t);if(n)return new Te.FloatValue(parseFloat(n[0]));let r=t[0];if(r=="^")return new Te.StringValue(t.substring(1));if(r==`
18
+ `&&t.length==1)return new Te.StringValue(`
19
+ `);if(t=="<>")return new Wh.Glue;for(let a=0;a<i._controlCommandNames.length;++a){let s=i._controlCommandNames[a];if(t==s)return new j.ControlCommand(a)}if(t=="L^"&&(t="^"),ul.NativeFunctionCall.CallExistsWithName(t))return ul.NativeFunctionCall.CallWithName(t);if(t=="->->")return j.ControlCommand.PopTunnel();if(t=="~ret")return j.ControlCommand.PopFunction();if(t=="void")return new Gh.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new Te.DivertTargetValue(new pg.Path(n.toString()));if(t["^var"]){n=t["^var"];let h=new Te.VariablePointerValue(n.toString());return "ci"in t&&(n=t.ci,h.contextIndex=parseInt(n)),h}let r=false,a=false,s=pn.PushPopType.Function,o=false;if((n=t["->"])?r=true:(n=t["f()"])?(r=true,a=true,s=pn.PushPopType.Function):(n=t["->t->"])?(r=true,a=true,s=pn.PushPopType.Tunnel):(n=t["x()"])&&(r=true,o=true,a=false,s=pn.PushPopType.Function),r){let h=new jh.Divert;h.pushesToStack=a,h.stackPushType=s,h.isExternal=o;let c=n.toString();return (n=t.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!t.c,o&&(n=t.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=t["*"]){let h=new qh.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=t.flg)&&(h.flags=parseInt(n)),h}if(n=t["VAR?"])return new ll.VariableReference(n.toString());if(n=t["CNT?"]){let h=new ll.VariableReference;return h.pathStringForCount=n.toString(),h}let l=false,u=false;if((n=t["VAR="])?(l=true,u=true):(n=t["temp="])&&(l=true,u=false),l){let h=n.toString(),c=!t.re,p=new Mh.VariableAssignment(h,c);return p.isGlobal=u,p}if(t["#"]!==void 0)return n=t["#"],new $h.Tag(n.toString());if(n=t.list){let h=n,c=new Ss.InkList;if(n=t.origins){let p=n;c.SetInitialOriginNames(p);}for(let p in h)if(h.hasOwnProperty(p)){let f=h[p],v=new Ss.InkListItem(p),g=parseInt(f);c.Add(v,g);}return new Te.ListValue(c)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,n){return JSON.stringify(e,(r,a)=>t?.some(s=>s===r)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=false){if(e.WriteArrayStart(),t===null)return (0, Wt.throwNullException)("container");for(let l of t.content)this.WriteRuntimeObject(e,l);let r=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!n,o=r!=null||a>0||s;if(o&&e.WriteObjectStart(),r!=null)for(let[l,u]of r){let h=l,c=(0, re.asOrNull)(u,vs.Container);e.WritePropertyStart(h),this.WriteRuntimeContainer(e,c,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),s&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new vs.Container;t.content=this.JArrayToRuntimeObjList(e,true);let n=e[e.length-1];if(n!=null){let r=new Map;for(let a in n)if(a=="#f")t.countFlags=parseInt(n[a]);else if(a=="#n")t.name=n[a].toString();else {let s=this.JTokenToRuntimeObject(n[a]),o=(0, re.asOrNull)(s,vs.Container);o&&(o.name=a),r.set(a,s);}t.namedOnlyContent=r;}return t}static JObjectToChoice(e){let t=new Jh.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t.isInvisibleDefault=!!e.isInvisibleDefault,t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),e.WriteProperty("isInvisibleDefault",t.isInvisibleDefault),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, Wt.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[r,a]of n){let s=Ss.InkListItem.fromSerializedKey(r),o=a;if(s.itemName===null)return (0, Wt.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(s.originName?s.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(s.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let r of n.originNames)e.Write(r);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let r={};for(let[a,s]of n.items){let o=Ss.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Wt.throwNullException)("item.itemName");r[o.itemName]=s;}t[n.name]=r;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let r in t)if(t.hasOwnProperty(r)){let a=r.toString(),s=t[r],o=new Map;for(let u in s)if(t.hasOwnProperty(r)){let h=s[u];o.set(u,parseInt(h));}let l=new fg.ListDefinition(a,o);n.push(l);}return new mg.ListDefinitionsOrigin(n)}};Ds.JsonSerialisation=Es;Es._controlCommandNames=(()=>{let i=[];i[j.ControlCommand.CommandType.EvalStart]="ev",i[j.ControlCommand.CommandType.EvalOutput]="out",i[j.ControlCommand.CommandType.EvalEnd]="/ev",i[j.ControlCommand.CommandType.Duplicate]="du",i[j.ControlCommand.CommandType.PopEvaluatedValue]="pop",i[j.ControlCommand.CommandType.PopFunction]="~ret",i[j.ControlCommand.CommandType.PopTunnel]="->->",i[j.ControlCommand.CommandType.BeginString]="str",i[j.ControlCommand.CommandType.EndString]="/str",i[j.ControlCommand.CommandType.NoOp]="nop",i[j.ControlCommand.CommandType.ChoiceCount]="choiceCnt",i[j.ControlCommand.CommandType.Turns]="turn",i[j.ControlCommand.CommandType.TurnsSince]="turns",i[j.ControlCommand.CommandType.ReadCount]="readc",i[j.ControlCommand.CommandType.Random]="rnd",i[j.ControlCommand.CommandType.SeedRandom]="srnd",i[j.ControlCommand.CommandType.VisitIndex]="visit",i[j.ControlCommand.CommandType.SequenceShuffleIndex]="seq",i[j.ControlCommand.CommandType.StartThread]="thread",i[j.ControlCommand.CommandType.Done]="done",i[j.ControlCommand.CommandType.End]="end",i[j.ControlCommand.CommandType.ListFromInt]="listInt",i[j.ControlCommand.CommandType.ListRange]="range",i[j.ControlCommand.CommandType.ListRandom]="lrnd",i[j.ControlCommand.CommandType.BeginTag]="#",i[j.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<j.ControlCommand.CommandType.TOTAL_VALUES;++e)if(i[e]==null)throw new Error("Control command not accounted for in serialisation");return i})();});var dl=x(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.CallStack=void 0;var hl=kt(),Hh=Ae(),gg=Zn(),zh=fn(),Cg=ee(),yg=Nt(),Xn=qn(),vg=On(),Uh=tn(),cl=pe(),Yn=class i{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){vg.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=Xn.Pointer.Null,arguments[0]instanceof gg.Story){let e=arguments[0];this._startOfRoot=Xn.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new i.Thread),this._threads[0].callstack.push(new i.Element(hl.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let r of n){let a=r,s=new i.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=Xn.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let n of this._threads)n.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==hl.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let r=new i.Element(e,this.currentElement.currentPointer,false);r.evaluationStackHeightWhenPushed=t,r.functionStartInOutputStream=n,this.callStack.push(r);}CanPop(e=null){return this.canPop?e==null?true:this.currentElement.type==e:false}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let n=this.callStack[t-1],r=(0, Uh.tryGetValueFromMap)(n.temporaryVariables,e,null);return r.exists?r.result:null}SetTemporaryVariable(e,t,n,r=-1){r==-1&&(r=this.currentElementIndex+1);let a=this.callStack[r-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, Uh.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&Cg.ListValue.RetainListOriginsForAssignment(s.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new yg.StringBuilder;for(let t=0;t<this._threads.length;t++){let n=this._threads[t],r=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
20
+ `,t+1,this._threads.length,r?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==hl.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=n.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, cl.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Qn.CallStack=Yn;(function(i){class e{constructor(r,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=r;}Copy(){let r=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return r.temporaryVariables=new Map(this.temporaryVariables),r.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,r.functionStartInOutputStream=this.functionStartInOutputStream,r}}i.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=Xn.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let r=arguments[0],a=arguments[1];this.threadIndex=parseInt(r.threadIndex);let s=r.callstack;for(let l of s){let u=l,h=parseInt(u.type),c=Xn.Pointer.Null,p,f=u.cPath;if(typeof f<"u"){p=f.toString();let D=a.ContentAtPath(new Hh.Path(p));if(c.container=D.container,c.index=parseInt(u.idx),D.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+p+". Has the story changed since this save data was created?");D.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+p+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+p+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let v=!!u.exp,g=new e(h,c,v),A=u.temp;typeof A<"u"?g.temporaryVariables=zh.JsonSerialisation.JObjectToDictionaryRuntimeObjs(A):g.temporaryVariables.clear(),this.callstack.push(g);}let o=r.previousContentObject;if(typeof o<"u"){let l=new Hh.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let r=new t;r.threadIndex=this.threadIndex;for(let a of this.callstack)r.callstack.push(a.Copy());return r.previousPointer=this.previousPointer.copy(),r}WriteJson(r){r.WriteObjectStart(),r.WritePropertyStart("callstack"),r.WriteArrayStart();for(let a of this.callstack){if(r.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, cl.throwNullException)("el.currentPointer.container");r.WriteProperty("cPath",a.currentPointer.container.path.componentsString),r.WriteIntProperty("idx",a.currentPointer.index);}r.WriteProperty("exp",a.inExpressionEvaluation),r.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(r.WritePropertyStart("temp"),zh.JsonSerialisation.WriteDictionaryRuntimeObjs(r,a.temporaryVariables),r.WritePropertyEnd()),r.WriteObjectEnd();}if(r.WriteArrayEnd(),r.WritePropertyEnd(),r.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, cl.throwNullException)("this.previousPointer.Resolve()");r.WriteProperty("previousContentObject",a.path.toString());}r.WriteObjectEnd();}}i.Thread=t;})(Yn||(Qn.CallStack=Yn={}));});var Xh=x(As=>{Object.defineProperty(As,"__esModule",{value:true});As.VariablesState=void 0;var de=ee(),Sg=Pn(),Kh=fn(),me=H(),ei=tn(),Dt=pe();function Eg(){return class{}}var bs=class i extends Eg(){variableChangedEvent(e,t){for(let n of this.variableChangedEventCallbacks)n(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let n=this._globalVariables.get(t);this.variableChangedEvent(t,n);}if(this.patch!=null)for(let t of this.patch.changedVariables){let n=this.patch.TryGetGlobal(t,null);n.exists&&e.set(t,n);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,n]of e)this.variableChangedEvent(t,n);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(e),typeof n>"u"&&(n=this._defaultGlobalVariables.get(e)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new Sg.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=de.Value.Create(t);if(n==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,n);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(r,a){return a in r?r[a]:r.$(a)},set(r,a,s){return a in r?r[a]=s:r.$(a,s),!0},ownKeys(r){return [...new Set([...r._defaultGlobalVariables.keys(),...r._globalVariables.keys()])]},getOwnPropertyDescriptor(r,a){return {enumerable:!0,configurable:!0,value:r.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Dt.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,n]of this._defaultGlobalVariables){let r=e[t];if(typeof r<"u"){let a=Kh.JsonSerialisation.JTokenToRuntimeObject(r);if(a===null)return (0, Dt.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let r=t,a=n;if(i.dontSaveDefaultValues&&this._defaultGlobalVariables.has(r)){let s=this._defaultGlobalVariables.get(r);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(r),Kh.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Dt.throwNullException)("obj1");if(t===null)return (0, Dt.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let n=(0, me.asOrNull)(e,de.BoolValue);if(n!==null)return n.value===(0, me.asOrThrows)(t,de.BoolValue).value;let r=(0, me.asOrNull)(e,de.IntValue);if(r!==null)return r.value===(0, me.asOrThrows)(t,de.IntValue).value;let a=(0, me.asOrNull)(e,de.FloatValue);if(a!==null)return a.value===(0, me.asOrThrows)(t,de.FloatValue).value;let s=(0, me.asOrNull)(e,de.Value),o=(0, me.asOrNull)(t,de.Value);if(s!==null&&o!==null)return (0, me.isEquatable)(s.valueObject)&&(0, me.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let n=this.GetRawVariableWithName(e,t),r=(0, me.asOrNull)(n,de.VariablePointerValue);return r!==null&&(n=this.ValueAtVariablePointer(r)),n}TryGetDefaultVariableValue(e){let t=(0, ei.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let n=null;if(t==0||t==-1){let r=null;if(this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists)||(r=(0, ei.tryGetValueFromMap)(this._globalVariables,e,null),r.exists)||this._defaultGlobalVariables!==null&&(r=(0, ei.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),r.exists))return r.result;if(this._listDefsOrigin===null)return (0, Dt.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(e,t),n}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let n=e.variableName;if(n===null)return (0, Dt.throwNullException)("name");let r=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let s=(0, me.asOrNull)(t,de.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, me.asOrNull)(this.GetRawVariableWithName(n,r),de.VariablePointerValue),s!=null&&(n=s.variableName,r=s.contextIndex,a=r==0);while(s!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,r);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, me.asOrThrows)(e,de.ListValue),r=(0, me.asOrThrows)(t,de.ListValue);n.value&&r.value&&r.value.Count==0&&r.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(e,t){let n=null;if(this.patch===null&&(n=(0, ei.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, ei.tryGetValueFromMap)(this._globalVariables,e,null))),de.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, Dt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&n!==null&&t!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Dt.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let n=this.GetRawVariableWithName(e.variableName,t),r=(0, me.asOrNull)(n,de.VariablePointerValue);return r??new de.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};As.VariablesState=bs;bs.dontSaveDefaultValues=true;});var fl=x(xs=>{Object.defineProperty(xs,"__esModule",{value:true});xs.PRNG=void 0;var pl=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};xs.PRNG=pl;});var Yh=x(ws=>{Object.defineProperty(ws,"__esModule",{value:true});ws.StatePatch=void 0;var ml=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:true}:{result:t,exists:false}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:true}:{result:t,exists:false}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:true}:{result:t,exists:false}}};ws.StatePatch=ml;});var gl=x(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.SimpleJson=void 0;var ti=class i{static TextToDictionary(e){return new i.Reader(e).ToDictionary()}static TextToArray(e){return new i.Reader(e).ToArray()}};ni.SimpleJson=ti;(function(i){class e{constructor(r){if(JSON.parse("0",(s,o,l)=>l!=null)){let s=(o,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(r,s);}else {let s=r.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}i.Reader=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(r){this.WriteObjectStart(),r(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let r={};if(this.state===i.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=r,this._collectionStack.push(r);}else this.state===i.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(r),this._collectionStack.push(r)):(this.Assert(this.state===i.Writer.State.None),this._jsonObject=r,this._collectionStack.push(r));this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===i.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(r,a){if(this.WritePropertyStart(r),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}this.WritePropertyEnd();}WriteIntProperty(r,a){this.WritePropertyStart(r),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(r,a){this.WritePropertyStart(r),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(r){this.Assert(this.state===i.Writer.State.Object),this._propertyNameStack.push(r),this.IncrementChildCount(),this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===i.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===i.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Property)),this._stateStack.push(new i.Writer.StateElement(i.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===i.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(r){this.Assert(this.state===i.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=r;}WriteArrayStart(){this.StartNewObject(true);let r=[];if(this.state===i.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=r,this._collectionStack.push(r);}else this.state===i.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(r),this._collectionStack.push(r)):(this.Assert(this.state===i.Writer.State.None),this._jsonObject=r,this._collectionStack.push(r));this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===i.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(r,a=true){if(r===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(r);}WriteBool(r){r!==null&&(this.StartNewObject(false),this._addToCurrentObject(r));}WriteInt(r){r!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(r)));}WriteFloat(r){r!==null&&(this.StartNewObject(false),r==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):r==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(r)?this._addToCurrentObject(0):this._addToCurrentObject(r));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new i.Writer.StateElement(i.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==i.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(r,a=true){if(this.Assert(this.state===i.Writer.State.String),r===null){console.error("Warning: trying to write a null string");return}this._currentString+=r;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(r){r?this.Assert(this.state===i.Writer.State.None||this.state===i.Writer.State.Property||this.state===i.Writer.State.Array):this.Assert(this.state===i.Writer.State.Property||this.state===i.Writer.State.Array),this.state===i.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===i.Writer.State.Array||this.state===i.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:i.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let r=this._stateStack.pop();r.childCount++,this._stateStack.push(r);}Assert(r){if(!r)throw Error("Assert failed while writing JSON")}_addToCurrentObject(r){this.Assert(this.currentCollection!==null),this.state===i.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(r)):this.state===i.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=r,this._propertyNameStack.pop());}}i.Writer=t,(function(n){(function(s){s[s.None=0]="None",s[s.Object=1]="Object",s[s.Array=2]="Array",s[s.Property=3]="Property",s[s.PropertyName=4]="PropertyName",s[s.String=5]="String";})(n.State||(n.State={}));class a{constructor(o){this.type=i.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;})(t=i.Writer||(i.Writer={}));})(ti||(ni.SimpleJson=ti={}));});var Zh=x(Os=>{Object.defineProperty(Os,"__esModule",{value:true});Os.Flow=void 0;var Qh=dl(),_s=fn(),Dg=pe(),Cl=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new Qh.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=_s.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=_s.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let r=n.choiceThreads;typeof r<"u"&&this.LoadFlowChoiceThreads(r,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),e.WriteProperty("outputStream",n=>_s.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, Dg.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let r of this.currentChoices)_s.JsonSerialisation.WriteChoice(n,r);n.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let n of this.currentChoices){let r=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(r!==null)n.threadAtGeneration=r.Copy();else {let a=e[`${n.originalThreadIndex}`];n.threadAtGeneration=new Qh.CallStack.Thread(a,t);}}}};Os.Flow=Cl;});var nc=x(Ps=>{Object.defineProperty(Ps,"__esModule",{value:true});Ps.StoryState=void 0;var bg=dl(),Ag=Xh(),ue=ee(),bt=kt(),xg=gs(),yl=as(),ec=Ae(),Ee=fe(),vl=Nt(),At=fn(),wg=fl(),_g=Vt(),mn=qn(),ii=tn(),ae=H(),Og=On(),qe=pe(),Tg=Zn(),Pg=Yh(),tc=gl(),Ts=Zh(),Fg=_e(),Sl=class i{ToJson(e=false){let t=new tc.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=tc.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let n=this.story.ContentAtPath(new ec.Path(e)).container;if(n===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(n,0),t.exists)return t.result}return t=(0, ii.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, qe.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let r=this._patch.TryGetVisitCount(e,0);if(r.exists)return r.result}let t=e.path.toString(),n=(0, ii.tryGetValueFromMap)(this._visitCounts,t,null);return n.exists?n.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let r=this.VisitCountForContainer(e);r++,this._patch.SetVisitCount(e,r);return}let t=e.path.toString(),n=(0, ii.tryGetValueFromMap)(this._visitCounts,t,null);n.exists?this._visitCounts.set(t,n.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let r=this._patch.TryGetTurnIndex(e,0);if(r.exists)return this.currentTurnIndex-r.result}let t=e.path.toString(),n=(0, ii.tryGetValueFromMap)(this._turnIndices,t,0);return n.exists?this.currentTurnIndex-n.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, qe.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, qe.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new vl.StringBuilder,t=false;for(let n of this.outputStream){let r=(0, ae.asOrNull)(n,ue.StringValue);if(!t&&r!==null)e.Append(r.value);else {let a=(0, ae.asOrNull)(n,Ee.ControlCommand);a!==null&&(a.commandType==Ee.ControlCommand.CommandType.BeginTag?t=true:a.commandType==Ee.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new vl.StringBuilder,n=-1,r=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&n==-1&&(n=a),o||(s!=`
21
21
  `&&n>0&&n!=r&&t.Append(" "),n=-1),s==`
22
- `&&(r=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new kl.StringBuilder;for(let n of this.outputStream){let r=(0, le.asOrNull)(n,Te.ControlCommand);if(r!=null){if(r.commandType==Te.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(r.commandType==Te.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=false;}}else if(e){let a=(0, le.asOrNull)(n,ce.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, le.asOrNull)(n,aC.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let n=this.CleanOutputWhitespace(t.toString());this._currentTags.push(n),t.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=_n.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=e,this._currentFlow=new Ms.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new sC.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new oC.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=_n.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,n=(0, gi.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new Ms.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=true),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, Qe.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new i(this.story);if(t._patch=new cC.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new rC.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let n of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(n.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[n,r]of this._namedFlows)t._namedFlows.set(n,r),t._aliveFlowNamesDirty=true;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,true);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,false);this._patch=null;}}ApplyCountChanges(e,t,n){(n?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,n]of this._namedFlows)e.WriteProperty(t,r=>n.WriteJson(r));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>Rt.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, Qe.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Rt.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Rt.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",hC.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,n=t.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+n+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let r=t.flows;if(r!=null){let s=r;Object.keys(s).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(s);for(let[l,u]of o){let h=l,c=u,p=new Ms.Flow(h,this.story,c);if(Object.keys(s).length===1)this._currentFlow=new Ms.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, Qe.throwNullException)("this._namedFlows");this._namedFlows.set(h,p);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let l=t.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=Rt.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Rt.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let s=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Rt.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new yc.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=Rt.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Rt.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, le.asOrNull)(e,ce.StringValue);if(t!==null){let n=this.TrySplittingHeadTailWhitespace(t);if(n!==null){for(let r of n)this.PushToOutputStreamIndividual(r);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, Qe.throwNullException)("single.value");let n=-1,r=-1;for(let h=0;h<t.length;h++){let c=t[h];if(c==`
22
+ `&&(r=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new vl.StringBuilder;for(let n of this.outputStream){let r=(0, ae.asOrNull)(n,Ee.ControlCommand);if(r!=null){if(r.commandType==Ee.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(r.commandType==Ee.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=false;}}else if(e){let a=(0, ae.asOrNull)(n,ue.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, ae.asOrNull)(n,xg.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let n=this.CleanOutputWhitespace(t.toString());this._currentTags.push(n),t.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=mn.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=e,this._currentFlow=new Ts.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new Ag.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new wg.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=mn.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,n=(0, ii.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new Ts.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=true),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, qe.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new i(this.story);if(t._patch=new Pg.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new bg.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let n of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(n.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[n,r]of this._namedFlows)t._namedFlows.set(n,r),t._aliveFlowNamesDirty=true;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,true);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,false);this._patch=null;}}ApplyCountChanges(e,t,n){(n?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,n]of this._namedFlows)e.WriteProperty(t,r=>n.WriteJson(r));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>At.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, qe.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>At.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>At.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",Tg.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,n=t.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+n+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let r=t.flows;if(r!=null){let s=r;Object.keys(s).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(s);for(let[l,u]of o){let h=l,c=u,p=new Ts.Flow(h,this.story,c);if(Object.keys(s).length===1)this._currentFlow=new Ts.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, qe.throwNullException)("this._namedFlows");this._namedFlows.set(h,p);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let l=t.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=At.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=At.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let s=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=At.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new ec.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=At.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=At.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, ae.asOrNull)(e,ue.StringValue);if(t!==null){let n=this.TrySplittingHeadTailWhitespace(t);if(n!==null){for(let r of n)this.PushToOutputStreamIndividual(r);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, qe.throwNullException)("single.value");let n=-1,r=-1;for(let h=0;h<t.length;h++){let c=t[h];if(c==`
23
23
  `)n==-1&&(n=h),r=h;else {if(c==" "||c==" ")continue;break}}let a=-1,s=-1;for(let h=t.length-1;h>=0;h--){let c=t[h];if(c==`
24
- `)a==-1&&(a=h),s=h;else {if(c==" "||c==" ")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=t.length;if(n!=-1){if(n>0){let h=new ce.StringValue(t.substring(0,n));o.push(h);}o.push(new ce.StringValue(`
25
- `)),l=r+1;}if(a!=-1&&(u=s),u>l){let h=t.substring(l,u);o.push(new ce.StringValue(h));}if(a!=-1&&s>r&&(o.push(new ce.StringValue(`
26
- `)),a<t.length-1)){let h=t.length-a-1,c=new ce.StringValue(t.substring(a+1,a+1+h));o.push(c);}return o}PushToOutputStreamIndividual(e){let t=(0, le.asOrNull)(e,Il.Glue),n=(0, le.asOrNull)(e,ce.StringValue),r=true;if(t)this.TrimNewlinesFromOutputStream(),r=true;else if(n){let a=-1,s=this.callStack.currentElement;s.type==kt.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u],c=h instanceof Te.ControlCommand?h:null;if((h instanceof Il.Glue?h:null)!=null){o=u;break}else if(c!=null&&c.commandType==Te.ControlCommand.CommandType.BeginString){u>=a&&(a=-1);break}}let l=-1;if(o!=-1&&a!=-1?l=Math.min(a,o):o!=-1?l=o:l=a,l!=-1){if(n.isNewline)r=false;else if(n.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let u=this.callStack.elements;for(let h=u.length-1;h>=0;h--){let c=u[h];if(c.type==kt.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(r=false);}if(r){if(e===null)return (0, Qe.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let n=this.outputStream[t],r=(0, le.asOrNull)(n,Te.ControlCommand),a=(0, le.asOrNull)(n,ce.StringValue);if(r!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t<this.outputStream.length;)(0, le.asOrNull)(this.outputStream[t],ce.StringValue)?this.outputStream.splice(t,1):t++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let e=this.outputStream.length-1;e>=0;e--){let t=this.outputStream[e];if(t instanceof Il.Glue)this.outputStream.splice(e,1);else if(t instanceof Te.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof Te.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof ce.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof ce.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, le.asOrNull)(this.outputStream[e],Te.ControlCommand);if(t instanceof Te.ControlCommand&&t.commandType==Te.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, le.asOrNull)(e,ce.ListValue);if(t){let n=t.value;if(n===null)return (0, Qe.throwNullException)("rawList");if(n.originNames!=null){n.origins||(n.origins=[]),n.origins.length=0;for(let r of n.originNames){if(this.story.listDefinitions===null)return (0, Qe.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(r,null);if(a.result===null)return (0, Qe.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, Qe.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, le.nullIfUndefined)(t)}else {if(e>this.evaluationStack.length)throw new Error("trying to pop too many objects");let t=this.evaluationStack.splice(this.evaluationStack.length-e,e);return (0, le.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=_n.Pointer.Null,this.previousPointer=_n.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){uC.Debug.Assert(this.callStack.currentElement.type==kt.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let n=this.outputStream[t],r=(0, le.asOrNull)(n,ce.StringValue),a=(0, le.asOrNull)(n,Te.ControlCommand);if(r!=null){if(a)break;if(r.isNewline||r.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==kt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(e);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(kt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=_n.Pointer.StartOf(e),this.PassArgumentsToEvaluationStack(t);}PassArgumentsToEvaluationStack(e){if(e!==null)for(let t=0;t<e.length;t++){if(!(typeof e[t]=="number"||typeof e[t]=="string"||typeof e[t]=="boolean"||e[t]instanceof dC.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, le.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(ce.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==kt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=_n.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=kt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let e=this.callStack.currentElement.evaluationStackHeightWhenPushed,t=null;for(;this.evaluationStack.length>e;){let n=this.PopEvaluationStack();t===null&&(t=n);}if(this.PopCallStack(kt.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof lC.Void)return null;let n=(0, le.asOrThrows)(t,ce.Value);return n.valueType==ce.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(e,t){t?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(e)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(e));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};Gs.StoryState=Rl;});var Ec=w($s=>{Object.defineProperty($s,"__esModule",{value:true});$s.Stopwatch=void 0;var Ll=class{constructor(){this.startTime=void 0;}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime();}Stop(){this.startTime=void 0;}};$s.Stopwatch=Ll;});var Dc=w(Js=>{Object.defineProperty(Js,"__esModule",{value:true});Js.ErrorType=void 0;var bc;(function(i){i[i.Author=0]="Author",i[i.Warning=1]="Warning",i[i.Error=2]="Error";})(bc||(Js.ErrorType=bc={}));});var ci=w(tn=>{Object.defineProperty(tn,"__esModule",{value:true});tn.Story=tn.InkList=void 0;var Se=ae(),Bl=Re(),Wl=xn(),pC=Sc(),k=ye(),Ze=Ut(),fC=dr(),gC=El(),Ac=ct(),F=ne(),jl=ke(),mi=zt(),Hs=Ps(),mC=Ft(),CC=Dn(),yC=ht(),Zt=Mn(),ql=Tl(),en=Jt(),vC=Dl(),SC=Ec(),Lt=Zn(),Ci=Be(),R=z(),H=Ce(),wc=Nl(),xc=Dc(),EC=Be();Object.defineProperty(tn,"InkList",{enumerable:true,get:function(){return EC.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var On=class i extends Bl.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, H.throwNullException)("this._state");for(let t of this._state.currentChoices)t.isInvisibleDefault||(t.index=e.length,e.push(t));return e}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=false,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=false,this._temporaryEvaluationContainer=null,this._asyncContinueActive=false,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount=0,this._asyncSaving=false,this._profiler=null;let e,t=null,n=null;if(arguments[0]instanceof Se.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let r=arguments[0];n=wc.SimpleJson.TextToDictionary(r);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new vC.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let r=n,a=r.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let s=parseInt(a);if(s>i.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(s<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");s!=i.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${i.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=r.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let l;(l=r.listDefs)&&(this._listDefinitions=Wl.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, R.asOrThrows)(Wl.JsonSerialisation.JTokenToRuntimeObject(o),Se.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new wc.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",i.inkVersionCurrent),e.WriteProperty("root",n=>Wl.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[r,a]of n.items){let s=Ci.InkListItem.fromSerializedKey(r),o=a;e.WriteIntProperty(s.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new pC.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, H.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, H.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new jl.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=e;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(e){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+e);this.state.SwitchFlow_Internal(e);}RemoveFlow(e){this.state.RemoveFlow_Internal(e);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(e){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(e);}ContinueInternal(e=0){this._profiler!=null&&this._profiler.PreContinue();let t=e>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!t&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=t,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=false,this._state.ResetOutput(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation();}let n=new SC.Stopwatch;n.Start();let r=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{r=this.ContinueSingleStep();}catch(s){if(!(s instanceof Zt.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(r||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((r||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(Ze.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(Ze.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(a=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let s of this.state.currentErrors)this.onError(s,xc.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,xc.ErrorType.Warning);this.ResetErrors();}else {let s=new en.StringBuilder;throw s.Append("Ink had "),this.state.hasError&&(s.Append(`${this.state.currentErrors.length}`),s.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&s.Append(" and ")),this.state.hasWarning&&(s.Append(`${this.state.currentWarnings.length}`),s.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&s.Append(" and ")),s.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),s.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new Zt.StoryException(s.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, H.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, H.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==i.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==i.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(e,t,n,r){if(e===null)return (0, H.throwNullException)("prevText");if(t===null)return (0, H.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
27
- `;if(n==r&&e.length==t.length&&a)return i.OutputStateChange.NoChange;if(!a)return i.OutputStateChange.NewlineRemoved;if(r>n)return i.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return i.OutputStateChange.ExtendedBeyondNewline}return i.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new en.StringBuilder;for(;this.canContinue;)e.Append(this.Continue());return e.toString()}ContentAtPath(e){return this.mainContentContainer.ContentAtPath(e)}KnotContainerWithName(e){let t=this.mainContentContainer.namedContent.get(e);return t instanceof Se.Container?t:null}PointerAtPath(e){if(e.length==0)return Lt.Pointer.Null;let t=new Lt.Pointer,n=e.length,r=null;return e.lastComponent===null?(0, H.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(n=e.length-1,r=this.mainContentContainer.ContentAtPath(e,void 0,n),t.container=r.container,t.index=e.lastComponent.index):(r=this.mainContentContainer.ContentAtPath(e),t.container=r.container,t.index=-1),r.obj==null||r.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):r.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+r.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, H.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let e=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,e}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let e=true,t=this.state.currentPointer.copy();if(t.isNull)return;let n=(0, R.asOrNull)(t.Resolve(),Se.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)t=Lt.Pointer.StartOf(n),n=(0, R.asOrNull)(t.Resolve(),Se.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let r=t.Resolve(),a=this.PerformLogicAndFlowControl(r);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, R.asOrNull)(r,fC.ChoicePoint);if(s){let l=this.ProcessChoice(s);l&&this.state.generatedChoices.push(l),r=null,e=false;}if(r instanceof Se.Container&&(e=false),e){let l=(0, R.asOrNull)(r,F.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);r=new F.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(r):this.state.PushToOutputStream(r);}this.NextContent();let o=(0, R.asOrNull)(r,k.ControlCommand);o&&o.commandType==k.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let s=e.Resolve(),o=(0, R.asOrNull)(s,Se.Container)||(0, R.asOrNull)(e.container,Se.Container);for(;o;)this._prevContainers.push(o),o=(0, R.asOrNull)(o.parent,Se.Container);}let n=t.Resolve();if(n==null)return;let r=(0, R.asOrNull)(n.parent,Se.Container),a=true;for(;r&&(this._prevContainers.indexOf(r)<0||r.countingAtStartOnly);){let s=r.content.length>0&&n==r.content[0]&&a;s||(a=false),this.VisitContainer(r,s),n=r,r=(0, R.asOrNull)(r.parent,Se.Container);}}PopChoiceStringAndTags(e){let t=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);for(;this.state.evaluationStack.length>0&&(0, R.asOrNull)(this.state.PeekEvaluationStack(),Hs.Tag)!=null;){let n=(0, R.asOrNull)(this.state.PopEvaluationStack(),Hs.Tag);n&&e.push(n.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let n="",r="",a=[];if(e.hasChoiceOnlyContent&&(r=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new gC.Choice;return s.targetPath=e.pathOnChoice,s.sourcePath=e.path.toString(),s.isInvisibleDefault=e.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(n+r).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof F.Value){let n=e;if(n instanceof F.DivertTargetValue){let r=n;return this.Error("Shouldn't use a divert target (to "+r.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof Ac.Divert){let t=e;if(t.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(t.hasVariableTarget){let n=t.variableDivertName,r=this.state.variablesState.GetVariableWithName(n);if(r==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(r instanceof F.DivertTargetValue)){let s=(0, R.asOrNull)(r,F.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";s instanceof F.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+r+"'.",this.Error(o);}let a=(0, R.asOrThrows)(r,F.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),true;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),true}else if(e instanceof k.ControlCommand){let t=e;switch(t.commandType){case k.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case k.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case k.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let g=this.state.PopEvaluationStack();if(!(g instanceof mi.Void)){let E=new F.StringValue(g.toString());this.state.PushToOutputStream(E);}}break;case k.ControlCommand.CommandType.NoOp:break;case k.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case k.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case k.ControlCommand.CommandType.PopFunction:case k.ControlCommand.CommandType.PopTunnel:let n=t.commandType==k.ControlCommand.CommandType.PopFunction?Ze.PushPopType.Function:Ze.PushPopType.Tunnel,r=null;if(n==Ze.PushPopType.Tunnel){let g=this.state.PopEvaluationStack();r=(0, R.asOrNull)(g,F.DivertTargetValue),r===null&&this.Assert(g instanceof mi.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let g=new Map;g.set(Ze.PushPopType.Function,"function return statement (~ return)"),g.set(Ze.PushPopType.Tunnel,"tunnel onwards statement (->->)");let E=g.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(E="end of flow (-> END or choice)");let _="Found "+g.get(n)+", when expected "+E;this.Error(_);}else this.state.PopCallStack(),r&&(this.state.divertedPointer=this.PointerAtPath(r.targetPath));break;case k.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(t),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case k.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case k.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let g=[],E=0;for(let N=this.state.outputStream.length-1;N>=0;--N){let te=this.state.outputStream[N];E++;let be=(0, R.asOrNull)(te,k.ControlCommand);if(be!=null){if(be.commandType==k.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}te instanceof F.StringValue&&g.push(te);}this.state.PopFromOutputStream(E);let _=new en.StringBuilder;for(let N of g.reverse())_.Append(N.toString());let T=new Hs.Tag(this.state.CleanOutputWhitespace(_.toString()));this.state.PushEvaluationStack(T);}else this.state.PushToOutputStream(t);break}case k.ControlCommand.CommandType.EndString:{let g=[],E=[],_=0;for(let N=this.state.outputStream.length-1;N>=0;--N){let te=this.state.outputStream[N];_++;let be=(0, R.asOrNull)(te,k.ControlCommand);if(be&&be.commandType==k.ControlCommand.CommandType.BeginString)break;te instanceof Hs.Tag&&E.push(te),te instanceof F.StringValue&&g.push(te);}this.state.PopFromOutputStream(_);for(let N of E)this.state.PushToOutputStream(N);g=g.reverse();let T=new en.StringBuilder;for(let N of g)T.Append(N.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new F.StringValue(T.toString()));break}case k.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new F.IntValue(a));break;case k.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new F.IntValue(this.state.currentTurnIndex+1));break;case k.ControlCommand.CommandType.TurnsSince:case k.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof F.DivertTargetValue)){let g="";s instanceof F.IntValue&&(g=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+g);break}let o=(0, R.asOrThrows)(s,F.DivertTargetValue),l=(0, R.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,Se.Container),u;l!=null?t.commandType==k.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(t.commandType==k.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new F.IntValue(u));break;case k.ControlCommand.CommandType.Random:{let g=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),E=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(E==null||!(E instanceof F.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(g==null||!(g instanceof F.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(g.value===null)return (0, H.throwNullException)("maxInt.value");if(E.value===null)return (0, H.throwNullException)("minInt.value");let _=g.value-E.value+1;(!isFinite(_)||_>Number.MAX_SAFE_INTEGER)&&(_=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),_<=0&&this.Error("RANDOM was called with minimum as "+E.value+" and maximum as "+g.value+". The maximum must be larger");let T=this.state.storySeed+this.state.previousRandom,te=new ql.PRNG(T).next(),be=te%_+E.value;this.state.PushEvaluationStack(new F.IntValue(be)),this.state.previousRandom=te;break}case k.ControlCommand.CommandType.SeedRandom:let h=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(h==null||!(h instanceof F.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, H.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new mi.Void);break;case k.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new F.IntValue(c));break;case k.ControlCommand.CommandType.SequenceShuffleIndex:let p=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new F.IntValue(p));break;case k.ControlCommand.CommandType.StartThread:break;case k.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Lt.Pointer.Null);break;case k.ControlCommand.CommandType.End:this.state.ForceEnd();break;case k.ControlCommand.CommandType.ListFromInt:let f=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),y=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);if(f===null)throw new Zt.StoryException("Passed non-integer when creating a list element from a numerical value.");let C=null;if(this.listDefinitions===null)return (0, H.throwNullException)("this.listDefinitions");let A=this.listDefinitions.TryListGetDefinition(y.value,null);if(A.exists){if(f.value===null)return (0, H.throwNullException)("minInt.value");let g=A.result.TryGetItemWithValue(f.value,Ci.InkListItem.Null);g.exists&&(C=new F.ListValue(g.result,f.value));}else throw new Zt.StoryException("Failed to find LIST called "+y.value);C==null&&(C=new F.ListValue),this.state.PushEvaluationStack(C);break;case k.ControlCommand.CommandType.ListRange:let b=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.Value),m=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.Value),d=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.ListValue);if(d===null||m===null||b===null)throw new Zt.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(d.value===null)return (0, H.throwNullException)("targetList.value");let S=d.value.ListWithSubRange(m.valueObject,b.valueObject);this.state.PushEvaluationStack(new F.ListValue(S));break;case k.ControlCommand.CommandType.ListRandom:{let g=this.state.PopEvaluationStack();if(g===null)throw new Zt.StoryException("Expected list for LIST_RANDOM");let E=g.value,_=null;if(E===null)throw (0, H.throwNullException)("list");if(E.Count==0)_=new Ci.InkList;else {let T=this.state.storySeed+this.state.previousRandom,te=new ql.PRNG(T).next(),be=te%E.Count,rn=E.entries();for(let ru=0;ru<=be-1;ru++)rn.next();let iu=rn.next().value,Ai={Key:Ci.InkListItem.fromSerializedKey(iu[0]),Value:iu[1]};if(Ai.Key.originName===null)return (0, H.throwNullException)("randomItem.Key.originName");_=new Ci.InkList(Ai.Key.originName,this),_.Add(Ai.Key,Ai.Value),this.state.previousRandom=te;}this.state.PushEvaluationStack(new F.ListValue(_));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof mC.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),true}else if(e instanceof CC.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let r=t.containerForCount,a=this.state.VisitCountForContainer(r);n=new F.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(t.name),n==null&&(this.Warning("Variable not found: '"+t.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),n=new F.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(e instanceof yC.NativeFunctionCall){let t=e,n=this.state.PopEvaluationStack(t.numberOfParameters),r=t.Call(n);return this.state.PushEvaluationStack(r),true}return false}ChoosePathString(e,t=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,n),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==Ze.PushPopType.Function){let r="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(r="("+a.path.toString()+") "),new Error("Story was running a function "+r+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace:
28
- `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new jl.Path(e));}IfAsyncWeCant(e){if(this._asyncContinueActive)throw new Error("Can't "+e+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(e,t=true){this.state.SetChosenPath(e,t),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(e){e=e;let t=this.currentChoices;this.Assert(e>=0&&e<t.length,"choice out of range");let n=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, H.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, H.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(e,t),this.IfAsyncWeCant("evaluate a function"),e==null)throw new Error("Function is null");if(e==""||e.trim()=="")throw new Error("Function is empty or white space.");let r=this.KnotContainerWithName(e);if(r==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(r,t);let s=new en.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let l=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,l),n?{returned:l,output:o}:l}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(Ze.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, H.throwNullException)("funcName");let n=this._externals.get(e),r=null,a=typeof n<"u";if(a&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+e+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+e+"()"),a&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){r=this.KnotContainerWithName(e),this.Assert(r!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(Ze.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Lt.Pointer.StartOf(r);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let u=0;u<t;++u){let c=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.Value).valueObject;s.push(c);}s.reverse();let o=n.function(s),l=null;o!=null?(l=F.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new mi.Void,this.state.PushEvaluationStack(l);}BindExternalFunctionGeneral(e,t,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(e),"Function '"+e+"' has already been bound."),this._externals.set(e,{function:t,lookAheadSafe:n});}TryCoerce(e){return e}BindExternalFunction(e,t,n=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,r=>{this.Assert(r.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=r.length;s<o;s++)a[s]=this.TryCoerce(r[s]);return t.apply(null,a)},n);}UnbindExternalFunction(e){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(e),"Function '"+e+"' has not been bound."),this._externals.delete(e);}ValidateExternalBindings(){let e=null,t=null,n=arguments[1]||new Set;if(arguments[0]instanceof Se.Container&&(e=arguments[0]),arguments[0]instanceof Bl.InkObject&&(t=arguments[0]),e===null&&t===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let r="Error: Missing function binding for external";r+=n.size>1?"s":"",r+=": '",r+=Array.from(n).join("', '"),r+="' ",r+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(r);}else if(e!=null){for(let r of e.content){let a=r;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(r,n);}for(let[,r]of e.namedContent)this.ValidateExternalBindings((0, R.asOrNull)(r,Bl.InkObject),n);}else if(t!=null){let r=(0, R.asOrNull)(t,Ac.Divert);if(r&&r.isExternal){let a=r.targetPathString;if(a===null)return (0, H.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.add(a);}}}ObserveVariable(e,t){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(e))throw new Error("Cannot observe variable '"+e+"' because it wasn't declared in the ink story.");this._variableObservers.has(e)?this._variableObservers.get(e).push(t):this._variableObservers.set(e,[t]);}ObserveVariables(e,t){for(let n=0,r=e.length;n<r;n++)this.ObserveVariable(e[n],t[n]);}RemoveVariableObserver(e,t){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(t!=null){if(this._variableObservers.has(t))if(e!=null){let n=this._variableObservers.get(t);n!=null&&(n.splice(n.indexOf(e),1),n.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let n=this._variableObservers.keys();for(let r of n){let a=this._variableObservers.get(r);a!=null&&(a.splice(a.indexOf(e),1),a.length===0&&this._variableObservers.delete(r));}}}}VariableStateDidChangeEvent(e,t){if(this._variableObservers===null)return;let n=this._variableObservers.get(e);if(typeof n<"u"){if(!(t instanceof F.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let r=(0, R.asOrThrows)(t,F.Value);for(let a of n)a(e,r.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new jl.Path(e),n=this.ContentAtPath(t).container;if(n===null)return (0, H.throwNullException)("flowContainer");for(;;){let s=n.content[0];if(s instanceof Se.Container)n=s;else break}let r=false,a=null;for(let s of n.content){let o=(0, R.asOrNull)(s,k.ControlCommand);if(o!=null)o.commandType==k.ControlCommand.CommandType.BeginTag?r=true:o.commandType==k.ControlCommand.CommandType.EndTag&&(r=false);else if(r){let l=(0, R.asOrNull)(s,F.StringValue);l!==null?(a===null&&(a=[]),l.value!==null&&a.push(l.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let e=new en.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new en.StringBuilder;return e.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=Lt.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(Ze.PushPopType.Function)?(this.state.PopCallStack(Ze.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new mi.Void),t=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),t=true):this.state.TryExitFunctionEvaluationFromGame(),t&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let e=true,t=this.state.callStack.currentElement.currentPointer.copy();if(t.index++,t.container===null)return (0, H.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let n=(0, R.asOrNull)(t.container.parent,Se.Container);if(!(n instanceof Se.Container))break;let r=n.content.indexOf(t.container);if(r==-1)break;if(t=new Lt.Pointer(n,r),t.index++,e=true,t.container===null)return (0, H.throwNullException)("pointer.container")}return e||(t=Lt.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(r=>r.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let n=t[0];return n.targetPath===null?(0, H.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, H.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,false),true)}NextSequenceShuffleIndex(){let e=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(!(e instanceof F.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, H.throwNullException)("seqContainer");if(e.value===null)return (0, H.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.IntValue).value;if(a===null)return (0, H.throwNullException)("seqCount");let s=a/n,o=a%n,l=t.path.toString(),u=0;for(let f=0,y=l.length;f<y;f++)u+=l.charCodeAt(f)||0;let h=u+s+this.state.storySeed,c=new ql.PRNG(Math.floor(h)),p=[];for(let f=0;f<n;++f)p.push(f);for(let f=0;f<=o;++f){let y=c.next()%p.length,C=p[y];if(p.splice(y,1),f==o)return C}throw new Error("Should never reach here")}Error(e,t=false){let n=new Zt.StoryException(e);throw n.useEndLineNumber=t,n}Warning(e){this.AddError(e,true);}AddError(e,t=false,n=false){let r=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(r!=null){let s=n?r.endLineNumber:r.startLineNumber;e="RUNTIME "+a+": '"+r.fileName+"' line "+s+": "+e;}else this.state.currentPointer.isNull?e="RUNTIME "+a+": "+e:e="RUNTIME "+a+": ("+this.state.currentPointer+"): "+e;this.state.AddError(e,t),t||this.state.ForceEnd();}Assert(e,t=null){if(e==false)throw t==null&&(t="Story assert"),new Error(t+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let e,t=this.state.currentPointer;if(!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(t=this.state.callStack.elements[n].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.outputStream.length-1;n>=0;--n)if(e=this.state.outputStream[n].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};tn.Story=On;On.inkVersionCurrent=21;(function(i){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(i.OutputStateChange||(i.OutputStateChange={}));})(On||(tn.Story=On={}));});var Oc=w(Ys=>{Object.defineProperty(Ys,"__esModule",{value:true});Ys.Story=void 0;var bC=$i(),DC=Pr(),zs=ae(),Us=ye(),yi=ln(),Ks=dt(),_c=vn(),AC=ul(),wC=ss(),xC=gl(),_C=ci(),Pn=bt(),OC=Vt(),PC=Ft(),vi=z(),TC=ni(),FC=ii(),NC=Xt(),Xs=class i extends Ks.FlowBase{get flowLevel(){return _c.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(e,t=false){super(null,e,null,false,t),this._errorHandler=null,this._hadError=false,this._hadWarning=false,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=false,this.ExportRuntime=(n=null)=>{var r,a;this._errorHandler=n,this.constants=new Map;for(let h of this.FindAll(DC.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let p=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(p,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(wC.ListDefinition)())!((r=h.identifier)===null||r===void 0)&&r.name&&this._listDefs.set((a=h.identifier)===null||a===void 0?void 0:a.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let s=this.runtimeObject,o=new zs.Container;o.AddContent(Us.ControlCommand.EvalStart());let l=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),o.AddContent(c.listDefinition.runtimeObject),l.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(o);}let p=new PC.VariableAssignment(h,true);p.isGlobal=true,o.AddContent(p);}o.AddContent(Us.ControlCommand.EvalEnd()),o.AddContent(Us.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(Us.ControlCommand.Done());let u=new _C.Story(s,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let r=this._listDefs.get(n);return r||null},this.ResolveListItem=(n,r,a=null)=>{let s=null;if(n)return (s=this._listDefs.get(n))?s.ItemNamed(r):null;{let o=null,l=null;for(let[,u]of this._listDefs.entries()){let h=u.ItemNamed(r);h&&(o?this.Error(`Ambiguous item name '${r}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,false):(o=h,l=u));}return o}},this.FlattenContainersIn=n=>{let r=new Set;if(n.content)for(let a of n.content){let s=(0, vi.asOrNull)(a,zs.Container);s&&r.add(s);}if(n.namedContent)for(let[,a]of n.namedContent){let s=(0, vi.asOrNull)(a,zs.Container);s&&r.add(s);}for(let a of r)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let r=(0, vi.asOrNull)(n.parent,zs.Container);if(r){let a=r.content.indexOf(n);r.content.splice(a,1);let s=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),r.InsertContent(o,a),a+=1;}},this.Error=(n,r,a)=>{let s=a?yi.ErrorType.Warning:yi.ErrorType.Error,o="";if(r instanceof bC.AuthorWarning?(o+="TODO: ",s=yi.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",r&&r.debugMetadata!==null&&r.debugMetadata.startLineNumber>=1&&(r.debugMetadata.fileName!=null&&(o+=`'${r.debugMetadata.fileName}' `),o+=`line ${r.debugMetadata.startLineNumber}: `),o+=n,n=o,this._errorHandler!==null)this._errorHandler(n,s);else throw new Error(n);this._hadError=s===yi.ErrorType.Error,this._hadWarning=s===yi.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=n=>this.externals.has(n),this.AddExternal=n=>{this.externals.has(n.name)?this.Error(`Duplicate EXTERNAL definition of '${n.name}'`,n,false):n.name&&this.externals.set(n.name,n);},this.DontFlattenContainer=n=>{this._dontFlattenContainers.add(n);},this.NameConflictError=(n,r,a,s)=>{n.Error(`${s} '${r}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,r,a,s="")=>{var o;let l=s||n.typeName;if(i.IsReservedKeyword(r?.name)){n.Error(`'${r}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(FC.FunctionCall.IsBuiltIn(r?.name||"")){n.Error(`'${r}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(r?.name||"",_c.FlowLevel.Knot),h=(0, vi.asOrNull)(u,Ks.FlowBase);if(h&&(h!==n||a===Pn.SymbolType.Arg)){this.NameConflictError(n,r?.name||"",h,l);return}if(a<Pn.SymbolType.List)return;for(let[y,C]of this._listDefs)if(r?.name===y&&n!==C&&C.variableAssignment!==n&&this.NameConflictError(n,r?.name,C,l),!(n instanceof xC.ListElementDefinition))for(let A of C.itemDefinitions)r?.name===A.name&&this.NameConflictError(n,r?.name||"",A,l);if(a<=Pn.SymbolType.Var)return;let c=r?.name&&this.variableDeclarations.get(r?.name)||null;if(c&&c!==n&&c.isGlobalDeclaration&&c.listDefinition==null&&this.NameConflictError(n,r?.name||"",c,l),a<Pn.SymbolType.SubFlowAndWeave)return;let f=new NC.Path(r).ResolveFromContext(n);if(f&&f!==n){this.NameConflictError(n,r?.name||"",f,l);return}if(!(a<Pn.SymbolType.Arg)&&a!==Pn.SymbolType.Arg){let y=(0, vi.asOrNull)(n,Ks.FlowBase);if(y||(y=(0, TC.ClosestFlowBase)(n)),y&&y.hasParameters&&y.args){for(let C of y.args)if(((o=C.identifier)===null||o===void 0?void 0:o.name)===r?.name){n.Error(`${l} '${r}': name has already been used for a argument to ${y.identifier} on ${y.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let n of e)if(n instanceof AC.IncludedFile){let r=n,a=e.indexOf(n);if(e.splice(a,1),r.includedStory){let s=[],o=r.includedStory;if(o.content!=null){for(let l of o.content)l instanceof Ks.FlowBase?t.push(l):s.push(l);s.push(new OC.Text(`
29
- `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};Ys.Story=Xs;Xs.IsReservedKeyword=i=>{switch(i){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var Tc=w(Qs=>{Object.defineProperty(Qs,"__esModule",{value:true});Qs.StringExpression=void 0;var Pc=ye(),VC=Ue(),IC=Vt(),kC=z(),Ml=class i extends VC.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof IC.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(Pc.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(Pc.ControlCommand.EndString());},this.toString=()=>{let t="";for(let n of this.content)t+=n;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, kC.asOrNull)(e,i);if(t===null||!this.isSingleString||!t.isSingleString)return false;let n=this.toString(),r=t.toString();return n===r}};Qs.StringExpression=Ml;});var Nc=w(Tn=>{Object.defineProperty(Tn,"__esModule",{value:true});Tn.LegacyTag=Tn.Tag=void 0;var RC=ee(),Fc=ye(),Gl=class extends RC.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?Fc.ControlCommand.BeginTag():Fc.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};Tn.Tag=Gl;var LC=rl(),$l=class extends LC.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};Tn.LegacyTag=$l;});var Vc=w(Zs=>{Object.defineProperty(Zs,"__esModule",{value:true});Zs.DefaultFileHandler=void 0;var Jl=class{constructor(e){this.rootPath=e,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};Zs.DefaultFileHandler=Jl;});var Kl=w(ia=>{Object.defineProperty(ia,"__esModule",{value:true});ia.InkParser=void 0;var BC=nh(),WC=$i(),jC=Qa(),it=gh(),pe=Yn(),qC=yn(),MC=Ah(),GC=xr(),Si=Vo(),qe=jr(),$C=Pr(),ea=Hh(),JC=zh(),nn=bn(),Hl=En(),HC=Ue(),zC=Uh(),Ic=Kh(),ta=ii(),UC=ti(),KC=Xh(),XC=vs(),na=Qh(),kc=ul(),YC=Zh(),QC=dl(),Rc=tc(),ZC=ss(),ey=gl(),ty=Po(),Lc=ee(),ny=Xt(),Bc=So(),Wc=Mo(),de=Wo(),Fe=ml(),iy=yl(),jc=Oc(),Ei=Tc(),Dt=uo(),Fn=Nc(),At=Vt(),qc=$o(),zl=Xo(),Ul=An(),ry=Xa(),Bt=z(),bi=Lr(),Nn=ar(),Mc=ln(),sy=Vc(),K=class i extends Dt.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,n=null,r=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel(Fe.StatementLevel.Top);return new jc.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let l=this.Parse(s);if(l===null)return null;let u=[];u.push(l);do{let h=this.BeginRule();if(o()===null){this.FailRule(h);break}let p=this.Parse(s);if(p===null){this.FailRule(h);break}this.SucceedRule(h),u.push(p);}while(true);return u},this.CreateDebugMetadata=(s,o)=>{let l=new JC.DebugMetadata;return l.startLineNumber=(s?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(s?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(s,o,l)=>{let u=(0, Bt.asOrNull)(s,Lc.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let h=Array.isArray(s)?s:null;if(h!==null)for(let p of h)(0, Bt.asOrNull)(p,Lc.ParsedObject)&&(p.hasOwnDebugMetadata||(p.debugMetadata=this.CreateDebugMetadata(o,l)));let c=(0, Bt.asOrNull)(s,bi.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(s,o,l=0,u=false)=>{let c=u?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${l+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,u?Mc.ErrorType.Warning:Mc.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
30
- \r`);return o?new WC.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=i.ListAllCharacterRanges();for(let l of o)s.AddCharacters(l.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let s=true,o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!o){if(o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),o===null)return null;s=false;}let l=this.Parse(this.BracketedName);this.Whitespace(),l!=null&&this.Newline();let u=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let h=null,c=this.Parse(this.MixedTextAndLogic);c&&(h=new qe.ContentList(c));let p=null,f=null,y=this.ParseString("[")!==null;if(y){this.EndTagIfNecessary(h);let m=this.Parse(this.MixedTextAndLogic);m!==null&&(p=new qe.ContentList(m)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(p);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(f=new qe.ContentList(d));}this.Whitespace(),this.EndTagIfNecessary(f??h);let C=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let A=!h&&!f&&!p;if(A&&C===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&y&&!p&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),f||(f=new qe.ContentList),this.EndTagIfNecessary(f),C!==null)for(let m of C){let d=(0, Bt.asOrNull)(m,nn.Divert);d&&d.isEmpty||f.AddContent(m);}f.AddContent(new At.Text(`
31
- `));let b=new qC.Choice(h,p,f);return l&&(b.identifier=l),b.indentationDepth=o.length,b.hasWeaveStyleInlineBrackets=y,b.condition=u,b.onceOnly=s,b.isInvisibleDefault=A,b},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new ty.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Dt.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let s=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(s),this.Expect(this.String("}"),"closing '}' for choice condition"),s},this.Gather=()=>{let s=this.Parse(this.GatherDashes);if(s===null)return null;let o=Number(s),l=this.Parse(this.BracketedName),u=new UC.Gather(l,o);return this.Newline(),u},this.GatherDashes=()=>{this.Whitespace();let s=0;for(;this.ParseDashNotArrow()!==null;)s+=1,this.Whitespace();return s===0?null:s},this.ParseDashNotArrow=()=>{let s=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(s):this.FailRule(s)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),s)},this.InnerConditionalContent=s=>{if(s===void 0){let c=this.Parse(this.ConditionExpression),p=this.Parse(()=>this.InnerConditionalContent(c));return p===null?null:p}let o,l=s!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let c=this.StatementsAtLevel(Fe.StatementLevel.InnerBlock);if(c!==null){o=[new Si.ConditionalSingleBranch(c)];let f=this.Parse(this.SingleMultilineCondition);f&&(f.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",f),f.isElse=true),o.push(f));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let c=new Si.ConditionalSingleBranch(null);c.isTrueBranch=true,o.unshift(c);}if(s){let c=false;for(let p=0;p<o.length;++p){let f=o[p],y=p===o.length-1;f.ownExpression?(f.matchingEquality=true,c=true):c&&y?(f.matchingEquality=true,f.isElse=true):!y&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",f):p===0?f.isTrueBranch=true:f.isElse=true;}}else {for(let c=0;c<o.length;++c){let p=o[c],f=c===o.length-1;if(p.ownExpression===null)if(f)p.isElse=true;else if(p.isElse){let y=o[o.length-1];y.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",y):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",p);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",p);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let c of o)c.isInline=u;return new GC.Conditional(s,o)},this.InlineConditionalBranches=()=>{let s=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(s===null||s.length===0)return null;let o=[];if(s.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let l=new Si.ConditionalSingleBranch(s[0]);if(l.isTrueBranch=true,o.push(l),s.length>1){let u=new Si.ConditionalSingleBranch(s[1]);u.isElse=true,o.push(u);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineCondition);return s===null?null:(this.MultilineWhitespace(),s)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=null,o=this.Parse(this.ElseExpression)!==null;o||(s=this.Parse(this.ConditionExpression));let l=this.StatementsAtLevel(Fe.StatementLevel.InnerBlock);s===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new At.Text("")]),this.MultilineWhitespace();let u=new Si.ConditionalSingleBranch(l);return u.ownExpression=s,u.isElse=o,u},this.ConditionExpression=()=>{let s=this.Parse(this.Expression);return s===null||(this.DisallowIncrement(s),this.Whitespace(),this.ParseString(":")===null)?null:s},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:Dt.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let l=s.length-1,u=s[l];if(u instanceof At.Text){let h=u;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),o?h.text+=" ":h.text.length===0&&(s.splice(l,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof nn.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof Fn.Tag&&s[0].isStart||s.push(new At.Text(`
32
- `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),s)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let o=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let l=this.Parse(this.MultiDivert);l!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...l));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),l){let u=this.ParseSingleCharacter();s+=u;}}else break}while(true);return s!==null?new At.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new pe.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new pe.CharacterSet(`{}|
33
- \r\\#`),this._notTextEndCharactersChoice=new pe.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new pe.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let s=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let l=this.ParseUntil(s,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;s=[],this.EndTagIfNecessary(s);for(let u=0;u<l.length;++u)if(u%2===0){if(l[u]==="->->"){u===0||u===l.length-1||u===l.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let p=new qc.TunnelOnwards;if(u<l.length-1){let f=(0, Bt.asOrNull)(l[u+1],nn.Divert);p.divertAfter=f;}s.push(p);break}}else {let c=l[u];u<l.length-1&&(c.isTunnel=true),s.push(c);}if(s.length===0&&l.length===1){let u=new nn.Divert(null);u.isEmpty=true,s.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new nn.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new ny.Path(s);return new nn.Divert(l,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof qc.TunnelOnwards)return null;let l=s[0];return l.isTunnel?null:l},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let s=0;for(;this.ParseString("->")!==null;)s+=1;return s===0?null:s===1?"->":(s===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let s=this.ParseTempKeyword();this.Whitespace();let o=null;if(s?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let l=this.ParseString("+")!==null,u=this.ParseString("-")!==null;if(l&&u&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return s&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return l||u?new na.IncDecExpression(o,h,l):new zl.VariableAssignment({variableIdentifier:o,assignedExpression:h,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof na.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let s=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(s),true):(this.FailRule(s),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new Bc.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>s){let h=`right side of '${u.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(o,u),h);if(c===null)return this.FailRule(l),null;o=this.SucceedRule(l,c);continue}this.FailRule(l);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let s=this.Parse(this.ExpressionDivertTarget);if(s!==null)return s;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&o!==null&&(l=this.ExpressionUnary()),l===null)return null;o!==null&&(l=ry.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof Ul.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new na.IncDecExpression(c.identifier,h);}}return l},this.ExpressionNot=()=>{let s=this.Identifier();return s==="not"?s:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let s=this.Parse(this.SingleDivert);return !s||s&&s.isThread?null:(this.Whitespace(),new Hl.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new Nn.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new Nn.NumberExpression(s,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let o=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,o===null?o=[new At.Text("")]:o.find(l=>l instanceof nn.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Ei.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new Nn.NumberExpression(true,"bool"):s==="false"?new Nn.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new ta.FunctionCall(s,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,s);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let s=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return s===null||jc.Story.IsReservedKeyword(s[0].name)?null:new Ul.VariableReference(s)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let s=this.Parse(this.Expression);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),s)},this.ExpressionInfixRight=(s,o)=>{if(!s)return null;this.Whitespace();let l=this.Parse(()=>this.Expression(o.precedence));return l?new jC.BinaryExpression(s,l,o.type):null},this.ParseInfixOperator=()=>{for(let s of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(s.type)!==null){if(s.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,s)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let s=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new Rc.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${l?.name}`;}return this.Whitespace(),s},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(s,o,l=false)=>{let u=new YC.InfixOperator(s,o,l);this._binaryOperators.push(u),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,s.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let s=this.Expect(()=>this.ParseUntilCharactersFromString(`
24
+ `)a==-1&&(a=h),s=h;else {if(c==" "||c==" ")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=t.length;if(n!=-1){if(n>0){let h=new ue.StringValue(t.substring(0,n));o.push(h);}o.push(new ue.StringValue(`
25
+ `)),l=r+1;}if(a!=-1&&(u=s),u>l){let h=t.substring(l,u);o.push(new ue.StringValue(h));}if(a!=-1&&s>r&&(o.push(new ue.StringValue(`
26
+ `)),a<t.length-1)){let h=t.length-a-1,c=new ue.StringValue(t.substring(a+1,a+1+h));o.push(c);}return o}PushToOutputStreamIndividual(e){let t=(0, ae.asOrNull)(e,yl.Glue),n=(0, ae.asOrNull)(e,ue.StringValue),r=true;if(t)this.TrimNewlinesFromOutputStream(),r=true;else if(n){let a=-1,s=this.callStack.currentElement;s.type==bt.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u],c=h instanceof Ee.ControlCommand?h:null;if((h instanceof yl.Glue?h:null)!=null){o=u;break}else if(c!=null&&c.commandType==Ee.ControlCommand.CommandType.BeginString){u>=a&&(a=-1);break}}let l=-1;if(o!=-1&&a!=-1?l=Math.min(a,o):o!=-1?l=o:l=a,l!=-1){if(n.isNewline)r=false;else if(n.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let u=this.callStack.elements;for(let h=u.length-1;h>=0;h--){let c=u[h];if(c.type==bt.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(r=false);}if(r){if(e===null)return (0, qe.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let n=this.outputStream[t],r=(0, ae.asOrNull)(n,Ee.ControlCommand),a=(0, ae.asOrNull)(n,ue.StringValue);if(r!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t<this.outputStream.length;)(0, ae.asOrNull)(this.outputStream[t],ue.StringValue)?this.outputStream.splice(t,1):t++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let e=this.outputStream.length-1;e>=0;e--){let t=this.outputStream[e];if(t instanceof yl.Glue)this.outputStream.splice(e,1);else if(t instanceof Ee.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof Ee.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof ue.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof ue.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, ae.asOrNull)(this.outputStream[e],Ee.ControlCommand);if(t instanceof Ee.ControlCommand&&t.commandType==Ee.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, ae.asOrNull)(e,ue.ListValue);if(t){let n=t.value;if(n===null)return (0, qe.throwNullException)("rawList");if(n.originNames!=null){n.origins||(n.origins=[]),n.origins.length=0;for(let r of n.originNames){if(this.story.listDefinitions===null)return (0, qe.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(r,null);if(a.result===null)return (0, qe.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, qe.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, ae.nullIfUndefined)(t)}else {if(e>this.evaluationStack.length)throw new Error("trying to pop too many objects");let t=this.evaluationStack.splice(this.evaluationStack.length-e,e);return (0, ae.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=mn.Pointer.Null,this.previousPointer=mn.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){Og.Debug.Assert(this.callStack.currentElement.type==bt.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let n=this.outputStream[t],r=(0, ae.asOrNull)(n,ue.StringValue),a=(0, ae.asOrNull)(n,Ee.ControlCommand);if(r!=null){if(a)break;if(r.isNewline||r.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==bt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(e);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(bt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=mn.Pointer.StartOf(e),this.PassArgumentsToEvaluationStack(t);}PassArgumentsToEvaluationStack(e){if(e!==null)for(let t=0;t<e.length;t++){if(!(typeof e[t]=="number"||typeof e[t]=="string"||typeof e[t]=="boolean"||e[t]instanceof Fg.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, ae.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(ue.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==bt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=mn.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=bt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let e=this.callStack.currentElement.evaluationStackHeightWhenPushed,t=null;for(;this.evaluationStack.length>e;){let n=this.PopEvaluationStack();t===null&&(t=n);}if(this.PopCallStack(bt.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof _g.Void)return null;let n=(0, ae.asOrThrows)(t,ue.Value);return n.valueType==ue.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(e,t){t?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(e)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(e));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};Ps.StoryState=Sl;});var ic=x(Fs=>{Object.defineProperty(Fs,"__esModule",{value:true});Fs.Stopwatch=void 0;var El=class{constructor(){this.startTime=void 0;}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime();}Stop(){this.startTime=void 0;}};Fs.Stopwatch=El;});var sc=x(Ns=>{Object.defineProperty(Ns,"__esModule",{value:true});Ns.ErrorType=void 0;var rc;(function(i){i[i.Author=0]="Author",i[i.Warning=1]="Warning",i[i.Error=2]="Error";})(rc||(Ns.ErrorType=rc={}));});var Zn=x(Mt=>{Object.defineProperty(Mt,"__esModule",{value:true});Mt.Story=Mt.InkList=void 0;var ge=ie(),Dl=xe(),bl=fn(),Ng=nc(),k=fe(),Me=kt(),Ig=Zi(),Vg=sl(),ac=et(),F=ee(),Al=Ae(),ri=Vt(),Is=gs(),kg=vt(),Rg=cn(),Lg=Ze(),jt=Pn(),xl=fl(),qt=Nt(),Bg=ol(),Wg=ic(),xt=qn(),si=_e(),R=H(),J=pe(),oc=gl(),lc=sc(),jg=_e();Object.defineProperty(Mt,"InkList",{enumerable:true,get:function(){return jg.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var gn=class i extends Dl.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, J.throwNullException)("this._state");for(let t of this._state.currentChoices)t.isInvisibleDefault||(t.index=e.length,e.push(t));return e}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=false,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=false,this._temporaryEvaluationContainer=null,this._asyncContinueActive=false,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount=0,this._asyncSaving=false,this._profiler=null;let e,t=null,n=null;if(arguments[0]instanceof ge.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let r=arguments[0];n=oc.SimpleJson.TextToDictionary(r);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new Bg.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let r=n,a=r.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let s=parseInt(a);if(s>i.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(s<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");s!=i.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${i.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=r.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let l;(l=r.listDefs)&&(this._listDefinitions=bl.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, R.asOrThrows)(bl.JsonSerialisation.JTokenToRuntimeObject(o),ge.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new oc.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",i.inkVersionCurrent),e.WriteProperty("root",n=>bl.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[r,a]of n.items){let s=si.InkListItem.fromSerializedKey(r),o=a;e.WriteIntProperty(s.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new Ng.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, J.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, J.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new Al.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=e;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(e){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+e);this.state.SwitchFlow_Internal(e);}RemoveFlow(e){this.state.RemoveFlow_Internal(e);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(e){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(e);}ContinueInternal(e=0){this._profiler!=null&&this._profiler.PreContinue();let t=e>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!t&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=t,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=false,this._state.ResetOutput(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation();}let n=new Wg.Stopwatch;n.Start();let r=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{r=this.ContinueSingleStep();}catch(s){if(!(s instanceof jt.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(r||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((r||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(Me.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(Me.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(a=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let s of this.state.currentErrors)this.onError(s,lc.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,lc.ErrorType.Warning);this.ResetErrors();}else {let s=new qt.StringBuilder;throw s.Append("Ink had "),this.state.hasError&&(s.Append(`${this.state.currentErrors.length}`),s.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&s.Append(" and ")),this.state.hasWarning&&(s.Append(`${this.state.currentWarnings.length}`),s.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&s.Append(" and ")),s.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),s.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new jt.StoryException(s.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, J.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, J.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==i.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==i.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(e,t,n,r){if(e===null)return (0, J.throwNullException)("prevText");if(t===null)return (0, J.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
27
+ `;if(n==r&&e.length==t.length&&a)return i.OutputStateChange.NoChange;if(!a)return i.OutputStateChange.NewlineRemoved;if(r>n)return i.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return i.OutputStateChange.ExtendedBeyondNewline}return i.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new qt.StringBuilder;for(;this.canContinue;)e.Append(this.Continue());return e.toString()}ContentAtPath(e){return this.mainContentContainer.ContentAtPath(e)}KnotContainerWithName(e){let t=this.mainContentContainer.namedContent.get(e);return t instanceof ge.Container?t:null}PointerAtPath(e){if(e.length==0)return xt.Pointer.Null;let t=new xt.Pointer,n=e.length,r=null;return e.lastComponent===null?(0, J.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(n=e.length-1,r=this.mainContentContainer.ContentAtPath(e,void 0,n),t.container=r.container,t.index=e.lastComponent.index):(r=this.mainContentContainer.ContentAtPath(e),t.container=r.container,t.index=-1),r.obj==null||r.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):r.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+r.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, J.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let e=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,e}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let e=true,t=this.state.currentPointer.copy();if(t.isNull)return;let n=(0, R.asOrNull)(t.Resolve(),ge.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)t=xt.Pointer.StartOf(n),n=(0, R.asOrNull)(t.Resolve(),ge.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let r=t.Resolve(),a=this.PerformLogicAndFlowControl(r);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, R.asOrNull)(r,Ig.ChoicePoint);if(s){let l=this.ProcessChoice(s);l&&this.state.generatedChoices.push(l),r=null,e=false;}if(r instanceof ge.Container&&(e=false),e){let l=(0, R.asOrNull)(r,F.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);r=new F.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(r):this.state.PushToOutputStream(r);}this.NextContent();let o=(0, R.asOrNull)(r,k.ControlCommand);o&&o.commandType==k.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let s=e.Resolve(),o=(0, R.asOrNull)(s,ge.Container)||(0, R.asOrNull)(e.container,ge.Container);for(;o;)this._prevContainers.push(o),o=(0, R.asOrNull)(o.parent,ge.Container);}let n=t.Resolve();if(n==null)return;let r=(0, R.asOrNull)(n.parent,ge.Container),a=true;for(;r&&(this._prevContainers.indexOf(r)<0||r.countingAtStartOnly);){let s=r.content.length>0&&n==r.content[0]&&a;s||(a=false),this.VisitContainer(r,s),n=r,r=(0, R.asOrNull)(r.parent,ge.Container);}}PopChoiceStringAndTags(e){let t=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);for(;this.state.evaluationStack.length>0&&(0, R.asOrNull)(this.state.PeekEvaluationStack(),Is.Tag)!=null;){let n=(0, R.asOrNull)(this.state.PopEvaluationStack(),Is.Tag);n&&e.push(n.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let n="",r="",a=[];if(e.hasChoiceOnlyContent&&(r=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new Vg.Choice;return s.targetPath=e.pathOnChoice,s.sourcePath=e.path.toString(),s.isInvisibleDefault=e.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(n+r).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof F.Value){let n=e;if(n instanceof F.DivertTargetValue){let r=n;return this.Error("Shouldn't use a divert target (to "+r.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof ac.Divert){let t=e;if(t.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(t.hasVariableTarget){let n=t.variableDivertName,r=this.state.variablesState.GetVariableWithName(n);if(r==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(r instanceof F.DivertTargetValue)){let s=(0, R.asOrNull)(r,F.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";s instanceof F.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+r+"'.",this.Error(o);}let a=(0, R.asOrThrows)(r,F.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),true;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),true}else if(e instanceof k.ControlCommand){let t=e;switch(t.commandType){case k.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case k.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case k.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let m=this.state.PopEvaluationStack();if(!(m instanceof ri.Void)){let S=new F.StringValue(m.toString());this.state.PushToOutputStream(S);}}break;case k.ControlCommand.CommandType.NoOp:break;case k.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case k.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case k.ControlCommand.CommandType.PopFunction:case k.ControlCommand.CommandType.PopTunnel:let n=t.commandType==k.ControlCommand.CommandType.PopFunction?Me.PushPopType.Function:Me.PushPopType.Tunnel,r=null;if(n==Me.PushPopType.Tunnel){let m=this.state.PopEvaluationStack();r=(0, R.asOrNull)(m,F.DivertTargetValue),r===null&&this.Assert(m instanceof ri.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let m=new Map;m.set(Me.PushPopType.Function,"function return statement (~ return)"),m.set(Me.PushPopType.Tunnel,"tunnel onwards statement (->->)");let S=m.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(S="end of flow (-> END or choice)");let w="Found "+m.get(n)+", when expected "+S;this.Error(w);}else this.state.PopCallStack(),r&&(this.state.divertedPointer=this.PointerAtPath(r.targetPath));break;case k.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(t),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case k.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case k.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let m=[],S=0;for(let N=this.state.outputStream.length-1;N>=0;--N){let Z=this.state.outputStream[N];S++;let ye=(0, R.asOrNull)(Z,k.ControlCommand);if(ye!=null){if(ye.commandType==k.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}Z instanceof F.StringValue&&m.push(Z);}this.state.PopFromOutputStream(S);let w=new qt.StringBuilder;for(let N of m.reverse())w.Append(N.toString());let P=new Is.Tag(this.state.CleanOutputWhitespace(w.toString()));this.state.PushEvaluationStack(P);}else this.state.PushToOutputStream(t);break}case k.ControlCommand.CommandType.EndString:{let m=[],S=[],w=0;for(let N=this.state.outputStream.length-1;N>=0;--N){let Z=this.state.outputStream[N];w++;let ye=(0, R.asOrNull)(Z,k.ControlCommand);if(ye&&ye.commandType==k.ControlCommand.CommandType.BeginString)break;Z instanceof Is.Tag&&S.push(Z),Z instanceof F.StringValue&&m.push(Z);}this.state.PopFromOutputStream(w);for(let N of S)this.state.PushToOutputStream(N);m=m.reverse();let P=new qt.StringBuilder;for(let N of m)P.Append(N.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new F.StringValue(P.toString()));break}case k.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new F.IntValue(a));break;case k.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new F.IntValue(this.state.currentTurnIndex+1));break;case k.ControlCommand.CommandType.TurnsSince:case k.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof F.DivertTargetValue)){let m="";s instanceof F.IntValue&&(m=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+m);break}let o=(0, R.asOrThrows)(s,F.DivertTargetValue),l=(0, R.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,ge.Container),u;l!=null?t.commandType==k.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(t.commandType==k.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new F.IntValue(u));break;case k.ControlCommand.CommandType.Random:{let m=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),S=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(S==null||!(S instanceof F.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(m==null||!(m instanceof F.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(m.value===null)return (0, J.throwNullException)("maxInt.value");if(S.value===null)return (0, J.throwNullException)("minInt.value");let w=m.value-S.value+1;(!isFinite(w)||w>Number.MAX_SAFE_INTEGER)&&(w=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),w<=0&&this.Error("RANDOM was called with minimum as "+S.value+" and maximum as "+m.value+". The maximum must be larger");let P=this.state.storySeed+this.state.previousRandom,Z=new xl.PRNG(P).next(),ye=Z%w+S.value;this.state.PushEvaluationStack(new F.IntValue(ye)),this.state.previousRandom=Z;break}case k.ControlCommand.CommandType.SeedRandom:let h=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(h==null||!(h instanceof F.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, J.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new ri.Void);break;case k.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new F.IntValue(c));break;case k.ControlCommand.CommandType.SequenceShuffleIndex:let p=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new F.IntValue(p));break;case k.ControlCommand.CommandType.StartThread:break;case k.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=xt.Pointer.Null);break;case k.ControlCommand.CommandType.End:this.state.ForceEnd();break;case k.ControlCommand.CommandType.ListFromInt:let f=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),v=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);if(f===null)throw new jt.StoryException("Passed non-integer when creating a list element from a numerical value.");let g=null;if(this.listDefinitions===null)return (0, J.throwNullException)("this.listDefinitions");let A=this.listDefinitions.TryListGetDefinition(v.value,null);if(A.exists){if(f.value===null)return (0, J.throwNullException)("minInt.value");let m=A.result.TryGetItemWithValue(f.value,si.InkListItem.Null);m.exists&&(g=new F.ListValue(m.result,f.value));}else throw new jt.StoryException("Failed to find LIST called "+v.value);g==null&&(g=new F.ListValue),this.state.PushEvaluationStack(g);break;case k.ControlCommand.CommandType.ListRange:let D=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.Value),C=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.Value),d=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.ListValue);if(d===null||C===null||D===null)throw new jt.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(d.value===null)return (0, J.throwNullException)("targetList.value");let E=d.value.ListWithSubRange(C.valueObject,D.valueObject);this.state.PushEvaluationStack(new F.ListValue(E));break;case k.ControlCommand.CommandType.ListRandom:{let m=this.state.PopEvaluationStack();if(m===null)throw new jt.StoryException("Expected list for LIST_RANDOM");let S=m.value,w=null;if(S===null)throw (0, J.throwNullException)("list");if(S.Count==0)w=new si.InkList;else {let P=this.state.storySeed+this.state.previousRandom,Z=new xl.PRNG(P).next(),ye=Z%S.Count,$t=S.entries();for(let Ml=0;Ml<=ye-1;Ml++)$t.next();let ql=$t.next().value,di={Key:si.InkListItem.fromSerializedKey(ql[0]),Value:ql[1]};if(di.Key.originName===null)return (0, J.throwNullException)("randomItem.Key.originName");w=new si.InkList(di.Key.originName,this),w.Add(di.Key,di.Value),this.state.previousRandom=Z;}this.state.PushEvaluationStack(new F.ListValue(w));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof kg.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),true}else if(e instanceof Rg.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let r=t.containerForCount,a=this.state.VisitCountForContainer(r);n=new F.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(t.name),n==null&&(this.Warning("Variable not found: '"+t.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),n=new F.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(e instanceof Lg.NativeFunctionCall){let t=e,n=this.state.PopEvaluationStack(t.numberOfParameters),r=t.Call(n);return this.state.PushEvaluationStack(r),true}return false}ChoosePathString(e,t=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,n),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==Me.PushPopType.Function){let r="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(r="("+a.path.toString()+") "),new Error("Story was running a function "+r+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace:
28
+ `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new Al.Path(e));}IfAsyncWeCant(e){if(this._asyncContinueActive)throw new Error("Can't "+e+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(e,t=true){this.state.SetChosenPath(e,t),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(e){e=e;let t=this.currentChoices;this.Assert(e>=0&&e<t.length,"choice out of range");let n=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, J.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, J.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(e,t),this.IfAsyncWeCant("evaluate a function"),e==null)throw new Error("Function is null");if(e==""||e.trim()=="")throw new Error("Function is empty or white space.");let r=this.KnotContainerWithName(e);if(r==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(r,t);let s=new qt.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let l=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,l),n?{returned:l,output:o}:l}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(Me.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, J.throwNullException)("funcName");let n=this._externals.get(e),r=null,a=typeof n<"u";if(a&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+e+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+e+"()"),a&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){r=this.KnotContainerWithName(e),this.Assert(r!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(Me.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=xt.Pointer.StartOf(r);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let u=0;u<t;++u){let c=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.Value).valueObject;s.push(c);}s.reverse();let o=n.function(s),l=null;o!=null?(l=F.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new ri.Void,this.state.PushEvaluationStack(l);}BindExternalFunctionGeneral(e,t,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(e),"Function '"+e+"' has already been bound."),this._externals.set(e,{function:t,lookAheadSafe:n});}TryCoerce(e){return e}BindExternalFunction(e,t,n=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,r=>{this.Assert(r.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=r.length;s<o;s++)a[s]=this.TryCoerce(r[s]);return t.apply(null,a)},n);}UnbindExternalFunction(e){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(e),"Function '"+e+"' has not been bound."),this._externals.delete(e);}ValidateExternalBindings(){let e=null,t=null,n=arguments[1]||new Set;if(arguments[0]instanceof ge.Container&&(e=arguments[0]),arguments[0]instanceof Dl.InkObject&&(t=arguments[0]),e===null&&t===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let r="Error: Missing function binding for external";r+=n.size>1?"s":"",r+=": '",r+=Array.from(n).join("', '"),r+="' ",r+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(r);}else if(e!=null){for(let r of e.content){let a=r;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(r,n);}for(let[,r]of e.namedContent)this.ValidateExternalBindings((0, R.asOrNull)(r,Dl.InkObject),n);}else if(t!=null){let r=(0, R.asOrNull)(t,ac.Divert);if(r&&r.isExternal){let a=r.targetPathString;if(a===null)return (0, J.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.add(a);}}}ObserveVariable(e,t){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(e))throw new Error("Cannot observe variable '"+e+"' because it wasn't declared in the ink story.");this._variableObservers.has(e)?this._variableObservers.get(e).push(t):this._variableObservers.set(e,[t]);}ObserveVariables(e,t){for(let n=0,r=e.length;n<r;n++)this.ObserveVariable(e[n],t[n]);}RemoveVariableObserver(e,t){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(t!=null){if(this._variableObservers.has(t))if(e!=null){let n=this._variableObservers.get(t);n!=null&&(n.splice(n.indexOf(e),1),n.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let n=this._variableObservers.keys();for(let r of n){let a=this._variableObservers.get(r);a!=null&&(a.splice(a.indexOf(e),1),a.length===0&&this._variableObservers.delete(r));}}}}VariableStateDidChangeEvent(e,t){if(this._variableObservers===null)return;let n=this._variableObservers.get(e);if(typeof n<"u"){if(!(t instanceof F.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let r=(0, R.asOrThrows)(t,F.Value);for(let a of n)a(e,r.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new Al.Path(e),n=this.ContentAtPath(t).container;if(n===null)return (0, J.throwNullException)("flowContainer");for(;;){let s=n.content[0];if(s instanceof ge.Container)n=s;else break}let r=false,a=null;for(let s of n.content){let o=(0, R.asOrNull)(s,k.ControlCommand);if(o!=null)o.commandType==k.ControlCommand.CommandType.BeginTag?r=true:o.commandType==k.ControlCommand.CommandType.EndTag&&(r=false);else if(r){let l=(0, R.asOrNull)(s,F.StringValue);l!==null?(a===null&&(a=[]),l.value!==null&&a.push(l.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let e=new qt.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new qt.StringBuilder;return e.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=xt.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(Me.PushPopType.Function)?(this.state.PopCallStack(Me.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new ri.Void),t=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),t=true):this.state.TryExitFunctionEvaluationFromGame(),t&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let e=true,t=this.state.callStack.currentElement.currentPointer.copy();if(t.index++,t.container===null)return (0, J.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let n=(0, R.asOrNull)(t.container.parent,ge.Container);if(!(n instanceof ge.Container))break;let r=n.content.indexOf(t.container);if(r==-1)break;if(t=new xt.Pointer(n,r),t.index++,e=true,t.container===null)return (0, J.throwNullException)("pointer.container")}return e||(t=xt.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(r=>r.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let n=t[0];return n.targetPath===null?(0, J.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, J.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,false),true)}NextSequenceShuffleIndex(){let e=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(!(e instanceof F.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, J.throwNullException)("seqContainer");if(e.value===null)return (0, J.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.IntValue).value;if(a===null)return (0, J.throwNullException)("seqCount");let s=a/n,o=a%n,l=t.path.toString(),u=0;for(let f=0,v=l.length;f<v;f++)u+=l.charCodeAt(f)||0;let h=u+s+this.state.storySeed,c=new xl.PRNG(Math.floor(h)),p=[];for(let f=0;f<n;++f)p.push(f);for(let f=0;f<=o;++f){let v=c.next()%p.length,g=p[v];if(p.splice(v,1),f==o)return g}throw new Error("Should never reach here")}Error(e,t=false){let n=new jt.StoryException(e);throw n.useEndLineNumber=t,n}Warning(e){this.AddError(e,true);}AddError(e,t=false,n=false){let r=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(r!=null){let s=n?r.endLineNumber:r.startLineNumber;e="RUNTIME "+a+": '"+r.fileName+"' line "+s+": "+e;}else this.state.currentPointer.isNull?e="RUNTIME "+a+": "+e:e="RUNTIME "+a+": ("+this.state.currentPointer+"): "+e;this.state.AddError(e,t),t||this.state.ForceEnd();}Assert(e,t=null){if(e==false)throw t==null&&(t="Story assert"),new Error(t+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let e,t=this.state.currentPointer;if(!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(t=this.state.callStack.elements[n].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.outputStream.length-1;n>=0;--n)if(e=this.state.outputStream[n].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};Mt.Story=gn;gn.inkVersionCurrent=21;(function(i){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(i.OutputStateChange||(i.OutputStateChange={}));})(gn||(Mt.Story=gn={}));});var hc=x(Bs=>{Object.defineProperty(Bs,"__esModule",{value:true});Bs.Story=void 0;var qg=Fi(),Mg=gr(),Vs=ie(),ks=fe(),ai=Kt(),Rs=tt(),uc=on(),Gg=zo(),$g=Hr(),Jg=Zo(),Hg=Zn(),Cn=ct(),zg=Et(),Ug=vt(),oi=H(),Kg=$n(),Xg=Jn(),Yg=Lt(),Ls=class i extends Rs.FlowBase{get flowLevel(){return uc.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(e,t=false){super(null,e,null,false,t),this._errorHandler=null,this._hadError=false,this._hadWarning=false,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=false,this.ExportRuntime=(n=null)=>{var r,a;this._errorHandler=n,this.constants=new Map;for(let h of this.FindAll(Mg.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let p=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(p,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll($g.ListDefinition)())!((r=h.identifier)===null||r===void 0)&&r.name&&this._listDefs.set((a=h.identifier)===null||a===void 0?void 0:a.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let s=this.runtimeObject,o=new Vs.Container;o.AddContent(ks.ControlCommand.EvalStart());let l=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),o.AddContent(c.listDefinition.runtimeObject),l.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(o);}let p=new Ug.VariableAssignment(h,true);p.isGlobal=true,o.AddContent(p);}o.AddContent(ks.ControlCommand.EvalEnd()),o.AddContent(ks.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(ks.ControlCommand.Done());let u=new Hg.Story(s,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let r=this._listDefs.get(n);return r||null},this.ResolveListItem=(n,r,a=null)=>{let s=null;if(n)return (s=this._listDefs.get(n))?s.ItemNamed(r):null;{let o=null,l=null;for(let[,u]of this._listDefs.entries()){let h=u.ItemNamed(r);h&&(o?this.Error(`Ambiguous item name '${r}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,false):(o=h,l=u));}return o}},this.FlattenContainersIn=n=>{let r=new Set;if(n.content)for(let a of n.content){let s=(0, oi.asOrNull)(a,Vs.Container);s&&r.add(s);}if(n.namedContent)for(let[,a]of n.namedContent){let s=(0, oi.asOrNull)(a,Vs.Container);s&&r.add(s);}for(let a of r)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let r=(0, oi.asOrNull)(n.parent,Vs.Container);if(r){let a=r.content.indexOf(n);r.content.splice(a,1);let s=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),r.InsertContent(o,a),a+=1;}},this.Error=(n,r,a)=>{let s=a?ai.ErrorType.Warning:ai.ErrorType.Error,o="";if(r instanceof qg.AuthorWarning?(o+="TODO: ",s=ai.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",r&&r.debugMetadata!==null&&r.debugMetadata.startLineNumber>=1&&(r.debugMetadata.fileName!=null&&(o+=`'${r.debugMetadata.fileName}' `),o+=`line ${r.debugMetadata.startLineNumber}: `),o+=n,n=o,this._errorHandler!==null)this._errorHandler(n,s);else throw new Error(n);this._hadError=s===ai.ErrorType.Error,this._hadWarning=s===ai.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=n=>this.externals.has(n),this.AddExternal=n=>{this.externals.has(n.name)?this.Error(`Duplicate EXTERNAL definition of '${n.name}'`,n,false):n.name&&this.externals.set(n.name,n);},this.DontFlattenContainer=n=>{this._dontFlattenContainers.add(n);},this.NameConflictError=(n,r,a,s)=>{n.Error(`${s} '${r}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,r,a,s="")=>{var o;let l=s||n.typeName;if(i.IsReservedKeyword(r?.name)){n.Error(`'${r}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(Xg.FunctionCall.IsBuiltIn(r?.name||"")){n.Error(`'${r}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(r?.name||"",uc.FlowLevel.Knot),h=(0, oi.asOrNull)(u,Rs.FlowBase);if(h&&(h!==n||a===Cn.SymbolType.Arg)){this.NameConflictError(n,r?.name||"",h,l);return}if(a<Cn.SymbolType.List)return;for(let[v,g]of this._listDefs)if(r?.name===v&&n!==g&&g.variableAssignment!==n&&this.NameConflictError(n,r?.name,g,l),!(n instanceof Jg.ListElementDefinition))for(let A of g.itemDefinitions)r?.name===A.name&&this.NameConflictError(n,r?.name||"",A,l);if(a<=Cn.SymbolType.Var)return;let c=r?.name&&this.variableDeclarations.get(r?.name)||null;if(c&&c!==n&&c.isGlobalDeclaration&&c.listDefinition==null&&this.NameConflictError(n,r?.name||"",c,l),a<Cn.SymbolType.SubFlowAndWeave)return;let f=new Yg.Path(r).ResolveFromContext(n);if(f&&f!==n){this.NameConflictError(n,r?.name||"",f,l);return}if(!(a<Cn.SymbolType.Arg)&&a!==Cn.SymbolType.Arg){let v=(0, oi.asOrNull)(n,Rs.FlowBase);if(v||(v=(0, Kg.ClosestFlowBase)(n)),v&&v.hasParameters&&v.args){for(let g of v.args)if(((o=g.identifier)===null||o===void 0?void 0:o.name)===r?.name){n.Error(`${l} '${r}': name has already been used for a argument to ${v.identifier} on ${v.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let n of e)if(n instanceof Gg.IncludedFile){let r=n,a=e.indexOf(n);if(e.splice(a,1),r.includedStory){let s=[],o=r.includedStory;if(o.content!=null){for(let l of o.content)l instanceof Rs.FlowBase?t.push(l):s.push(l);s.push(new zg.Text(`
29
+ `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};Bs.Story=Ls;Ls.IsReservedKeyword=i=>{switch(i){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var dc=x(Ws=>{Object.defineProperty(Ws,"__esModule",{value:true});Ws.StringExpression=void 0;var cc=fe(),Qg=Le(),Zg=Et(),eC=H(),wl=class i extends Qg.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof Zg.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(cc.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(cc.ControlCommand.EndString());},this.toString=()=>{let t="";for(let n of this.content)t+=n;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, eC.asOrNull)(e,i);if(t===null||!this.isSingleString||!t.isSingleString)return false;let n=this.toString(),r=t.toString();return n===r}};Ws.StringExpression=wl;});var fc=x(yn=>{Object.defineProperty(yn,"__esModule",{value:true});yn.LegacyTag=yn.Tag=void 0;var tC=Q(),pc=fe(),_l=class extends tC.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?pc.ControlCommand.BeginTag():pc.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};yn.Tag=_l;var nC=Mo(),Ol=class extends nC.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};yn.LegacyTag=Ol;});var mc=x(js=>{Object.defineProperty(js,"__esModule",{value:true});js.DefaultFileHandler=void 0;var Tl=class{constructor(e){this.rootPath=e,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};js.DefaultFileHandler=Tl;});var Il=x($s=>{Object.defineProperty($s,"__esModule",{value:true});$s.InkParser=void 0;var iC=Bu(),rC=Fi(),sC=Ra(),He=Yu(),ce=Wn(),aC=an(),oC=ah(),lC=pr(),li=Co(),Pe=_r(),uC=gr(),qs=Oh(),hC=Th(),Gt=hn(),Pl=un(),cC=Le(),dC=Ph(),gc=Fh(),Ms=Jn(),pC=Gn(),fC=Nh(),mC=as(),Gs=Vh(),Cc=zo(),gC=kh(),CC=Xo(),yc=Lh(),yC=Hr(),vC=Zo(),SC=po(),vc=Q(),EC=Lt(),Sc=io(),Ec=wo(),he=bo(),De=el(),DC=nl(),Dc=hc(),ui=dc(),dt=za(),vn=fc(),pt=Et(),bc=Oo(),Fl=Vo(),Nl=dn(),bC=Va(),wt=H(),hi=Ar(),Sn=zi(),Ac=Kt(),AC=mc(),U=class i extends dt.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,n=null,r=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel(De.StatementLevel.Top);return new Dc.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let l=this.Parse(s);if(l===null)return null;let u=[];u.push(l);do{let h=this.BeginRule();if(o()===null){this.FailRule(h);break}let p=this.Parse(s);if(p===null){this.FailRule(h);break}this.SucceedRule(h),u.push(p);}while(true);return u},this.CreateDebugMetadata=(s,o)=>{let l=new hC.DebugMetadata;return l.startLineNumber=(s?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(s?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(s,o,l)=>{let u=(0, wt.asOrNull)(s,vc.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let h=Array.isArray(s)?s:null;if(h!==null)for(let p of h)(0, wt.asOrNull)(p,vc.ParsedObject)&&(p.hasOwnDebugMetadata||(p.debugMetadata=this.CreateDebugMetadata(o,l)));let c=(0, wt.asOrNull)(s,hi.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(s,o,l=0,u=false)=>{let c=u?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${l+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,u?Ac.ErrorType.Warning:Ac.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
30
+ \r`);return o?new rC.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=i.ListAllCharacterRanges();for(let l of o)s.AddCharacters(l.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let s=true,o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!o){if(o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),o===null)return null;s=false;}let l=this.Parse(this.BracketedName);this.Whitespace(),l!=null&&this.Newline();let u=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let h=null,c=this.Parse(this.MixedTextAndLogic);c&&(h=new Pe.ContentList(c));let p=null,f=null,v=this.ParseString("[")!==null;if(v){this.EndTagIfNecessary(h);let C=this.Parse(this.MixedTextAndLogic);C!==null&&(p=new Pe.ContentList(C)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(p);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(f=new Pe.ContentList(d));}this.Whitespace(),this.EndTagIfNecessary(f??h);let g=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let A=!h&&!f&&!p;if(A&&g===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&v&&!p&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),f||(f=new Pe.ContentList),this.EndTagIfNecessary(f),g!==null)for(let C of g){let d=(0, wt.asOrNull)(C,Gt.Divert);d&&d.isEmpty||f.AddContent(C);}f.AddContent(new pt.Text(`
31
+ `));let D=new aC.Choice(h,p,f);return l&&(D.identifier=l),D.indentationDepth=o.length,D.hasWeaveStyleInlineBrackets=v,D.condition=u,D.onceOnly=s,D.isInvisibleDefault=A,D},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new SC.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),dt.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let s=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(s),this.Expect(this.String("}"),"closing '}' for choice condition"),s},this.Gather=()=>{let s=this.Parse(this.GatherDashes);if(s===null)return null;let o=Number(s),l=this.Parse(this.BracketedName),u=new pC.Gather(l,o);return this.Newline(),u},this.GatherDashes=()=>{this.Whitespace();let s=0;for(;this.ParseDashNotArrow()!==null;)s+=1,this.Whitespace();return s===0?null:s},this.ParseDashNotArrow=()=>{let s=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(s):this.FailRule(s)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),s)},this.InnerConditionalContent=s=>{if(s===void 0){let c=this.Parse(this.ConditionExpression),p=this.Parse(()=>this.InnerConditionalContent(c));return p===null?null:p}let o,l=s!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let c=this.StatementsAtLevel(De.StatementLevel.InnerBlock);if(c!==null){o=[new li.ConditionalSingleBranch(c)];let f=this.Parse(this.SingleMultilineCondition);f&&(f.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",f),f.isElse=true),o.push(f));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let c=new li.ConditionalSingleBranch(null);c.isTrueBranch=true,o.unshift(c);}if(s){let c=false;for(let p=0;p<o.length;++p){let f=o[p],v=p===o.length-1;f.ownExpression?(f.matchingEquality=true,c=true):c&&v?(f.matchingEquality=true,f.isElse=true):!v&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",f):p===0?f.isTrueBranch=true:f.isElse=true;}}else {for(let c=0;c<o.length;++c){let p=o[c],f=c===o.length-1;if(p.ownExpression===null)if(f)p.isElse=true;else if(p.isElse){let v=o[o.length-1];v.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",v):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",p);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",p);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let c of o)c.isInline=u;return new lC.Conditional(s,o)},this.InlineConditionalBranches=()=>{let s=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(s===null||s.length===0)return null;let o=[];if(s.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let l=new li.ConditionalSingleBranch(s[0]);if(l.isTrueBranch=true,o.push(l),s.length>1){let u=new li.ConditionalSingleBranch(s[1]);u.isElse=true,o.push(u);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineCondition);return s===null?null:(this.MultilineWhitespace(),s)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=null,o=this.Parse(this.ElseExpression)!==null;o||(s=this.Parse(this.ConditionExpression));let l=this.StatementsAtLevel(De.StatementLevel.InnerBlock);s===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new pt.Text("")]),this.MultilineWhitespace();let u=new li.ConditionalSingleBranch(l);return u.ownExpression=s,u.isElse=o,u},this.ConditionExpression=()=>{let s=this.Parse(this.Expression);return s===null||(this.DisallowIncrement(s),this.Whitespace(),this.ParseString(":")===null)?null:s},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:dt.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let l=s.length-1,u=s[l];if(u instanceof pt.Text){let h=u;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),o?h.text+=" ":h.text.length===0&&(s.splice(l,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof Gt.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof vn.Tag&&s[0].isStart||s.push(new pt.Text(`
32
+ `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),s)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let o=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let l=this.Parse(this.MultiDivert);l!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...l));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),l){let u=this.ParseSingleCharacter();s+=u;}}else break}while(true);return s!==null?new pt.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new ce.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new ce.CharacterSet(`{}|
33
+ \r\\#`),this._notTextEndCharactersChoice=new ce.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new ce.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let s=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let l=this.ParseUntil(s,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;s=[],this.EndTagIfNecessary(s);for(let u=0;u<l.length;++u)if(u%2===0){if(l[u]==="->->"){u===0||u===l.length-1||u===l.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let p=new bc.TunnelOnwards;if(u<l.length-1){let f=(0, wt.asOrNull)(l[u+1],Gt.Divert);p.divertAfter=f;}s.push(p);break}}else {let c=l[u];u<l.length-1&&(c.isTunnel=true),s.push(c);}if(s.length===0&&l.length===1){let u=new Gt.Divert(null);u.isEmpty=true,s.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new Gt.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new EC.Path(s);return new Gt.Divert(l,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof bc.TunnelOnwards)return null;let l=s[0];return l.isTunnel?null:l},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let s=0;for(;this.ParseString("->")!==null;)s+=1;return s===0?null:s===1?"->":(s===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let s=this.ParseTempKeyword();this.Whitespace();let o=null;if(s?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let l=this.ParseString("+")!==null,u=this.ParseString("-")!==null;if(l&&u&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return s&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return l||u?new Gs.IncDecExpression(o,h,l):new Fl.VariableAssignment({variableIdentifier:o,assignedExpression:h,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof Gs.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let s=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(s),true):(this.FailRule(s),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new Sc.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>s){let h=`right side of '${u.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(o,u),h);if(c===null)return this.FailRule(l),null;o=this.SucceedRule(l,c);continue}this.FailRule(l);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let s=this.Parse(this.ExpressionDivertTarget);if(s!==null)return s;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&o!==null&&(l=this.ExpressionUnary()),l===null)return null;o!==null&&(l=bC.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof Nl.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new Gs.IncDecExpression(c.identifier,h);}}return l},this.ExpressionNot=()=>{let s=this.Identifier();return s==="not"?s:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let s=this.Parse(this.SingleDivert);return !s||s&&s.isThread?null:(this.Whitespace(),new Pl.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new Sn.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new Sn.NumberExpression(s,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let o=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,o===null?o=[new pt.Text("")]:o.find(l=>l instanceof Gt.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new ui.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new Sn.NumberExpression(true,"bool"):s==="false"?new Sn.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new Ms.FunctionCall(s,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,s);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let s=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return s===null||Dc.Story.IsReservedKeyword(s[0].name)?null:new Nl.VariableReference(s)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let s=this.Parse(this.Expression);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),s)},this.ExpressionInfixRight=(s,o)=>{if(!s)return null;this.Whitespace();let l=this.Parse(()=>this.Expression(o.precedence));return l?new sC.BinaryExpression(s,l,o.type):null},this.ParseInfixOperator=()=>{for(let s of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(s.type)!==null){if(s.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,s)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let s=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new yc.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${l?.name}`;}return this.Whitespace(),s},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(s,o,l=false)=>{let u=new gC.InfixOperator(s,o,l);this._binaryOperators.push(u),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,s.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let s=this.Expect(()=>this.ParseUntilCharactersFromString(`
34
34
  \r`),"filename for include statement");s=s.replace(new RegExp(/[ \t]+$/g),"");let o=this.fileHandler.ResolveInkFilename(s,this._filename);if(this.FilenameIsAlreadyOpen(o))return this.Error(`Recursive INCLUDE detected: '${o}' is already open.`),this.ParseUntilCharactersFromString(`\r
35
- `),new kc.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(h){this.Error(`Failed to load: '${s}'.
36
- Error:${h}`);}return u!=null&&(l=new i(u,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new kc.IncludedFile(l)},this.FilenameIsAlreadyOpen=s=>this._rootParser._openFilenames.includes(s),this.AddOpenFilename=s=>{this._rootParser._openFilenames.push(s);},this.RemoveOpenFilename=s=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(s),1);},this.KnotDefinition=()=>{let s=this.Parse(this.KnotDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(Fe.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new QC.Knot(s.name,l,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,l=s?.name==="function";l?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=s,o===null&&(this.Error(`Expected the name of the ${l?"function":"knot"}`),o=new bi.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new Ic.FlowDecl(o,u,l)},this.KnotTitleEquals=()=>{let s=this.ParseCharactersFromString("=");return s===null||s.length<=1?null:s},this.StitchDefinition=()=>{let s=this.Parse(this.StitchDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(Fe.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new iy.Stitch(s.name,l,s.args,s.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let s=this.ParseString("function")!==null;s&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new Ic.FlowDecl(o,l,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new pe.CharacterSet("="),null),[new At.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),s===null&&(s=[]),s},this.FlowDeclArgument=()=>{let s=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(s==null&&l===null)return null;let u=new BC.Argument;return o!==null&&(u.isDivertTarget=true),s!==null&&s.name==="ref"?(l===null&&this.Error("Expected an parameter name after 'ref'"),u.identifier=l,u.isByReference=true):(u.isDivertTarget?u.identifier=l:u.identifier=s,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},this.ExternalDeclaration=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new bi.Identifier("");this.Whitespace();let l=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);l===null&&(l=[]);let u=l.map(h=>{var c;return (c=h.identifier)===null||c===void 0?void 0:c.name}).filter(Bt.filterUndef);return new zC.ExternalDeclaration(o,u)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let s=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(s,"expression after '~'",this.SkipToNextLine);if(o===null)return new qe.ContentList;o instanceof HC.Expression&&!(o instanceof ta.FunctionCall||o instanceof na.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
35
+ `),new Cc.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(h){this.Error(`Failed to load: '${s}'.
36
+ Error:${h}`);}return u!=null&&(l=new i(u,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new Cc.IncludedFile(l)},this.FilenameIsAlreadyOpen=s=>this._rootParser._openFilenames.includes(s),this.AddOpenFilename=s=>{this._rootParser._openFilenames.push(s);},this.RemoveOpenFilename=s=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(s),1);},this.KnotDefinition=()=>{let s=this.Parse(this.KnotDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(De.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new CC.Knot(s.name,l,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,l=s?.name==="function";l?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=s,o===null&&(this.Error(`Expected the name of the ${l?"function":"knot"}`),o=new hi.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new gc.FlowDecl(o,u,l)},this.KnotTitleEquals=()=>{let s=this.ParseCharactersFromString("=");return s===null||s.length<=1?null:s},this.StitchDefinition=()=>{let s=this.Parse(this.StitchDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(De.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new DC.Stitch(s.name,l,s.args,s.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let s=this.ParseString("function")!==null;s&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new gc.FlowDecl(o,l,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new ce.CharacterSet("="),null),[new pt.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),s===null&&(s=[]),s},this.FlowDeclArgument=()=>{let s=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(s==null&&l===null)return null;let u=new iC.Argument;return o!==null&&(u.isDivertTarget=true),s!==null&&s.name==="ref"?(l===null&&this.Error("Expected an parameter name after 'ref'"),u.identifier=l,u.isByReference=true):(u.isDivertTarget?u.identifier=l:u.identifier=s,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},this.ExternalDeclaration=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new hi.Identifier("");this.Whitespace();let l=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);l===null&&(l=[]);let u=l.map(h=>{var c;return (c=h.identifier)===null||c===void 0?void 0:c.name}).filter(wt.filterUndef);return new dC.ExternalDeclaration(o,u)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let s=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(s,"expression after '~'",this.SkipToNextLine);if(o===null)return new Pe.ContentList;o instanceof cC.Expression&&!(o instanceof Ms.FunctionCall||o instanceof Gs.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
37
37
  ~ return
38
38
  ~ var x = blah
39
39
  ~ x++
40
- ~ myFunction()`);let l=(0, Bt.asOrNull)(o,ta.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(ta.FunctionCall)()!==null&&(o=new qe.ContentList(o,new At.Text(`
41
- `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u?(u instanceof Nn.NumberExpression||u instanceof Ei.StringExpression||u instanceof Hl.DivertTarget||u instanceof Ul.VariableReference||u instanceof Rc.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):u instanceof Ei.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new zl.VariableAssignment({assignedExpression:u,isGlobalDeclaration:true,variableIdentifier:o})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let l=this.Expect(this.ListDefinition,"list item names");return l?(l.identifier=new bi.Identifier(o.name),new zl.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new ZC.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let u=null;if(this.ParseString("=")!==null){this.Whitespace();let h=this.Expect(this.ExpressionInt,"value to be assigned to list item");h!==null&&(u=h.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new ey.ListElementDefinition(l,s,u)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l instanceof Nn.NumberExpression||l instanceof Hl.DivertTarget||l instanceof Ei.StringExpression?l instanceof Ei.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new $C.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new KC.Glue(new XC.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let l=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(l===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(l);let u=(0, Bt.asOrNull)(l,qe.ContentList);return u||(u=new qe.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new Wc.Sequence(u,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let l=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let u of l){let h=this.BeginRule(),c=this.ParseObject(u);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let s=this.Parse(this.Expression);return s&&(s.outputWhenComplete=true),s},this.IdentifierWithMetadata=()=>{let s=this.Identifier();return s===null?null:new bi.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let l of s)if(!(l>="0"&&l<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new pe.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=de.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new Wc.Sequence(l,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case de.SequenceType.Once:case de.SequenceType.Cycle:case de.SequenceType.Stopping:case de.SequenceType.Shuffle:case de.SequenceType.Shuffle|de.SequenceType.Stopping:case de.SequenceType.Shuffle|de.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),de.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new pe.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":s|=de.SequenceType.Once;break;case "&":s|=de.SequenceType.Cycle;break;case "~":s|=de.SequenceType.Shuffle;break;case "$":s|=de.SequenceType.Stopping;break}return s===0?null:s},this.SequenceTypeWordAnnotation=()=>{let s=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(s===null||s.length===0||this.ParseString(":")===null)return null;let o=0;for(let l of s)o|=l;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=de.SequenceType.Once;break;case "cycle":s=de.SequenceType.Cycle;break;case "shuffle":s=de.SequenceType.Shuffle;break;case "stopping":s=de.SequenceType.Stopping;break}return s===null?null:s},this.InnerSequenceObjects=()=>{let s=this.Parse(this.Newline)!==null,o=null;return s?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let s=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(s===null)return null;let o=[],l=false;for(let u of s)if(u==="|")l||o.push(new qe.ContentList),l=false;else {let h=u;h===null?this.Error(`Expected content, but got ${u} (this is an ink compiler bug!)`):o.push(new qe.ContentList(h)),l=true;}return l||o.push(new qe.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineSequenceElement);return s===null?null:s},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=this.StatementsAtLevel(Fe.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new At.Text(`
42
- `)),new qe.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===Fe.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(s),()=>this.StatementsBreakForLevel(s))),this.StatementAtLevel=s=>{let o=this._statementRulesAtLevel[s],l=this.OneOf(o);return s===Fe.StatementLevel.Top&&l instanceof Bc.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let s=Object.values(Fe.StatementLevel);this._statementRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]);for(let o of s){let l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=Fe.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>Fe.StatementLevel.InnerBlock&&l.push(this.Gather),o>=Fe.StatementLevel.Knot&&l.push(this.StitchDefinition),l.push(this.Line(this.ListDeclaration)),l.push(this.Line(this.VariableDeclaration)),l.push(this.Line(this.ConstDeclaration)),l.push(this.Line(this.ExternalDeclaration)),l.push(this.Line(this.IncludeStatement)),l.push(this.LogicLine),l.push(this.LineOfMixedTextAndLogic),o<=Fe.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=Fe.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=Fe.StatementLevel.InnerBlock&&(u.push(this.ParseDashNotArrow),u.push(this.String("}"))),this._statementRulesAtLevel[o]=l,this._statementBreakRulesAtLevel[o]=u;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
43
- \r`),this.ParseNewline(),Dt.ParseSuccess),this.Line=s=>()=>{let o=this.ParseObject(s);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let s=null;if(this.tagActive){let o=new qe.ContentList;o.AddContent(new Fn.Tag(false)),o.AddContent(new Fn.Tag(true)),s=o;}else s=new Fn.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new pe.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Dt.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Dt.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?Dt.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Dt.ParseSuccess:null,this.Spaced=s=>()=>{this.Whitespace();let o=this.ParseObject(s);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let s=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)s=true;return s?Dt.ParseSuccess:null},this.MultiSpaced=s=>()=>{this.AnyWhitespace();let o=this.ParseObject(s);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new sy.DefaultFileHandler:this._fileHandler=a,r===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=r;}PreProcessInputString(e){return new MC.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(ea.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(ea.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(ea.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(ea.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new pe.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(e){this.tagActive&&(e!=null&&(e instanceof qe.ContentList?e.AddContent(new Fn.Tag(false)):e.push(new Fn.Tag(false))),this.tagActive=false);}};ia.InkParser=K;K.LatinBasic=it.CharacterRange.Define("A","z",new pe.CharacterSet().AddRange("[","`"));K.LatinExtendedA=it.CharacterRange.Define("\u0100","\u017F");K.LatinExtendedB=it.CharacterRange.Define("\u0180","\u024F");K.Greek=it.CharacterRange.Define("\u0370","\u03FF",new pe.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));K.Cyrillic=it.CharacterRange.Define("\u0400","\u04FF",new pe.CharacterSet().AddRange("\u0482","\u0489"));K.Armenian=it.CharacterRange.Define("\u0530","\u058F",new pe.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));K.Hebrew=it.CharacterRange.Define("\u0590","\u05FF",new pe.CharacterSet);K.Arabic=it.CharacterRange.Define("\u0600","\u06FF",new pe.CharacterSet);K.Korean=it.CharacterRange.Define("\uAC00","\uD7AF",new pe.CharacterSet);K.Latin1Supplement=it.CharacterRange.Define("\x80","\xFF",new pe.CharacterSet);K.Chinese=it.CharacterRange.Define("\u4E00","\u9FFF",new pe.CharacterSet);K.ListAllCharacterRanges=()=>[K.LatinBasic,K.LatinExtendedA,K.LatinExtendedB,K.Arabic,K.Armenian,K.Cyrillic,K.Greek,K.Hebrew,K.Korean,K.Latin1Supplement,K.Chinese];});var Gc=w(ra=>{Object.defineProperty(ra,"__esModule",{value:true});ra.GenerateStoryStats=void 0;var ay=yn(),oy=bn(),ly=ti(),uy=dl(),hy=yl(),cy=Vt();function dy(i){let e=i.FindAll(cy.Text)(),t=0;for(let l of e){let u=0,h=true;for(let c of l.text)c==" "||c==" "||c==`
44
- `||c=="\r"?h=true:h&&(u++,h=false);t+=u;}let n=i.FindAll(uy.Knot)(),r=i.FindAll(hy.Stitch)(),a=i.FindAll(ay.Choice)(),s=i.FindAll(ly.Gather)(l=>l.debugMetadata!=null),o=i.FindAll(oy.Divert)();return {words:t,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:r.length,gathers:s.length,diverts:o.length-1,choices:a.length}}ra.GenerateStoryStats=dy;});var $c=w(sa=>{Object.defineProperty(sa,"__esModule",{value:true});sa.JsonFileHandler=void 0;var Xl=class{constructor(e){this.fileHierarchy=e,this.ResolveInkFilename=t=>{if(Object.keys(this.fileHierarchy).includes(t))return t;throw new Error(`Cannot locate ${t}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=t=>{if(Object.keys(this.fileHierarchy).includes(t))return this.fileHierarchy[t];throw new Error(`Cannot open ${t}.`)};}};sa.JsonFileHandler=Xl;});var Hc=w(Ee=>{Object.defineProperty(Ee,"__esModule",{value:true});Ee.Compiler=Ee.Story=Ee.InkList=Ee.JsonFileHandler=Ee.StatementLevel=Ee.InkParser=Ee.CompilerOptions=void 0;var py=Va(),fy=eh(),Yl=ln(),gy=Kl(),my=ne(),Cy=z(),yy=Gc(),vy=Va();Object.defineProperty(Ee,"CompilerOptions",{enumerable:true,get:function(){return vy.CompilerOptions}});var Sy=Kl();Object.defineProperty(Ee,"InkParser",{enumerable:true,get:function(){return Sy.InkParser}});var Ey=ml();Object.defineProperty(Ee,"StatementLevel",{enumerable:true,get:function(){return Ey.StatementLevel}});var by=$c();Object.defineProperty(Ee,"JsonFileHandler",{enumerable:true,get:function(){return by.JsonFileHandler}});var Jc=ci();Object.defineProperty(Ee,"InkList",{enumerable:true,get:function(){return Jc.InkList}});Object.defineProperty(Ee,"Story",{enumerable:true,get:function(){return Jc.Story}});var Ql=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(e,t=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new gy.InkParser(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),this.errors.length===0?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var n;for(let r of this.runtimeStory.state.outputStream){let a=(0, Cy.asOrNull)(r,my.StringValue);if(a!==null){let s=new fy.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, yy.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let r=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),n>=r&&n<r+s.length)return a;r+=s.length;}return null},this.OnError=(n,r)=>{switch(r){case Yl.ErrorType.Author:this._authorMessages.push(n);break;case Yl.ErrorType.Warning:this._warnings.push(n);break;case Yl.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,r);},this._inputString=e,this._options=t||new py.CompilerOptions;}};Ee.Compiler=Ql;});var W;(r=>(r.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),r.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),r.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),r.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(W||={});var sd=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ad=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,od=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,la={Space_Separator:sd,ID_Start:ad,ID_Continue:od},re={isSpaceSeparator(i){return typeof i=="string"&&la.Space_Separator.test(i)},isIdStartChar(i){return typeof i=="string"&&(i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="$"||i==="_"||la.ID_Start.test(i))},isIdContinueChar(i){return typeof i=="string"&&(i>="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||i==="$"||i==="_"||i==="\u200C"||i==="\u200D"||la.ID_Continue.test(i))},isDigit(i){return typeof i=="string"&&/[0-9]/.test(i)},isHexDigit(i){return typeof i=="string"&&/[0-9A-Fa-f]/.test(i)}},ha,De,Ct,xi,wt,et,ue,pa,In,ld=function(e,t){ha=String(e),De="start",Ct=[],xi=0,wt=1,et=0,ue=void 0,pa=void 0,In=void 0;do ue=ud(),dd[De]();while(ue.type!=="eof");return typeof t=="function"?ca({"":In},"",t):In};function ca(i,e,t){let n=i[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let r=0;r<n.length;r++){let a=String(r),s=ca(n,a,t);s===void 0?delete n[a]:Object.defineProperty(n,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let r in n){let a=ca(n,r,t);a===void 0?delete n[r]:Object.defineProperty(n,r,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(i,e,n)}var I,V,Vn,mt,L;function ud(){for(I="default",V="",Vn=false,mt=1;;){L=yt();let i=ou[I]();if(i)return i}}function yt(){if(ha[xi])return String.fromCodePoint(ha.codePointAt(xi))}function D(){let i=yt();return i===`
45
- `?(wt++,et=0):i?et+=i.length:et++,i&&(xi+=i.length),i}var ou={default(){switch(L){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
46
- `:case "\r":case "\u2028":case "\u2029":D();return;case "/":D(),I="comment";return;case void 0:return D(),X("eof")}if(re.isSpaceSeparator(L)){D();return}return ou[De]()},comment(){switch(L){case "*":D(),I="multiLineComment";return;case "/":D(),I="singleLineComment";return}throw Y(D())},multiLineComment(){switch(L){case "*":D(),I="multiLineCommentAsterisk";return;case void 0:throw Y(D())}D();},multiLineCommentAsterisk(){switch(L){case "*":D();return;case "/":D(),I="default";return;case void 0:throw Y(D())}D(),I="multiLineComment";},singleLineComment(){switch(L){case `
47
- `:case "\r":case "\u2028":case "\u2029":D(),I="default";return;case void 0:return D(),X("eof")}D();},value(){switch(L){case "{":case "[":return X("punctuator",D());case "n":return D(),jt("ull"),X("null",null);case "t":return D(),jt("rue"),X("boolean",true);case "f":return D(),jt("alse"),X("boolean",false);case "-":case "+":D()==="-"&&(mt=-1),I="sign";return;case ".":V=D(),I="decimalPointLeading";return;case "0":V=D(),I="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":V=D(),I="decimalInteger";return;case "I":return D(),jt("nfinity"),X("numeric",1/0);case "N":return D(),jt("aN"),X("numeric",NaN);case '"':case "'":Vn=D()==='"',V="",I="string";return}throw Y(D())},identifierNameStartEscape(){if(L!=="u")throw Y(D());D();let i=da();switch(i){case "$":case "_":break;default:if(!re.isIdStartChar(i))throw au();break}V+=i,I="identifierName";},identifierName(){switch(L){case "$":case "_":case "\u200C":case "\u200D":V+=D();return;case "\\":D(),I="identifierNameEscape";return}if(re.isIdContinueChar(L)){V+=D();return}return X("identifier",V)},identifierNameEscape(){if(L!=="u")throw Y(D());D();let i=da();switch(i){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!re.isIdContinueChar(i))throw au();break}V+=i,I="identifierName";},sign(){switch(L){case ".":V=D(),I="decimalPointLeading";return;case "0":V=D(),I="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":V=D(),I="decimalInteger";return;case "I":return D(),jt("nfinity"),X("numeric",mt*(1/0));case "N":return D(),jt("aN"),X("numeric",NaN)}throw Y(D())},zero(){switch(L){case ".":V+=D(),I="decimalPoint";return;case "e":case "E":V+=D(),I="decimalExponent";return;case "x":case "X":V+=D(),I="hexadecimal";return}return X("numeric",mt*0)},decimalInteger(){switch(L){case ".":V+=D(),I="decimalPoint";return;case "e":case "E":V+=D(),I="decimalExponent";return}if(re.isDigit(L)){V+=D();return}return X("numeric",mt*Number(V))},decimalPointLeading(){if(re.isDigit(L)){V+=D(),I="decimalFraction";return}throw Y(D())},decimalPoint(){switch(L){case "e":case "E":V+=D(),I="decimalExponent";return}if(re.isDigit(L)){V+=D(),I="decimalFraction";return}return X("numeric",mt*Number(V))},decimalFraction(){switch(L){case "e":case "E":V+=D(),I="decimalExponent";return}if(re.isDigit(L)){V+=D();return}return X("numeric",mt*Number(V))},decimalExponent(){switch(L){case "+":case "-":V+=D(),I="decimalExponentSign";return}if(re.isDigit(L)){V+=D(),I="decimalExponentInteger";return}throw Y(D())},decimalExponentSign(){if(re.isDigit(L)){V+=D(),I="decimalExponentInteger";return}throw Y(D())},decimalExponentInteger(){if(re.isDigit(L)){V+=D();return}return X("numeric",mt*Number(V))},hexadecimal(){if(re.isHexDigit(L)){V+=D(),I="hexadecimalInteger";return}throw Y(D())},hexadecimalInteger(){if(re.isHexDigit(L)){V+=D();return}return X("numeric",mt*Number(V))},string(){switch(L){case "\\":D(),V+=hd();return;case '"':if(Vn)return D(),X("string",V);V+=D();return;case "'":if(!Vn)return D(),X("string",V);V+=D();return;case `
48
- `:case "\r":throw Y(D());case "\u2028":case "\u2029":pd(L);break;case void 0:throw Y(D())}V+=D();},start(){switch(L){case "{":case "[":return X("punctuator",D())}I="value";},beforePropertyName(){switch(L){case "$":case "_":V=D(),I="identifierName";return;case "\\":D(),I="identifierNameStartEscape";return;case "}":return X("punctuator",D());case '"':case "'":Vn=D()==='"',I="string";return}if(re.isIdStartChar(L)){V+=D(),I="identifierName";return}throw Y(D())},afterPropertyName(){if(L===":")return X("punctuator",D());throw Y(D())},beforePropertyValue(){I="value";},afterPropertyValue(){switch(L){case ",":case "}":return X("punctuator",D())}throw Y(D())},beforeArrayValue(){if(L==="]")return X("punctuator",D());I="value";},afterArrayValue(){switch(L){case ",":case "]":return X("punctuator",D())}throw Y(D())},end(){throw Y(D())}};function X(i,e){return {type:i,value:e,line:wt,column:et}}function jt(i){for(let e of i){if(yt()!==e)throw Y(D());D();}}function hd(){switch(yt()){case "b":return D(),"\b";case "f":return D(),"\f";case "n":return D(),`
49
- `;case "r":return D(),"\r";case "t":return D()," ";case "v":return D(),"\v";case "0":if(D(),re.isDigit(yt()))throw Y(D());return "\0";case "x":return D(),cd();case "u":return D(),da();case `
50
- `:case "\u2028":case "\u2029":return D(),"";case "\r":return D(),yt()===`
51
- `&&D(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw Y(D());case void 0:throw Y(D())}return D()}function cd(){let i="",e=yt();if(!re.isHexDigit(e)||(i+=D(),e=yt(),!re.isHexDigit(e)))throw Y(D());return i+=D(),String.fromCodePoint(parseInt(i,16))}function da(){let i="",e=4;for(;e-- >0;){let t=yt();if(!re.isHexDigit(t))throw Y(D());i+=D();}return String.fromCodePoint(parseInt(i,16))}var dd={start(){if(ue.type==="eof")throw qt();ua();},beforePropertyName(){switch(ue.type){case "identifier":case "string":pa=ue.value,De="afterPropertyName";return;case "punctuator":wi();return;case "eof":throw qt()}},afterPropertyName(){if(ue.type==="eof")throw qt();De="beforePropertyValue";},beforePropertyValue(){if(ue.type==="eof")throw qt();ua();},beforeArrayValue(){if(ue.type==="eof")throw qt();if(ue.type==="punctuator"&&ue.value==="]"){wi();return}ua();},afterPropertyValue(){if(ue.type==="eof")throw qt();switch(ue.value){case ",":De="beforePropertyName";return;case "}":wi();}},afterArrayValue(){if(ue.type==="eof")throw qt();switch(ue.value){case ",":De="beforeArrayValue";return;case "]":wi();}},end(){}};function ua(){let i;switch(ue.type){case "punctuator":switch(ue.value){case "{":i={};break;case "[":i=[];break}break;case "null":case "boolean":case "numeric":case "string":i=ue.value;break}if(In===void 0)In=i;else {let e=Ct[Ct.length-1];Array.isArray(e)?e.push(i):Object.defineProperty(e,pa,{value:i,writable:true,enumerable:true,configurable:true});}if(i!==null&&typeof i=="object")Ct.push(i),Array.isArray(i)?De="beforeArrayValue":De="beforePropertyName";else {let e=Ct[Ct.length-1];e==null?De="end":Array.isArray(e)?De="afterArrayValue":De="afterPropertyValue";}}function wi(){Ct.pop();let i=Ct[Ct.length-1];i==null?De="end":Array.isArray(i)?De="afterArrayValue":De="afterPropertyValue";}function Y(i){return _i(i===void 0?`JSON5: invalid end of input at ${wt}:${et}`:`JSON5: invalid character '${lu(i)}' at ${wt}:${et}`)}function qt(){return _i(`JSON5: invalid end of input at ${wt}:${et}`)}function au(){return et-=5,_i(`JSON5: invalid identifier character at ${wt}:${et}`)}function pd(i){console.warn(`JSON5: '${lu(i)}' in strings is not valid ECMAScript; consider escaping`);}function lu(i){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[i])return e[i];if(i<" "){let t=i.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return i}function _i(i){let e=new SyntaxError(i);return e.lineNumber=wt,e.columnNumber=et,e}var fd=function(e,t,n){let r=[],a="",s,o,l="",u;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,u=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let C of t){let A;typeof C=="string"?A=C:(typeof C=="number"||C instanceof String||C instanceof Number)&&(A=String(C)),A!==void 0&&s.indexOf(A)<0&&s.push(A);}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),h("",{"":e});function h(C,A){let b=A[C];switch(b!=null&&(typeof b.toJSON5=="function"?b=b.toJSON5(C):typeof b.toJSON=="function"&&(b=b.toJSON(C))),o&&(b=o.call(A,C,b)),b instanceof Number?b=Number(b):b instanceof String?b=String(b):b instanceof Boolean&&(b=b.valueOf()),b){case null:return "null";case true:return "true";case false:return "false"}if(typeof b=="string")return c(b);if(typeof b=="number")return String(b);if(typeof b=="object")return Array.isArray(b)?y(b):p(b)}function c(C){let A={"'":.1,'"':.2},b={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},m="";for(let S=0;S<C.length;S++){let g=C[S];switch(g){case "'":case '"':A[g]++,m+=g;continue;case "\0":if(re.isDigit(C[S+1])){m+="\\x00";continue}}if(b[g]){m+=b[g];continue}if(g<" "){let E=g.charCodeAt(0).toString(16);m+="\\x"+("00"+E).substring(E.length);continue}m+=g;}let d=u||Object.keys(A).reduce((S,g)=>A[S]<A[g]?S:g);return m=m.replace(new RegExp(d,"g"),b[d]),d+m+d}function p(C){if(r.indexOf(C)>=0)throw TypeError("Converting circular structure to JSON5");r.push(C);let A=a;a=a+l;let b=s||Object.keys(C),m=[];for(let S of b){let g=h(S,C);if(g!==void 0){let E=f(S)+":";l!==""&&(E+=" "),E+=g,m.push(E);}}let d;if(m.length===0)d="{}";else {let S;if(l==="")S=m.join(","),d="{"+S+"}";else {let g=`,
52
- `+a;S=m.join(g),d=`{
53
- `+a+S+`,
54
- `+A+"}";}}return r.pop(),a=A,d}function f(C){if(C.length===0)return c(C);let A=String.fromCodePoint(C.codePointAt(0));if(!re.isIdStartChar(A))return c(C);for(let b=A.length;b<C.length;b++)if(!re.isIdContinueChar(String.fromCodePoint(C.codePointAt(b))))return c(C);return C}function y(C){if(r.indexOf(C)>=0)throw TypeError("Converting circular structure to JSON5");r.push(C);let A=a;a=a+l;let b=[];for(let d=0;d<C.length;d++){let S=h(String(d),C);b.push(S!==void 0?S:"null");}let m;if(b.length===0)m="[]";else if(l==="")m="["+b.join(",")+"]";else {let d=`,
55
- `+a,S=b.join(d);m=`[
56
- `+a+S+`,
57
- `+A+"]";}return r.pop(),a=A,m}},gd={parse:ld,stringify:fd},md=gd,kn=md;var hu="\xA7SPACE\xA7",cu="\xA7DOUBLE_QUOTES\xA7",du="\xA7QUOTES\xA7",pu="SPECIAL_\xA7QUOTES\xA7",fu="\xA7CURLY_BRACKETS1\xA7",Cd="\xA7INK_VAR\xA7",gu="\xA7CURLY_BRACKETS2\xA7",O;(m=>{let i=[],e=[];async function t(d,S){for(let g=0;g<i.length;g++)try{let{validation:E}=i[g].opts;if(E instanceof RegExp){if(!E.test(d.join(" ")))continue}else if(E instanceof v.ZodType&&!E.safeParse(d).success)continue;let _=await i[g].fn(d,S,c);if(_===!0||typeof _=="string")return _}catch{}return false}function n(d,S={name:"custom-command",validation:/^/}){i.unshift({fn:d,opts:S});}m.add=n;function r(){return [...e.map(d=>d.opts),...i.map(d=>d.opts)]}m.info=r;function a(d,S){e.unshift({fn:d,opts:S});}m.addMapper=a;function s(){i.length=0;}m.clear=s;function o(){e.length=0;}m.clearMappers=o;async function l(d,S,g){try{let E=u(d),_=await t(E,g);return _===!0?void 0:typeof _=="string"?(_.startsWith("#")&&(_=_.substring(1)),await m.run(_,S,g)):h(E,S)}catch(E){throw W.error("Error parsing ink hashtag-command",d),E}}m.run=l;function u(d,S){if(d=d.replaceAll('\\"',cu),d=d.replaceAll("\\'",du),d=d.replaceAll("\\`",pu),d=d.replaceAll("\\{",fu),d=d.replaceAll("\\}",gu),S?.mergeInkVariables){let T;do T=d,d=d.replace(/\{[^{}:]*\}/g,Cd);while(d!==T)}d=d.replaceAll("{"," { "),d=d.replaceAll("}"," } "),d=d.replaceAll(fu,"{"),d=d.replaceAll(gu,"}");let g=[],E,_="";for(let T=0;T<d.length;T++){let N=d[T];N==='"'||N==="'"||N==="`"?E===void 0?(g.push(_),_="",E=N,_+=N):E===N?(E=void 0,_+=N,g.push(_),_=""):_+=N:_+=N;}return _!==""&&g.push(_),g.forEach((T,N)=>{N%2===1&&(g[N]=T.replaceAll(" ",hu));}),d=g.join(""),g=d.split(" ").filter(T=>T!==""),g=g.map(T=>T.replaceAll(hu," ").replaceAll(cu,'"').replaceAll(du,"'").replaceAll(pu,"`")),g=C(g),g=g.map(T=>T.startsWith('"')&&T.endsWith('"')||T.startsWith("'")&&T.endsWith("'")||T.startsWith("`")&&T.endsWith("`")?T.slice(1,-1):T),g}m.convertTagTolist=u;function h(d,S){for(let g of e){let{validation:E}=g.opts,_=false;if(E instanceof RegExp?_=E.test(d.join(" ")):E instanceof v.ZodType&&(_=E.safeParse(d).success),_)return g.fn(d,S)}W.error("The operation is not valid",d);}m.convertOperation=h;function c(d){return p(d)}m.convertListStringToObj=c;function p(d){if(d.length===0)return {};if(d.length%2!==0)throw W.error("The props list must have a pair number of elements",d),new Error("The props list must have a pair number of elements");let S="{";d.forEach((g,E)=>{if(E%2===0)S+=`"${g}": `;else {switch(g){case "null":case "undefined":case "true":case "false":S+=`${g}`;break;default:y(g)?(g=f(g),S+=`"${g}"`):g.startsWith("{")&&g.endsWith("}")?S+=`${g}`:g.startsWith('"')&&g.endsWith('"')?S+=`${g}`:Number.isNaN(parseFloat(g))?S+=`"${g}"`:S+=`${g}`;}E<d.length-1&&(S+=", ");}}),S+="}";try{return kn.parse(S)}catch(g){throw W.error("Error parsing ink json",S),g}}function f(d){return d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`")?d.substring(1,d.length-1):d}function y(d){return !!(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`"))}function C(d){return A(d).tokens}m.mergeJsonBlocks=C;function A(d){let S=[],g=false;for(let E=0;E<d.length;E++){let _=d[E];if(_!=="{"){S.push(_);continue}let T=b(d,E);if(T===-1){S.push(_);continue}let N=A(d.slice(E+1,T)),te=["{",...N.tokens,"}"],be=te.join(" ");if(!N.hasInvalidMatchedBlock)try{kn.parse(be),S.push(be),E=T;continue}catch{}g=true,S.push(...te),E=T;}return {tokens:S,hasInvalidMatchedBlock:g}}function b(d,S){let g=0;for(let E=S;E<d.length;E++)if(d[E]==="{")g++;else if(d[E]==="}"&&(g--,g===0))return E;return -1}})(O||={});O.addMapper((i,e)=>{e.labelToOpen={label:i[1],type:"call"},e.goNextStep=void 0;},{name:"call",description:"Calls the label specified by the second token, then returns to the current position.\n\n```ink\n# call label_name\n```",validation:v__default.default.tuple([v__default.default.literal("call"),v__default.default.string()])});O.addMapper((i,e)=>{e.labelToOpen={label:i[1],type:"jump"},e.goNextStep=void 0;},{name:"jump",description:"Jumps to the label specified by the second token without returning.\n\n```ink\n# jump label_name\n```",validation:v__default.default.tuple([v__default.default.literal("jump"),v__default.default.string()])});O.addMapper((i,e)=>("dialogue"in e&&delete e.dialogue,"goNextStep"in e&&delete e.goNextStep,{type:"dialogue",operationType:"clean"}),{name:"pause",description:"Clears the current dialogue and waits for user input before advancing.\n\n```ink\n# pause\n```",validation:v__default.default.tuple([v__default.default.literal("pause")])});O.addMapper((i,e)=>{e.goNextStep=true,e.glueEnabled=false;},{name:"continue",description:"Forces the story to proceed to the next step automatically.\n\n```ink\n# continue\n```",validation:v__default.default.tuple([v__default.default.literal("continue")])});O.addMapper(i=>({type:"video",operationType:i[0],alias:i[2]}),{name:"video-pause-resume",description:"Pauses or resumes a video canvas element identified by its alias.\n\n```ink\n# pause video <alias>\n# resume video <alias>\n```",validation:v__default.default.tuple([v__default.default.enum(["pause","resume"]),v__default.default.literal("video"),v__default.default.string()])});O.addMapper(i=>({type:i[1],operationType:i[0],aliases:i.slice(2)}),{name:"assets-bundle-load",description:`Loads (eagerly or lazily) a set of asset or bundle aliases.
40
+ ~ myFunction()`);let l=(0, wt.asOrNull)(o,Ms.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(Ms.FunctionCall)()!==null&&(o=new Pe.ContentList(o,new pt.Text(`
41
+ `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u?(u instanceof Sn.NumberExpression||u instanceof ui.StringExpression||u instanceof Pl.DivertTarget||u instanceof Nl.VariableReference||u instanceof yc.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):u instanceof ui.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new Fl.VariableAssignment({assignedExpression:u,isGlobalDeclaration:true,variableIdentifier:o})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let l=this.Expect(this.ListDefinition,"list item names");return l?(l.identifier=new hi.Identifier(o.name),new Fl.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new yC.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let u=null;if(this.ParseString("=")!==null){this.Whitespace();let h=this.Expect(this.ExpressionInt,"value to be assigned to list item");h!==null&&(u=h.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new vC.ListElementDefinition(l,s,u)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l instanceof Sn.NumberExpression||l instanceof Pl.DivertTarget||l instanceof ui.StringExpression?l instanceof ui.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new uC.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new fC.Glue(new mC.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let l=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(l===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(l);let u=(0, wt.asOrNull)(l,Pe.ContentList);return u||(u=new Pe.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new Ec.Sequence(u,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let l=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let u of l){let h=this.BeginRule(),c=this.ParseObject(u);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let s=this.Parse(this.Expression);return s&&(s.outputWhenComplete=true),s},this.IdentifierWithMetadata=()=>{let s=this.Identifier();return s===null?null:new hi.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let l of s)if(!(l>="0"&&l<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new ce.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=he.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new Ec.Sequence(l,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case he.SequenceType.Once:case he.SequenceType.Cycle:case he.SequenceType.Stopping:case he.SequenceType.Shuffle:case he.SequenceType.Shuffle|he.SequenceType.Stopping:case he.SequenceType.Shuffle|he.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),he.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new ce.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":s|=he.SequenceType.Once;break;case "&":s|=he.SequenceType.Cycle;break;case "~":s|=he.SequenceType.Shuffle;break;case "$":s|=he.SequenceType.Stopping;break}return s===0?null:s},this.SequenceTypeWordAnnotation=()=>{let s=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(s===null||s.length===0||this.ParseString(":")===null)return null;let o=0;for(let l of s)o|=l;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=he.SequenceType.Once;break;case "cycle":s=he.SequenceType.Cycle;break;case "shuffle":s=he.SequenceType.Shuffle;break;case "stopping":s=he.SequenceType.Stopping;break}return s===null?null:s},this.InnerSequenceObjects=()=>{let s=this.Parse(this.Newline)!==null,o=null;return s?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let s=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(s===null)return null;let o=[],l=false;for(let u of s)if(u==="|")l||o.push(new Pe.ContentList),l=false;else {let h=u;h===null?this.Error(`Expected content, but got ${u} (this is an ink compiler bug!)`):o.push(new Pe.ContentList(h)),l=true;}return l||o.push(new Pe.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineSequenceElement);return s===null?null:s},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=this.StatementsAtLevel(De.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new pt.Text(`
42
+ `)),new Pe.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===De.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(s),()=>this.StatementsBreakForLevel(s))),this.StatementAtLevel=s=>{let o=this._statementRulesAtLevel[s],l=this.OneOf(o);return s===De.StatementLevel.Top&&l instanceof Sc.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let s=Object.values(De.StatementLevel);this._statementRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]);for(let o of s){let l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=De.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>De.StatementLevel.InnerBlock&&l.push(this.Gather),o>=De.StatementLevel.Knot&&l.push(this.StitchDefinition),l.push(this.Line(this.ListDeclaration)),l.push(this.Line(this.VariableDeclaration)),l.push(this.Line(this.ConstDeclaration)),l.push(this.Line(this.ExternalDeclaration)),l.push(this.Line(this.IncludeStatement)),l.push(this.LogicLine),l.push(this.LineOfMixedTextAndLogic),o<=De.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=De.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=De.StatementLevel.InnerBlock&&(u.push(this.ParseDashNotArrow),u.push(this.String("}"))),this._statementRulesAtLevel[o]=l,this._statementBreakRulesAtLevel[o]=u;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
43
+ \r`),this.ParseNewline(),dt.ParseSuccess),this.Line=s=>()=>{let o=this.ParseObject(s);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let s=null;if(this.tagActive){let o=new Pe.ContentList;o.AddContent(new vn.Tag(false)),o.AddContent(new vn.Tag(true)),s=o;}else s=new vn.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new ce.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?dt.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?dt.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?dt.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?dt.ParseSuccess:null,this.Spaced=s=>()=>{this.Whitespace();let o=this.ParseObject(s);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let s=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)s=true;return s?dt.ParseSuccess:null},this.MultiSpaced=s=>()=>{this.AnyWhitespace();let o=this.ParseObject(s);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new AC.DefaultFileHandler:this._fileHandler=a,r===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=r;}PreProcessInputString(e){return new oC.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(qs.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(qs.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(qs.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(qs.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new ce.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(e){this.tagActive&&(e!=null&&(e instanceof Pe.ContentList?e.AddContent(new vn.Tag(false)):e.push(new vn.Tag(false))),this.tagActive=false);}};$s.InkParser=U;U.LatinBasic=He.CharacterRange.Define("A","z",new ce.CharacterSet().AddRange("[","`"));U.LatinExtendedA=He.CharacterRange.Define("\u0100","\u017F");U.LatinExtendedB=He.CharacterRange.Define("\u0180","\u024F");U.Greek=He.CharacterRange.Define("\u0370","\u03FF",new ce.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));U.Cyrillic=He.CharacterRange.Define("\u0400","\u04FF",new ce.CharacterSet().AddRange("\u0482","\u0489"));U.Armenian=He.CharacterRange.Define("\u0530","\u058F",new ce.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));U.Hebrew=He.CharacterRange.Define("\u0590","\u05FF",new ce.CharacterSet);U.Arabic=He.CharacterRange.Define("\u0600","\u06FF",new ce.CharacterSet);U.Korean=He.CharacterRange.Define("\uAC00","\uD7AF",new ce.CharacterSet);U.Latin1Supplement=He.CharacterRange.Define("\x80","\xFF",new ce.CharacterSet);U.Chinese=He.CharacterRange.Define("\u4E00","\u9FFF",new ce.CharacterSet);U.ListAllCharacterRanges=()=>[U.LatinBasic,U.LatinExtendedA,U.LatinExtendedB,U.Arabic,U.Armenian,U.Cyrillic,U.Greek,U.Hebrew,U.Korean,U.Latin1Supplement,U.Chinese];});var xc=x(Js=>{Object.defineProperty(Js,"__esModule",{value:true});Js.GenerateStoryStats=void 0;var xC=an(),wC=hn(),_C=Gn(),OC=Xo(),TC=nl(),PC=Et();function FC(i){let e=i.FindAll(PC.Text)(),t=0;for(let l of e){let u=0,h=true;for(let c of l.text)c==" "||c==" "||c==`
44
+ `||c=="\r"?h=true:h&&(u++,h=false);t+=u;}let n=i.FindAll(OC.Knot)(),r=i.FindAll(TC.Stitch)(),a=i.FindAll(xC.Choice)(),s=i.FindAll(_C.Gather)(l=>l.debugMetadata!=null),o=i.FindAll(wC.Divert)();return {words:t,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:r.length,gathers:s.length,diverts:o.length-1,choices:a.length}}Js.GenerateStoryStats=FC;});var wc=x(Hs=>{Object.defineProperty(Hs,"__esModule",{value:true});Hs.JsonFileHandler=void 0;var Vl=class{constructor(e){this.fileHierarchy=e,this.ResolveInkFilename=t=>{if(Object.keys(this.fileHierarchy).includes(t))return t;throw new Error(`Cannot locate ${t}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=t=>{if(Object.keys(this.fileHierarchy).includes(t))return this.fileHierarchy[t];throw new Error(`Cannot open ${t}.`)};}};Hs.JsonFileHandler=Vl;});var Oc=x(Ce=>{Object.defineProperty(Ce,"__esModule",{value:true});Ce.Compiler=Ce.Story=Ce.InkList=Ce.JsonFileHandler=Ce.StatementLevel=Ce.InkParser=Ce.CompilerOptions=void 0;var NC=Ca(),IC=Ru(),kl=Kt(),VC=Il(),kC=ee(),RC=H(),LC=xc(),BC=Ca();Object.defineProperty(Ce,"CompilerOptions",{enumerable:true,get:function(){return BC.CompilerOptions}});var WC=Il();Object.defineProperty(Ce,"InkParser",{enumerable:true,get:function(){return WC.InkParser}});var jC=el();Object.defineProperty(Ce,"StatementLevel",{enumerable:true,get:function(){return jC.StatementLevel}});var qC=wc();Object.defineProperty(Ce,"JsonFileHandler",{enumerable:true,get:function(){return qC.JsonFileHandler}});var _c=Zn();Object.defineProperty(Ce,"InkList",{enumerable:true,get:function(){return _c.InkList}});Object.defineProperty(Ce,"Story",{enumerable:true,get:function(){return _c.Story}});var Rl=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(e,t=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new VC.InkParser(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),this.errors.length===0?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var n;for(let r of this.runtimeStory.state.outputStream){let a=(0, RC.asOrNull)(r,kC.StringValue);if(a!==null){let s=new IC.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, LC.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let r=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),n>=r&&n<r+s.length)return a;r+=s.length;}return null},this.OnError=(n,r)=>{switch(r){case kl.ErrorType.Author:this._authorMessages.push(n);break;case kl.ErrorType.Warning:this._warnings.push(n);break;case kl.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,r);},this._inputString=e,this._options=t||new NC.CompilerOptions;}};Ce.Compiler=Rl;});var W;(r=>(r.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),r.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),r.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),r.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(W||={});var qc=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Mc=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,Gc=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,Ks={Space_Separator:qc,ID_Start:Mc,ID_Continue:Gc},ne={isSpaceSeparator(i){return typeof i=="string"&&Ks.Space_Separator.test(i)},isIdStartChar(i){return typeof i=="string"&&(i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="$"||i==="_"||Ks.ID_Start.test(i))},isIdContinueChar(i){return typeof i=="string"&&(i>="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||i==="$"||i==="_"||i==="\u200C"||i==="\u200D"||Ks.ID_Continue.test(i))},isDigit(i){return typeof i=="string"&&/[0-9]/.test(i)},isHexDigit(i){return typeof i=="string"&&/[0-9A-Fa-f]/.test(i)}},Ys,ve,at,fi,ft,Ge,oe,ea,Dn,$c=function(e,t){Ys=String(e),ve="start",at=[],fi=0,ft=1,Ge=0,oe=void 0,ea=void 0,Dn=void 0;do oe=Jc(),Uc[ve]();while(oe.type!=="eof");return typeof t=="function"?Qs({"":Dn},"",t):Dn};function Qs(i,e,t){let n=i[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let r=0;r<n.length;r++){let a=String(r),s=Qs(n,a,t);s===void 0?delete n[a]:Object.defineProperty(n,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let r in n){let a=Qs(n,r,t);a===void 0?delete n[r]:Object.defineProperty(n,r,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(i,e,n)}var V,I,En,st,L;function Jc(){for(V="default",I="",En=false,st=1;;){L=ot();let i=Jl[V]();if(i)return i}}function ot(){if(Ys[fi])return String.fromCodePoint(Ys.codePointAt(fi))}function b(){let i=ot();return i===`
45
+ `?(ft++,Ge=0):i?Ge+=i.length:Ge++,i&&(fi+=i.length),i}var Jl={default(){switch(L){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
46
+ `:case "\r":case "\u2028":case "\u2029":b();return;case "/":b(),V="comment";return;case void 0:return b(),K("eof")}if(ne.isSpaceSeparator(L)){b();return}return Jl[ve]()},comment(){switch(L){case "*":b(),V="multiLineComment";return;case "/":b(),V="singleLineComment";return}throw X(b())},multiLineComment(){switch(L){case "*":b(),V="multiLineCommentAsterisk";return;case void 0:throw X(b())}b();},multiLineCommentAsterisk(){switch(L){case "*":b();return;case "/":b(),V="default";return;case void 0:throw X(b())}b(),V="multiLineComment";},singleLineComment(){switch(L){case `
47
+ `:case "\r":case "\u2028":case "\u2029":b(),V="default";return;case void 0:return b(),K("eof")}b();},value(){switch(L){case "{":case "[":return K("punctuator",b());case "n":return b(),Ot("ull"),K("null",null);case "t":return b(),Ot("rue"),K("boolean",true);case "f":return b(),Ot("alse"),K("boolean",false);case "-":case "+":b()==="-"&&(st=-1),V="sign";return;case ".":I=b(),V="decimalPointLeading";return;case "0":I=b(),V="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=b(),V="decimalInteger";return;case "I":return b(),Ot("nfinity"),K("numeric",1/0);case "N":return b(),Ot("aN"),K("numeric",NaN);case '"':case "'":En=b()==='"',I="",V="string";return}throw X(b())},identifierNameStartEscape(){if(L!=="u")throw X(b());b();let i=Zs();switch(i){case "$":case "_":break;default:if(!ne.isIdStartChar(i))throw $l();break}I+=i,V="identifierName";},identifierName(){switch(L){case "$":case "_":case "\u200C":case "\u200D":I+=b();return;case "\\":b(),V="identifierNameEscape";return}if(ne.isIdContinueChar(L)){I+=b();return}return K("identifier",I)},identifierNameEscape(){if(L!=="u")throw X(b());b();let i=Zs();switch(i){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!ne.isIdContinueChar(i))throw $l();break}I+=i,V="identifierName";},sign(){switch(L){case ".":I=b(),V="decimalPointLeading";return;case "0":I=b(),V="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=b(),V="decimalInteger";return;case "I":return b(),Ot("nfinity"),K("numeric",st*(1/0));case "N":return b(),Ot("aN"),K("numeric",NaN)}throw X(b())},zero(){switch(L){case ".":I+=b(),V="decimalPoint";return;case "e":case "E":I+=b(),V="decimalExponent";return;case "x":case "X":I+=b(),V="hexadecimal";return}return K("numeric",st*0)},decimalInteger(){switch(L){case ".":I+=b(),V="decimalPoint";return;case "e":case "E":I+=b(),V="decimalExponent";return}if(ne.isDigit(L)){I+=b();return}return K("numeric",st*Number(I))},decimalPointLeading(){if(ne.isDigit(L)){I+=b(),V="decimalFraction";return}throw X(b())},decimalPoint(){switch(L){case "e":case "E":I+=b(),V="decimalExponent";return}if(ne.isDigit(L)){I+=b(),V="decimalFraction";return}return K("numeric",st*Number(I))},decimalFraction(){switch(L){case "e":case "E":I+=b(),V="decimalExponent";return}if(ne.isDigit(L)){I+=b();return}return K("numeric",st*Number(I))},decimalExponent(){switch(L){case "+":case "-":I+=b(),V="decimalExponentSign";return}if(ne.isDigit(L)){I+=b(),V="decimalExponentInteger";return}throw X(b())},decimalExponentSign(){if(ne.isDigit(L)){I+=b(),V="decimalExponentInteger";return}throw X(b())},decimalExponentInteger(){if(ne.isDigit(L)){I+=b();return}return K("numeric",st*Number(I))},hexadecimal(){if(ne.isHexDigit(L)){I+=b(),V="hexadecimalInteger";return}throw X(b())},hexadecimalInteger(){if(ne.isHexDigit(L)){I+=b();return}return K("numeric",st*Number(I))},string(){switch(L){case "\\":b(),I+=Hc();return;case '"':if(En)return b(),K("string",I);I+=b();return;case "'":if(!En)return b(),K("string",I);I+=b();return;case `
48
+ `:case "\r":throw X(b());case "\u2028":case "\u2029":Kc(L);break;case void 0:throw X(b())}I+=b();},start(){switch(L){case "{":case "[":return K("punctuator",b())}V="value";},beforePropertyName(){switch(L){case "$":case "_":I=b(),V="identifierName";return;case "\\":b(),V="identifierNameStartEscape";return;case "}":return K("punctuator",b());case '"':case "'":En=b()==='"',V="string";return}if(ne.isIdStartChar(L)){I+=b(),V="identifierName";return}throw X(b())},afterPropertyName(){if(L===":")return K("punctuator",b());throw X(b())},beforePropertyValue(){V="value";},afterPropertyValue(){switch(L){case ",":case "}":return K("punctuator",b())}throw X(b())},beforeArrayValue(){if(L==="]")return K("punctuator",b());V="value";},afterArrayValue(){switch(L){case ",":case "]":return K("punctuator",b())}throw X(b())},end(){throw X(b())}};function K(i,e){return {type:i,value:e,line:ft,column:Ge}}function Ot(i){for(let e of i){if(ot()!==e)throw X(b());b();}}function Hc(){switch(ot()){case "b":return b(),"\b";case "f":return b(),"\f";case "n":return b(),`
49
+ `;case "r":return b(),"\r";case "t":return b()," ";case "v":return b(),"\v";case "0":if(b(),ne.isDigit(ot()))throw X(b());return "\0";case "x":return b(),zc();case "u":return b(),Zs();case `
50
+ `:case "\u2028":case "\u2029":return b(),"";case "\r":return b(),ot()===`
51
+ `&&b(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw X(b());case void 0:throw X(b())}return b()}function zc(){let i="",e=ot();if(!ne.isHexDigit(e)||(i+=b(),e=ot(),!ne.isHexDigit(e)))throw X(b());return i+=b(),String.fromCodePoint(parseInt(i,16))}function Zs(){let i="",e=4;for(;e-- >0;){let t=ot();if(!ne.isHexDigit(t))throw X(b());i+=b();}return String.fromCodePoint(parseInt(i,16))}var Uc={start(){if(oe.type==="eof")throw Tt();Xs();},beforePropertyName(){switch(oe.type){case "identifier":case "string":ea=oe.value,ve="afterPropertyName";return;case "punctuator":pi();return;case "eof":throw Tt()}},afterPropertyName(){if(oe.type==="eof")throw Tt();ve="beforePropertyValue";},beforePropertyValue(){if(oe.type==="eof")throw Tt();Xs();},beforeArrayValue(){if(oe.type==="eof")throw Tt();if(oe.type==="punctuator"&&oe.value==="]"){pi();return}Xs();},afterPropertyValue(){if(oe.type==="eof")throw Tt();switch(oe.value){case ",":ve="beforePropertyName";return;case "}":pi();}},afterArrayValue(){if(oe.type==="eof")throw Tt();switch(oe.value){case ",":ve="beforeArrayValue";return;case "]":pi();}},end(){}};function Xs(){let i;switch(oe.type){case "punctuator":switch(oe.value){case "{":i={};break;case "[":i=[];break}break;case "null":case "boolean":case "numeric":case "string":i=oe.value;break}if(Dn===void 0)Dn=i;else {let e=at[at.length-1];Array.isArray(e)?e.push(i):Object.defineProperty(e,ea,{value:i,writable:true,enumerable:true,configurable:true});}if(i!==null&&typeof i=="object")at.push(i),Array.isArray(i)?ve="beforeArrayValue":ve="beforePropertyName";else {let e=at[at.length-1];e==null?ve="end":Array.isArray(e)?ve="afterArrayValue":ve="afterPropertyValue";}}function pi(){at.pop();let i=at[at.length-1];i==null?ve="end":Array.isArray(i)?ve="afterArrayValue":ve="afterPropertyValue";}function X(i){return mi(i===void 0?`JSON5: invalid end of input at ${ft}:${Ge}`:`JSON5: invalid character '${Hl(i)}' at ${ft}:${Ge}`)}function Tt(){return mi(`JSON5: invalid end of input at ${ft}:${Ge}`)}function $l(){return Ge-=5,mi(`JSON5: invalid identifier character at ${ft}:${Ge}`)}function Kc(i){console.warn(`JSON5: '${Hl(i)}' in strings is not valid ECMAScript; consider escaping`);}function Hl(i){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[i])return e[i];if(i<" "){let t=i.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return i}function mi(i){let e=new SyntaxError(i);return e.lineNumber=ft,e.columnNumber=Ge,e}var Xc=function(e,t,n){let r=[],a="",s,o,l="",u;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,u=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let g of t){let A;typeof g=="string"?A=g:(typeof g=="number"||g instanceof String||g instanceof Number)&&(A=String(g)),A!==void 0&&s.indexOf(A)<0&&s.push(A);}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),h("",{"":e});function h(g,A){let D=A[g];switch(D!=null&&(typeof D.toJSON5=="function"?D=D.toJSON5(g):typeof D.toJSON=="function"&&(D=D.toJSON(g))),o&&(D=o.call(A,g,D)),D instanceof Number?D=Number(D):D instanceof String?D=String(D):D instanceof Boolean&&(D=D.valueOf()),D){case null:return "null";case true:return "true";case false:return "false"}if(typeof D=="string")return c(D);if(typeof D=="number")return String(D);if(typeof D=="object")return Array.isArray(D)?v(D):p(D)}function c(g){let A={"'":.1,'"':.2},D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},C="";for(let E=0;E<g.length;E++){let m=g[E];switch(m){case "'":case '"':A[m]++,C+=m;continue;case "\0":if(ne.isDigit(g[E+1])){C+="\\x00";continue}}if(D[m]){C+=D[m];continue}if(m<" "){let S=m.charCodeAt(0).toString(16);C+="\\x"+("00"+S).substring(S.length);continue}C+=m;}let d=u||Object.keys(A).reduce((E,m)=>A[E]<A[m]?E:m);return C=C.replace(new RegExp(d,"g"),D[d]),d+C+d}function p(g){if(r.indexOf(g)>=0)throw TypeError("Converting circular structure to JSON5");r.push(g);let A=a;a=a+l;let D=s||Object.keys(g),C=[];for(let E of D){let m=h(E,g);if(m!==void 0){let S=f(E)+":";l!==""&&(S+=" "),S+=m,C.push(S);}}let d;if(C.length===0)d="{}";else {let E;if(l==="")E=C.join(","),d="{"+E+"}";else {let m=`,
52
+ `+a;E=C.join(m),d=`{
53
+ `+a+E+`,
54
+ `+A+"}";}}return r.pop(),a=A,d}function f(g){if(g.length===0)return c(g);let A=String.fromCodePoint(g.codePointAt(0));if(!ne.isIdStartChar(A))return c(g);for(let D=A.length;D<g.length;D++)if(!ne.isIdContinueChar(String.fromCodePoint(g.codePointAt(D))))return c(g);return g}function v(g){if(r.indexOf(g)>=0)throw TypeError("Converting circular structure to JSON5");r.push(g);let A=a;a=a+l;let D=[];for(let d=0;d<g.length;d++){let E=h(String(d),g);D.push(E!==void 0?E:"null");}let C;if(D.length===0)C="[]";else if(l==="")C="["+D.join(",")+"]";else {let d=`,
55
+ `+a,E=D.join(d);C=`[
56
+ `+a+E+`,
57
+ `+A+"]";}return r.pop(),a=A,C}},Yc={parse:$c,stringify:Xc},Qc=Yc,bn=Qc;var Ul="\xA7SPACE\xA7",Kl="\xA7DOUBLE_QUOTES\xA7",Xl="\xA7QUOTES\xA7",Yl="SPECIAL_\xA7QUOTES\xA7",Ql="\xA7CURLY_BRACKETS1\xA7",Zc="\xA7INK_VAR\xA7",Zl="\xA7CURLY_BRACKETS2\xA7",O;(C=>{let i=[],e=[];async function t(d,E){for(let m=0;m<i.length;m++)try{let{validation:S}=i[m].opts;if(S instanceof RegExp){if(!S.test(d.join(" ")))continue}else if(S instanceof y.ZodType&&!S.safeParse(d).success)continue;let w=await i[m].fn(d,E,c);if(w===!0||typeof w=="string")return w}catch{}return false}function n(d,E={name:"custom-command",validation:/^/}){i.unshift({fn:d,opts:E});}C.add=n;function r(){return [...e.map(d=>d.opts),...i.map(d=>d.opts)]}C.info=r;function a(d,E){e.unshift({fn:d,opts:E});}C.addMapper=a;function s(){i.length=0;}C.clear=s;function o(){e.length=0;}C.clearMappers=o;async function l(d,E,m){try{let S=u(d),w=await t(S,m);return w===!0?void 0:typeof w=="string"?(w.startsWith("#")&&(w=w.substring(1)),await C.run(w,E,m)):h(S,E)}catch(S){throw W.error("Error parsing ink hashtag-command",d),S}}C.run=l;function u(d,E){if(d=d.replaceAll('\\"',Kl),d=d.replaceAll("\\'",Xl),d=d.replaceAll("\\`",Yl),d=d.replaceAll("\\{",Ql),d=d.replaceAll("\\}",Zl),E?.mergeInkVariables){let P;do P=d,d=d.replace(/\{[^{}:]*\}/g,Zc);while(d!==P)}d=d.replaceAll("{"," { "),d=d.replaceAll("}"," } "),d=d.replaceAll(Ql,"{"),d=d.replaceAll(Zl,"}");let m=[],S,w="";for(let P=0;P<d.length;P++){let N=d[P];N==='"'||N==="'"||N==="`"?S===void 0?(m.push(w),w="",S=N,w+=N):S===N?(S=void 0,w+=N,m.push(w),w=""):w+=N:w+=N;}return w!==""&&m.push(w),m.forEach((P,N)=>{N%2===1&&(m[N]=P.replaceAll(" ",Ul));}),d=m.join(""),m=d.split(" ").filter(P=>P!==""),m=m.map(P=>P.replaceAll(Ul," ").replaceAll(Kl,'"').replaceAll(Xl,"'").replaceAll(Yl,"`")),m=g(m),m=m.map(P=>P.startsWith('"')&&P.endsWith('"')||P.startsWith("'")&&P.endsWith("'")||P.startsWith("`")&&P.endsWith("`")?P.slice(1,-1):P),m}C.convertTagTolist=u;function h(d,E){for(let m of e){let{validation:S}=m.opts,w=false;if(S instanceof RegExp?w=S.test(d.join(" ")):S instanceof y.ZodType&&(w=S.safeParse(d).success),w)return m.fn(d,E)}W.error("The operation is not valid",d);}C.convertOperation=h;function c(d){return p(d)}C.convertListStringToObj=c;function p(d){if(d.length===0)return {};if(d.length%2!==0)throw W.error("The props list must have a pair number of elements",d),new Error("The props list must have a pair number of elements");let E="{";d.forEach((m,S)=>{if(S%2===0)E+=`"${m}": `;else {switch(m){case "null":case "undefined":case "true":case "false":E+=`${m}`;break;default:v(m)?(m=f(m),E+=`"${m}"`):m.startsWith("{")&&m.endsWith("}")?E+=`${m}`:m.startsWith('"')&&m.endsWith('"')?E+=`${m}`:Number.isNaN(parseFloat(m))?E+=`"${m}"`:E+=`${m}`;}S<d.length-1&&(E+=", ");}}),E+="}";try{return bn.parse(E)}catch(m){throw W.error("Error parsing ink json",E),m}}function f(d){return d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`")?d.substring(1,d.length-1):d}function v(d){return !!(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`"))}function g(d){return A(d).tokens}C.mergeJsonBlocks=g;function A(d){let E=[],m=false;for(let S=0;S<d.length;S++){let w=d[S];if(w!=="{"){E.push(w);continue}let P=D(d,S);if(P===-1){E.push(w);continue}let N=A(d.slice(S+1,P)),Z=["{",...N.tokens,"}"],ye=Z.join(" ");if(!N.hasInvalidMatchedBlock)try{bn.parse(ye),E.push(ye),S=P;continue}catch{}m=true,E.push(...Z),S=P;}return {tokens:E,hasInvalidMatchedBlock:m}}function D(d,E){let m=0;for(let S=E;S<d.length;S++)if(d[S]==="{")m++;else if(d[S]==="}"&&(m--,m===0))return S;return -1}})(O||={});O.addMapper((i,e)=>{e.labelToOpen={label:i[1],type:"call"},e.goNextStep=void 0;},{name:"Call",description:"Calls the label specified by the second token, then returns to the current position.\n\n```ink\n# call label_name\n```",validation:y__default.default.tuple([y__default.default.literal("call"),y__default.default.string()])});O.addMapper((i,e)=>{e.labelToOpen={label:i[1],type:"jump"},e.goNextStep=void 0;},{name:"Jump",description:"Jumps to the label specified by the second token without returning.\n\n```ink\n# jump label_name\n```",validation:y__default.default.tuple([y__default.default.literal("jump"),y__default.default.string()])});O.addMapper((i,e)=>("dialogue"in e&&delete e.dialogue,"goNextStep"in e&&delete e.goNextStep,{type:"dialogue",operationType:"clean"}),{name:"Pause",description:"Clears the current dialogue and waits for user input before advancing.\n\n```ink\n# pause\n```",validation:y__default.default.tuple([y__default.default.literal("pause")])});O.addMapper((i,e)=>{e.goNextStep=true,e.glueEnabled=false;},{name:"Continue",description:"Forces the story to proceed to the next step automatically.\n\n```ink\n# continue\n```",validation:y__default.default.tuple([y__default.default.literal("continue")])});O.addMapper(i=>({type:"video",operationType:i[0],alias:i[2]}),{name:"Pause/Resume video",description:"Pauses or resumes a video canvas element identified by its alias.\n\n```ink\n# pause video <alias>\n# resume video <alias>\n```",validation:y__default.default.tuple([y__default.default.enum(["pause","resume"]),y__default.default.literal("video"),y__default.default.string()])});O.addMapper(i=>({type:i[1],operationType:i[0],aliases:i.slice(2)}),{name:"Load assets/bundle",description:`Loads (eagerly or lazily) a set of asset or bundle aliases.
58
58
 
59
59
  \`\`\`ink
60
60
  # load assets <alias...>
61
61
  # lazyload assets <alias...>
62
62
  # load bundle <alias...>
63
63
  # lazyload bundle <alias...>
64
- \`\`\``,validation:v__default.default.tuple([v__default.default.enum(["load","lazyload"]),v__default.default.enum(["assets","bundle"])]).rest(v__default.default.string())});O.addMapper(i=>({type:"all",operationType:i[0]}),{name:"all-sounds-pause-resume-stop",description:"Pauses, resumes, or stops all active sounds at once.\n\n```ink\n# pause all sounds\n# resume all sounds\n# stop all sounds\n```",validation:v__default.default.tuple([v__default.default.enum(["pause","resume","stop"]),v__default.default.literal("all"),v__default.default.enum(["sounds","sound"])])});O.addMapper(i=>({type:"sound",operationType:"pause",alias:i[2]}),{name:"pause-sound",description:"Pauses the sound identified by its alias.\n\n```ink\n# pause sound <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("pause"),v__default.default.literal("sound"),v__default.default.string()])});O.addMapper(i=>({type:"channel",operationType:"pause",alias:i[2]}),{name:"pause-channel",description:"Pauses the audio channel identified by its alias.\n\n```ink\n# pause channel <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("pause"),v__default.default.literal("channel"),v__default.default.string()])});O.addMapper(i=>({type:"sound",operationType:"resume",alias:i[2]}),{name:"resume-sound",description:"Resumes the sound identified by its alias.\n\n```ink\n# resume sound <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("resume"),v__default.default.literal("sound"),v__default.default.string()])});O.addMapper(i=>({type:"channel",operationType:"resume",alias:i[2]}),{name:"resume-channel",description:"Resumes the audio channel identified by its alias.\n\n```ink\n# resume channel <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("resume"),v__default.default.literal("channel"),v__default.default.string()])});O.addMapper(i=>({type:"sound",operationType:"stop",alias:i[2]}),{name:"stop-sound",description:"Stops the sound identified by its alias.\n\n```ink\n# stop sound <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("stop"),v__default.default.literal("sound"),v__default.default.string()])});O.addMapper(i=>({type:"sound",operationType:"stop",alias:i[2]}),{name:"remove-sound",description:"Removes (stops) the sound identified by its alias.\n\n```ink\n# remove sound <alias>\n```",deprecated:true,validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("sound"),v__default.default.string()])});O.addMapper(i=>({type:"sound",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"edit-sound",description:"Edits the properties of a sound identified by its alias.\n\n```ink\n# edit sound <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("sound"),v__default.default.string()]).rest(v__default.default.string()).refine(i=>(i.length-3)%2===0)});O.addMapper(i=>{let e=i[2],t={type:"sound",operationType:"play",alias:e,url:e};return i.length>3&&(t.props=O.convertListStringToObj(i.slice(3))),t},{name:"play-sound",description:"Plays a sound using its alias as the URL, with optional key/value properties.\n\n```ink\n# play sound <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("play"),v__default.default.literal("sound"),v__default.default.string()]).rest(v__default.default.string()).refine(i=>(i.length-3)%2===0)});O.addMapper(i=>{let e=i[2],t=i[3],n={type:"sound",operationType:"play",alias:e,url:t};return i.length>4&&(n.props=O.convertListStringToObj(i.slice(4))),n},{name:"play-sound-with-source",description:"Plays a sound with an explicit source URL and optional key/value properties.\n \n```ink\n# play sound <alias> <source> [<key> <value> \u2026]\n```\n",validation:v__default.default.tuple([v__default.default.literal("play"),v__default.default.literal("sound"),v__default.default.string()]).rest(v__default.default.string()).refine(i=>i.length>3&&(i.length-3)%2!==0)});function rt(i){let e=[],t=0,n="";for(let r of i)r.startsWith("{")?(t++,n+=r):r.endsWith("}")&&t>0?(t--,n+=r,t===0&&(e.push(n),n="")):t>0?n+=r:e.push(r);return e}function Oi(i,e){switch(i){case "dissolve":case "fade":case "movein":case "moveout":case "zoomin":case "zoomout":case "pushin":case "pushout":break;default:return}let t={type:i};if(e.length>0)try{t.props=O.convertListStringToObj(e);}catch{}return t}function mu(i,e,t){let n,r;t.length%2===0?(n=e,r=t):(n=t[0],r=t.slice(1));let a={type:i,operationType:"show",alias:e,url:n};if(r.length>0){if(r.includes("with")&&r.length>r.indexOf("with")+1){let s=r[r.indexOf("with")+1],o=r.slice(r.indexOf("with")+2);r=r.slice(0,r.indexOf("with"));let l=Oi(s,o);l!==void 0&&(a.transition=l);}r.length>0&&(a.props=O.convertListStringToObj(r));}return a}function yd(i,e){let t,n;e.length%2===0?(t=i,n=e):(t=e[0],n=e.slice(1));let r={type:"text",operationType:"show",alias:i,text:t};if(n.length>0){if(n.includes("with")&&n.length>n.indexOf("with")+1){let a=n[n.indexOf("with")+1],s=n.slice(n.indexOf("with")+2);n=n.slice(0,n.indexOf("with"));let o=Oi(a,s);o!==void 0&&(r.transition=o);}n.length>0&&(r.props=O.convertListStringToObj(n));}return r}function Rn(i,e,t){let n={type:i,operationType:"remove",alias:e};if(t.includes("with")&&t.length>t.indexOf("with")+1){let r=t[t.indexOf("with")+1],a=t.slice(t.indexOf("with")+2),s=Oi(r,a);s!==void 0&&(n.transition=s);}return n}function fa(i,e){let t=l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'")||l.startsWith("`")&&l.endsWith("`")?l.substring(1,l.length-1):l,n=[],r=e.findIndex(l=>l.startsWith("[")),a=e.findIndex(l=>l.endsWith("]"));if(r===-1||a===-1){W.error("Show imagecontainer must have a list of image ulrs",e);return}if(n=e.slice(r,a+1),n.length<2){W.error("Show imagecontainer must have a list of image ulrs",e);return}n[0]==="["?n.shift():n[0]=n[0].substring(1),n[n.length-1]==="]"?n.pop():n[n.length-1]=n[n.length-1].substring(0,n[n.length-1].length-1);let s={type:"imagecontainer",operationType:"show",alias:i,urls:n.map(l=>t(l))},o=e.slice(a+1);if(o.length>0){if(o.includes("with")&&o.length>o.indexOf("with")+1){let l=o[o.indexOf("with")+1],u=o.slice(o.indexOf("with")+2);o=o.slice(0,o.indexOf("with"));let h=Oi(l,u);h!==void 0&&(s.transition=h);}o.length>0&&(s.props=O.convertListStringToObj(o));}return s}function ga(i){let e=i.slice(3),t=e.findIndex(s=>s.startsWith("[")),n=e.findIndex(s=>s.endsWith("]"));if(t===-1||n===-1||n<t)return;let r=e.slice(n+1),a=r.indexOf("with");return a===-1?{beforeWith:r,afterWith:[]}:{beforeWith:r.slice(0,a),afterWith:r.slice(a+1)}}O.addMapper(i=>({alias:i[1],type:"shake",props:O.convertListStringToObj(i.slice(2))}),{name:"shake-effect",description:"Applies shake effect to a canvas alias with optional key/value parameters.\n\n```ink\n# shake <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("shake"),v__default.default.string()]).rest(v__default.default.string()).refine(i=>(i.length-2)%2===0)});O.addMapper(i=>{let e=i.slice(2),t=e,n=[];if(e.includes("options")){let a=e.indexOf("options");t=e.slice(0,a),n=e.slice(a+1);}return {alias:i[1],type:"animate",keyframes:O.convertListStringToObj(t),options:O.convertListStringToObj(n)}},{name:"animate-effect",description:"Animates a canvas alias with keyframes and optional options section, both in key/value pairs.\n\n```ink\n# animate <alias> [<key> <value> \u2026] [options <key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("animate"),v__default.default.string()]).rest(v__default.default.string()).refine(i=>{let e=i.slice(2),t=e.indexOf("options");if(t===-1)return e.length%2===0;if(e.lastIndexOf("options")!==t)return false;let n=e.slice(0,t),r=e.slice(t+1);return n.length%2===0&&r.length%2===0})});O.addMapper(i=>{let e=i[2],t=rt(i.slice(3));return mu("image",e,t)},{name:"show-image",description:"Shows an image canvas element with optional source, properties, and transition.\n\n```ink\n# show image <alias> [<source>] [<key> <value> \u2026] [with <transition> [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("image"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>fa(i[2],rt(i.slice(3))),{name:"show-imagecontainer",description:"Shows an image-container canvas element with list and optional key/value properties.\n\n```ink\n# show imagecontainer <alias> [<list>] [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string()).refine(i=>{let e=ga(i);return e===void 0?false:e.afterWith.length===0&&e.beforeWith.length%2===0})});O.addMapper(i=>fa(i[2],rt(i.slice(3))),{name:"show-imagecontainer-with-transition",description:"Shows an image-container canvas element with list, optional properties, and transition.\n\n```ink\n# show imagecontainer <alias> [<list>] [<key> <value> \u2026] with <transition>\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string()).refine(i=>{let e=ga(i);return e===void 0?false:e.afterWith.length===1&&e.beforeWith.length%2===0})});O.addMapper(i=>fa(i[2],rt(i.slice(3))),{name:"show-imagecontainer-with-transition-props",description:"Shows an image-container canvas element with list, optional properties, transition, and transition properties.\n\n```ink\n# show imagecontainer <alias> [<list>] [<key> <value> \u2026] with <transition> <key> <value> \u2026\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string()).refine(i=>{let e=ga(i);return e===void 0?false:e.afterWith.length>1&&(e.afterWith.length-1)%2===0&&e.beforeWith.length%2===0})});O.addMapper(i=>{let e=i[2],t=rt(i.slice(3));return mu("video",e,t)},{name:"show-video",description:"Shows a video canvas element with optional source, properties, and transition.\n\n```ink\n# show video <alias> [<source>] [<key> <value> \u2026] [with <transition> [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("video"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>{let e=i[2];return yd(e,i.slice(3))},{name:"show-text",description:"Shows a text canvas element with optional text, properties, and transition.\n\n```ink\n# show text <alias> [<text>] [<key> <value> \u2026] [with <transition> [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("text"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>{let e=i[2],t=rt(i.slice(3));return Rn("image",e,t)},{name:"remove-image",description:"Removes an image canvas element with optional source/properties and transition.\n\n```ink\n# remove image <alias> [<source>] [<key> <value> \u2026] [with <transition> [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("image"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>{let e=i[2],t=rt(i.slice(3));return Rn("video",e,t)},{name:"remove-video",description:"Removes a video canvas element with optional source/properties and transition.\n\n```ink\n# remove video <alias> [<source>] [<key> <value> \u2026] [with <transition> [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("video"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>{let e=i[2],t=rt(i.slice(3));return Rn("canvaselement",e,t)},{name:"remove-canvaselement",description:"Removes a canvas element with optional properties and optional transition params.\n\n```ink\n# remove canvaselement <alias> [<key> <value> \u2026] [with <transition> [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("canvaselement"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>{let e=i[2],t=rt(i.slice(3));return Rn("text",e,t)},{name:"remove-text",description:"Removes a text canvas element with optional properties and transition.\n\n```ink\n# remove text <alias> [<key> <value> \u2026] [with <transition> [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("text"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>{let e=i[2],t=rt(i.slice(3));return Rn("imagecontainer",e,t)},{name:"remove-imagecontainer",description:"Removes an image-container canvas element with optional properties and transition.\n\n```ink\n# remove imagecontainer <alias> [<key> <value> \u2026] [with <transition> [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>({type:"image",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"edit-image",description:"Edits the properties of an image canvas element identified by its alias.\n\n```ink\n# edit image <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("image"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>({type:"imagecontainer",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"edit-imagecontainer",description:"Edits the properties of an image-container canvas element identified by its alias.\n\n```ink\n# edit imagecontainer <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>({type:"canvaselement",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"edit-canvaselement",description:"Edits the properties of a canvas element identified by its alias.\n\n```ink\n# edit canvaselement <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("canvaselement"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>({type:"video",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"edit-video",description:"Edits the properties of a video canvas element identified by its alias.\n\n```ink\n# edit video <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("video"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>({type:"text",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"edit-text",description:"Edits the properties of a text canvas element identified by its alias.\n\n```ink\n# edit text <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("text"),v__default.default.string()]).rest(v__default.default.string())});O.addMapper(i=>({type:"input",operationType:"request"}),{name:"request-input",description:"Requests player input without any additional constraints.\n\n```ink\n# request input\n```",validation:v__default.default.tuple([v__default.default.literal("request"),v__default.default.literal("input")])});O.addMapper(i=>{let e={type:"input",operationType:"request"};try{let t=O.convertListStringToObj(i.slice(2));"type"in t&&typeof t.type=="string"&&(e.valueType=t.type),"default"in t&&(e.defaultValue=t.default);}catch{}return e},{name:"request-input-params",description:"Requests player input with optional key/value parameters (e.g. type, default).\n\n```ink\n# request input <key> <value> [<key> <value> \u2026]\n# request input type number default 18\n```",validation:v__default.default.tuple([v__default.default.literal("request"),v__default.default.literal("input")]).rest(v__default.default.string()).refine(i=>i.length>2&&(i.length-2)%2===0)});var vd=Object.defineProperty,Sd=(i,e,t)=>e in i?vd(i,e,{enumerable:true,configurable:true,writable:true,value:t}):i[e]=t,Ne=(i,e,t)=>Sd(i,typeof e!="symbol"?e+"":e,t),we;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(we||(we={}));var Ae=class M{static init(e){e.loadAssets&&(M._loadAssets=e.loadAssets),e.soundOperation&&(M._soundOperation=e.soundOperation),e.imageOperation&&(M._imageOperation=e.imageOperation),e.videoOperation&&(M._videoOperation=e.videoOperation),e.imageContainerOperation&&(M._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(M._textOperation=e.textOperation),e.canvasElementOperation&&(M._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(M._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(M._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(M._narrationOperation=e.narrationOperation),e.effectOperation&&(M._effectOperation=e.effectOperation),e.animateOperation&&(M._animateOperation=e.animateOperation),e.getLogichValue&&(M._getLogichValue=e.getLogichValue),e.getConditionalStep&&(M._getConditionalStep=e.getConditionalStep);}static get loadAssets(){return M._loadAssets}static get soundOperation(){return M._soundOperation}static get imageOperation(){return M._imageOperation}static get videoOperation(){return M._videoOperation}static get imageContainerOperation(){return M._imageContainerOperation}static get textOperation(){return M._textOperation}static get canvasElementOperation(){return M._canvasElementOperation}static get setStorageValue(){return M._setStorageValue}static get setInitialStorageValue(){return M._setInitialStorageValue}static get narrationOperation(){return M._narrationOperation}static get effectOperation(){return M._effectOperation}static get animateOperation(){return M._animateOperation}static get getLogichValue(){return M._getLogichValue}static get getConditionalStep(){return M._getConditionalStep}};Ne(Ae,"_loadAssets",()=>{}),Ne(Ae,"_soundOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_imageOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_videoOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_imageContainerOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_textOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_canvasElementOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_setStorageValue",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_setInitialStorageValue",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_narrationOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_effectOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_animateOperation",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_getLogichValue",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ne(Ae,"_getConditionalStep",()=>{throw we.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")});var x=Ae;var Mt;(i=>{i.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(u,h){e.unshift({fn:u,opts:h});}i.add=t;function n(u){let h=e.findIndex(c=>c.fn===u);h!==-1&&e.splice(h,1);}i.remove=n;function r(){return e.map(u=>u.opts)}i.info=r;function a(u,h){let c=e.filter(p=>(p.opts.type??"after-translation")===h.type);for(let p of c)u=l(u,p.fn,p.opts.validation);return u}i.replace=a;function s(u){let h=e.filter(c=>c.opts.i18nInterpolation);for(let c of h)u=o(u,c.fn,c.opts);return u}i.runI18nPreStep=s;function o(u,h,c){let{validation:p}=c,f=new RegExp(i.options.replaceRegex.source,"g"),y=[...u.matchAll(f)],C=new Set,A=[];for(let b of y)C.has(b[1])||(C.add(b[1]),A.push(b[1]));for(let b of A){if(p==="characterId"){if(!characters.RegisteredCharacters.has(b))continue}else if(p!=="all"){if(p instanceof RegExp){if(!p.test(b))continue}else if(p instanceof v.ZodType&&!p.safeParse(b).success)continue}h(b)!==void 0&&(u.includes(`{{[${b}]}}`)||(u=u.replaceAll(`[${b}]`,`{{[${b}]}}`)));}return u}function l(u,h,c){let p=new RegExp(i.options.replaceRegex.source,"g"),f=[...u.matchAll(p)],y=new Set,C=[];for(let A of f)y.has(A[1])||(y.add(A[1]),C.push(A[1]));for(let A of C){if(c==="characterId"){if(!characters.RegisteredCharacters.has(A))continue}else if(c!=="all"){if(c instanceof RegExp){if(!c.test(A))continue}else if(c instanceof v.ZodType&&!c.safeParse(A).success)continue}let b=h(A);b!==void 0&&(u=u.replaceAll(`[${A}]`,b));}return u}})(Mt||(Mt={}));function Ed(i,e={}){let t="";return i.values.forEach(n=>{if(typeof n=="string")t+=n;else {let r=x.getLogichValue(n,e);t+=`${r}`;}}),t}var ma;(i=>{let e=l=>l;function t(l){return Array.isArray(l)?l.map(u=>n(`${u}`)):n(`${l}`)}i.t=t;function n(l){let u=l;return i.beforeToTranslate&&(u=(0, i.beforeToTranslate)(u)),u=Mt.replace(u,{type:"before-translation"}),u=e(u),i.afterToTranslate&&(u=(0, i.afterToTranslate)(u)),u=Mt.replace(u,{type:"after-translation"}),u}i.translate=n;function r(l){e=l;}i.setTranslate=r;function a(l,u,h){let{defaultValue:c="empty_string"}=h;typeof u=="string"&&(u=[u]),Array.isArray(u)&&u.forEach(p=>{let f=p;if(i.beforeToTranslate&&(f=(0, i.beforeToTranslate)(f)),c==="empty_string")l[f]===void 0&&(l[f]="");else if(c==="copy_key"){let y=p;i.beforeToTranslate&&(y=(0, i.beforeToTranslate)(y));let C=Mt.runI18nPreStep(y);C=Mt.replace(C,{type:"before-translation"}),l[f]=C;}});}function s(l,u=[]){if(typeof l=="object"&&l&&"type"in l)if(l.type==="ifelse")l.then&&s(l.then,u),l.else&&s(l.else,u);else if(l.type==="stepswitch"){if(l.elements)if(Array.isArray(l.elements))l.elements.forEach(h=>{s(h,u);});else if(l.elements.type==="ifelse"){let h=[];s(l.elements,h),h.forEach(c=>{u.push(...c);});}else if(l.elements.type==="stepswitch"){let h=[];s(l.elements,h),h.forEach(c=>{u.push(...c);});}else s(l.elements,u);}else l.type==="resulttocombine"?(l.firstItem&&s(l.firstItem,u),l.secondConditionalItem&&l.secondConditionalItem.forEach(h=>{s(h,u);})):u.push(l);else l&&u.push(l);return u}async function o(l,u={},h={}){let{defaultValue:c="copy_key",operationStringConvert:p}=h,f=l.map(async y=>{if(y.choices){let C=[];Array.isArray(y.choices)?C=[y.choices]:C=s(y.choices),C.forEach(A=>{A.forEach(b=>{if("type"in b){let m=[];b.type==="ifelse"||b.type==="stepswitch"?s(b,m):m=[b],m.map(d=>s(d.text)).forEach(d=>{Array.isArray(d)&&d.forEach(S=>{Array.isArray(S)?S.forEach(g=>{typeof g=="string"?a(u,g,{defaultValue:c}):s(g).forEach(E=>{Array.isArray(E)?E.forEach(_=>{typeof _=="string"&&a(u,_,{defaultValue:c});}):typeof E=="string"&&a(u,E,{defaultValue:c});});}):typeof S=="string"&&a(u,S,{defaultValue:c});});});}});});}if(y.dialogue){let C=[];Array.isArray(y.dialogue)?C=[y.dialogue]:C=s(y.dialogue),C.forEach(A=>{if(typeof A=="string")a(u,A,{defaultValue:c});else if("text"in A){let b=s(A.text);typeof b=="string"&&(b=[b]),b.forEach(m=>{typeof m=="string"?a(u,m,{defaultValue:c}):s(m).forEach(d=>{typeof d=="string"?a(u,d,{defaultValue:c}):Array.isArray(d)&&d.forEach(S=>{typeof S=="string"?a(u,S,{defaultValue:c}):s(S).forEach(g=>{typeof g=="string"&&a(u,g,{defaultValue:c});});});});});}});}if(y.operations)for(let C of y.operations){if(C.type==="operationtoconvert"&&p){let A=Ed(C),b=await p(A,y,{});if(!b)return;C=b;}C.type==="text"&&C.operationType==="show"&&a(u,C.text,{defaultValue:c});}y.conditionalStep&&s(y.conditionalStep).forEach(C=>{Array.isArray(C)?o(C,u,h):o([C],u,h);});});return await Promise.all(f),u}i.generateJsonTranslation=o;})(ma||(ma={}));var me=ma;var Md=Object.defineProperty,Gd=(i,e,t)=>e in i?Md(i,e,{enumerable:true,configurable:true,writable:true,value:t}):i[e]=t,Ve=(i,e,t)=>Gd(i,typeof e!="symbol"?e+"":e,t);async function vu(i){let e=x.getLogichValue(i,{});if(e)switch(e.type){case "assets":switch(e.operationType){case "load":await canvas.Assets.load(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoad(e.aliases);break}break;case "bundle":switch(e.operationType){case "load":await canvas.Assets.loadBundle(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoadBundle(e.aliases);break}break}}var j;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(j||(j={}));async function Ni(i,e,t){switch(t.type){case "fade":await canvas.showWithFade(e.alias,i,t.props,t.priority);break;case "dissolve":await canvas.showWithDissolve(e.alias,i,t.props,t.priority);break;case "movein":case "moveout":await canvas.moveIn(e.alias,i,t.props,t.priority);break;case "zoomin":case "zoomout":await canvas.zoomIn(e.alias,i,t.props,t.priority);break;case "pushin":case "pushout":await canvas.pushIn(e.alias,i,t.props,t.priority);break}}function Ln(i){if(i.transition)switch(i.transition.type){case "fade":canvas.removeWithFade(i.alias,i.transition.props,i.transition.priority);break;case "dissolve":canvas.removeWithDissolve(i.alias,i.transition.props,i.transition.priority);break;case "movein":case "moveout":canvas.moveOut(i.alias,i.transition.props,i.transition.priority);break;case "zoomin":case "zoomout":canvas.zoomOut(i.alias,i.transition.props,i.transition.priority);break;case "pushin":case "pushout":canvas.pushOut(i.alias,i.transition.props,i.transition.priority);break}else canvas.canvas.remove(i.alias);}async function Su(i){switch(i.operationType){case "show":if(i.transition){let e=new canvas.ImageSprite(i.props,i.url||i.alias);await Ni(e,i,i.transition);}else await canvas.showImage(i.alias,i.url,i.props);break;case "edit":{let e=canvas.canvas.find(i.alias);e?i.props&&await e.setMemory({...e.memory,...i.props}):j.error(`Image with alias ${i.alias} not found.`);break}case "remove":Ln(i);break}}async function Eu(i){switch(i.operationType){case "show":if(i.transition){let e=new canvas.VideoSprite(i.props,i.url||i.alias);await Ni(e,i,i.transition);}else await canvas.showVideo(i.alias,i.url,i.props);break;case "edit":{let e=canvas.canvas.find(i.alias);e?i.props&&await e.setMemory({...e.memory,...i.props}):j.error(`Video with alias ${i.alias} not found.`);break}case "remove":Ln(i);break;case "pause":case "resume":{let e=canvas.canvas.find(i.alias);e?e.paused=i.operationType==="pause":j.error(`Video with alias ${i.alias} not found.`);break}}}async function bu(i){switch(i.operationType){case "show":if(i.transition){let e=new canvas.ImageContainer(i.props,i.urls);await Ni(e,i,i.transition);}else await canvas.showImageContainer(i.alias,i.urls,i.props);break;case "edit":{let e=canvas.canvas.find(i.alias);e?i.props&&await e.setMemory({...e.memory,...i.props}):j.error(`ImageContainer with alias ${i.alias} not found.`);break}case "remove":Ln(i);break}}async function Du(i){switch(i.operationType){case "show":if(i.props=i.props||{},i.props.text=me.t(i.text),i.transition){let e=new canvas.Text(i.props);await Ni(e,i,i.transition);}else canvas.showText(i.alias,i.text,i.props);break;case "edit":{let e=canvas.canvas.find(i.alias);e?i.props&&await e.setMemory({...e.memory,...i.props}):j.error(`Text with alias ${i.alias} not found.`);break}case "remove":Ln(i);break}}async function Au(i){switch(i.operationType){case "edit":try{let e=canvas.canvas.find(i.alias);e?i.props&&e.setMemory({...e.memory,...i.props}):j.error(`Canvas Element with alias ${i.alias} not found.`);}catch(e){j.error(`There was an error while trying to edit the canvas element with alias ${i.alias}.`,e);}break;case "remove":Ln(i);break}}async function wu(i){i.type==="shake"&&await canvas.shakeEffect(i.alias,i.props,i.priority);}function xu(i){switch(i.type){case "animate":canvas.canvas.animate(i.alias,i.keyframes,i.options,i.priority);break;case "animate-sequence":canvas.canvas.animate(i.alias,i.sequence,i.options,i.priority);break}}function _u(i){switch(i.type){case "input":narration.narration.requestInput({type:i.valueType},i.defaultValue);break;case "dialogue":narration.narration.dialogue=void 0;break}}function Ou(i){switch(i.operationType){case "play":i.url?sound.sound.play(i.alias,i.url,i.props):sound.sound.play(i.alias,i.props);break;case "stop":switch(i.type){case "sound":sound.sound.stop(i.alias);break;case "all":sound.sound.stopAll();break}break;case "pause":switch(i.type){case "sound":sound.sound.pause(i.alias);break;case "channel":sound.sound.findChannel(i.alias).pauseAll();break;case "all":sound.sound.pauseAll();break}break;case "resume":switch(i.type){case "sound":sound.sound.resume(i.alias);break;case "channel":sound.sound.findChannel(i.alias).resumeAll();break;case "all":sound.sound.resumeAll();break}break;case "edit":Object.entries(i.props).forEach(([e,t])=>{let n=sound.sound.find(i.alias);n&&(e==="volume"?n.volume.value=t:n.paused=t);});break}}var Ca="___param___",xe=class G{static init(e){e.loadAssets&&(G._loadAssets=e.loadAssets),e.soundOperation&&(G._soundOperation=e.soundOperation),e.imageOperation&&(G._imageOperation=e.imageOperation),e.videoOperation&&(G._videoOperation=e.videoOperation),e.imageContainerOperation&&(G._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(G._textOperation=e.textOperation),e.canvasElementOperation&&(G._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(G._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(G._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(G._narrationOperation=e.narrationOperation),e.effectOperation&&(G._effectOperation=e.effectOperation),e.animateOperation&&(G._animateOperation=e.animateOperation),e.getLogichValue&&(G._getLogichValue=e.getLogichValue),e.getConditionalStep&&(G._getConditionalStep=e.getConditionalStep);}static get loadAssets(){return G._loadAssets}static get soundOperation(){return G._soundOperation}static get imageOperation(){return G._imageOperation}static get videoOperation(){return G._videoOperation}static get imageContainerOperation(){return G._imageContainerOperation}static get textOperation(){return G._textOperation}static get canvasElementOperation(){return G._canvasElementOperation}static get setStorageValue(){return G._setStorageValue}static get setInitialStorageValue(){return G._setInitialStorageValue}static get narrationOperation(){return G._narrationOperation}static get effectOperation(){return G._effectOperation}static get animateOperation(){return G._animateOperation}static get getLogichValue(){return G._getLogichValue}static get getConditionalStep(){return G._getConditionalStep}};Ve(xe,"_loadAssets",()=>{}),Ve(xe,"_soundOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_imageOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_videoOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_imageContainerOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_textOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_canvasElementOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_setStorageValue",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_setInitialStorageValue",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_narrationOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_effectOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_animateOperation",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_getLogichValue",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ve(xe,"_getConditionalStep",()=>{throw j.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")});var $d=xe;function Jd(i,e){if(e&&typeof e=="object"&&typeof i.functionName=="string"&&i.functionName in e){let t=e[i.functionName];if(typeof t=="function"){let n=i.args.map(r=>$d.getLogichValue(r,e));return t(...n)}else j.warn(`getLogichValue function ${i.functionName} not found in props`);}}function Pu(i,e){let t=x.getLogichValue(i,e);return t&&typeof t=="object"&&"type"in t?x.getLogichValue(t,e):t}function Tu(i,e={}){let t=Pu(i.value,e);switch(i.storageType){case "flagStorage":storage.storage.setFlag(i.key,i.value);break;case "storage":storage.storage.set(i.key,t);break;case "tempstorage":storage.storage.setTempVariable(i.key,t);break;case "params":{let n=storage.storage.get(`${Ca}${narration.narration.openedLabels.length-1}`)||[];n.length>i.key&&(n[i.key]=t),storage.storage.setTempVariable(`${Ca}${narration.narration.openedLabels.length-1}`,n);break}}}function Fu(i,e={}){let t=Pu(i.value,e);switch(i.storageType){case "storage":case "tempstorage":storage.storage.default={[i.key]:t};break}}function Nu(i,e={}){let t=Vu(i,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return zd(t,e);case "arithmetic":case "arithmeticsingle":return Hd(t,e);case "compare":case "union":return Ud(t,e);case "function":return Jd(t,e)}return t}function Hd(i,e){let t=x.getLogichValue(i.leftValue,e);switch(i.type){case "arithmetic":{let n=x.getLogichValue(i.rightValue,e);switch(i.operator){case "*":return t*n;case "/":return t/n;case "+":return typeof t=="string"||typeof n=="string"?`${t}${n}`:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:Array.isArray(t)?[...t,n]:Array.isArray(n)?[t,...n]:t+n;case "-":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>!n.includes(r));if(Array.isArray(t))return t.filter(r=>r!==n);if(Array.isArray(n)){j.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-n;case "%":return t%n;case "POW":return t**n;case "RANDOM":return narration.narration.getRandomNumber(t,n);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>n.includes(r));j.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:j.warn("getValueFromArithmeticOperations unknown operator",i);return}}case "arithmeticsingle":switch(i.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function zd(i,e){if(i&&typeof i=="object"&&"type"in i&&i.type==="value"&&i.storageOperationType==="get")switch(i.storageType){case "storage":case "tempstorage":return i.key==="_input_value_"?narration.narration.inputValue:storage.storage.get(i.key);case "flagStorage":return storage.storage.getFlag(i.key);case "label":return narration.narration.getTimesLabelOpened(i.label);case "choice":return narration.narration.getTimesChoiceMade(i.index);case "logic":return x.getLogichValue(i.operation,e);case "params":{let t=storage.storage.get(`${Ca}${narration.narration.openedLabels.length-1}`)||[];if(t&&t.length>i.key)return t[i.key];j.warn("getValue params not found");return}}return i}function Ud(i,e){if(!i)return false;if(typeof i!="object"||!("type"in i))return !!i;switch(i.type){case "compare":{let t=x.getLogichValue(i.leftValue,e),n=x.getLogichValue(i.rightValue,e);switch(i.operator){case "==":return Array.isArray(t)&&Array.isArray(n)?t.length===n.length&&t.every(r=>n.includes(r)):t===n;case "!=":return Array.isArray(t)&&Array.isArray(n)?t.length!==n.length||!t.every(r=>n.includes(r)):t!==n;case "<":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<0:Array.isArray(t)&&Array.isArray(n)?t.length<n.length:t<n;case "<=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<=0:Array.isArray(t)&&Array.isArray(n)?t.length<=n.length:t<=n;case ">":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>0:Array.isArray(t)&&Array.isArray(n)?t.length>n.length:t>n;case ">=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>=0:Array.isArray(t)&&Array.isArray(n)?t.length>=n.length:t>=n;case "CONTAINS":return Array.isArray(t)&&Array.isArray(n)?n.every(r=>t.includes(r)):Array.isArray(t)?t.includes(n):t.toString().includes(n.toString())}break}case "value":{let t=x.getLogichValue(i,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return Kd(i,e)}return !!i}function Kd(i,e){if(i.unionType==="not"){let n=Nu(i.condition,e);return Array.isArray(n)?n.length===0:n&&typeof n=="object"?Object.keys(n).length===0:!n}let t=n=>x.getLogichValue(n,e)||false;return i.unionType==="and"?i.conditions.every(t):i.conditions.some(t)}function Xd(i,e){return Math.floor(Math.random()*(e-i+1)+i)}function Vu(i,e={}){if(Array.isArray(i)||!i)return i;if(i&&typeof i=="object"&&"type"in i)switch(i.type){case "resulttocombine":return Yd(i,e);case "ifelse":return x.getLogichValue(i.condition,e)?x.getLogichValue(i.then,e):x.getLogichValue(i.else,e);case "stepswitch":{let t=x.getLogichValue(i.elements,e)||[];if(t.length===0){j.error("getValueFromConditionalStatements elements.length === 0");return}switch(i.choiceType){case "random":{let n=Xd(0,t.length-1);return x.getLogichValue(t[n],e)}case "loop":{let n=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return n>t.length-1?(n=n%t.length,x.getLogichValue(t[n],e)):x.getLogichValue(t[n],e)}case "sequential":{let n,r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return i.end==="lastItem"&&(n=x.getLogichValue(t[t.length-1],e)),r>t.length-1?n:x.getLogichValue(t[r],e)}case "sequentialrandom":{let n=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:i.nestedId,onceOnly:true});if(n===void 0&&i.end==="lastItem"){let r=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(i.nestedId);if(!r?.usedRandomNumbers){j.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=r.usedRandomNumbers[`0-${t.length-1}`];return x.getLogichValue(t[a[a.length-1]],e)}if(n===void 0){j.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return x.getLogichValue(t[n],e)}}}}return i}function Vi(i,e={}){if(i.conditionalStep){let t=pixiVn.createExportableElement(x.getLogichValue(i.conditionalStep,e));if(t?.glueEnabled===void 0&&delete t?.glueEnabled,t?.goNextStep===void 0&&delete t?.goNextStep,t?.end===void 0&&delete t?.end,t?.choices===void 0&&delete t?.choices,t?.dialogue===void 0&&delete t?.dialogue,t?.labelToOpen===void 0&&delete t?.labelToOpen,t?.operations===void 0&&delete t?.operations,t){let n={...i,conditionalStep:void 0,...t};return Vi(n,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return i}function Yd(i,e){let t=i.firstItem,n=(i.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>x.getLogichValue(s,e)):[x.getLogichValue(a,e)]),r=t?[t,...n]:n;if(r.length===0){j.warn("combinateResult toCheck.length === 0");return}if(typeof r[0]=="string")return me.t(r);if(typeof r[0]=="object"){let a=r,s,o=false,l=a.map((m,d)=>{m=Vi(m,e);let S=x.getLogichValue(m.dialogue,e)||"";return d===0?(s=x.getLogichValue(m.glueEnabled,e)||false,S):(typeof S=="object"&&"text"in S&&(S=`${S.character}: ${S.text}`),s===false&&o&&(S=`
64
+ \`\`\``,validation:y__default.default.tuple([y__default.default.enum(["load","lazyload"]),y__default.default.enum(["assets","bundle"])]).rest(y__default.default.string())});O.addMapper(i=>({type:"all",operationType:i[0]}),{name:"Pause/Resume/Stop all sounds",description:"Pauses, resumes, or stops all active sounds at once.\n\n```ink\n# pause all sounds\n# resume all sounds\n# stop all sounds\n```",validation:y__default.default.tuple([y__default.default.enum(["pause","resume","stop"]),y__default.default.literal("all"),y__default.default.enum(["sounds","sound"])])});O.addMapper(i=>({type:"sound",operationType:"pause",alias:i[2]}),{name:"Pause sound",description:"Pauses the sound identified by its alias.\n\n```ink\n# pause sound <alias>\n```",validation:y__default.default.tuple([y__default.default.literal("pause"),y__default.default.literal("sound"),y__default.default.string()])});O.addMapper(i=>({type:"channel",operationType:"pause",alias:i[2]}),{name:"Pause channel",description:"Pauses the audio channel identified by its alias.\n\n```ink\n# pause channel <alias>\n```",validation:y__default.default.tuple([y__default.default.literal("pause"),y__default.default.literal("channel"),y__default.default.string()])});O.addMapper(i=>({type:"sound",operationType:"resume",alias:i[2]}),{name:"Resume sound",description:"Resumes the sound identified by its alias.\n\n```ink\n# resume sound <alias>\n```",validation:y__default.default.tuple([y__default.default.literal("resume"),y__default.default.literal("sound"),y__default.default.string()])});O.addMapper(i=>({type:"channel",operationType:"resume",alias:i[2]}),{name:"Resume channel",description:"Resumes the audio channel identified by its alias.\n\n```ink\n# resume channel <alias>\n```",validation:y__default.default.tuple([y__default.default.literal("resume"),y__default.default.literal("channel"),y__default.default.string()])});O.addMapper(i=>({type:"sound",operationType:"stop",alias:i[2]}),{name:"Stop sound",description:"Stops the sound identified by its alias.\n\n```ink\n# stop sound <alias>\n```",validation:y__default.default.tuple([y__default.default.literal("stop"),y__default.default.literal("sound"),y__default.default.string()])});O.addMapper(i=>({type:"sound",operationType:"stop",alias:i[2]}),{name:"Remove sound",description:"Removes (stops) the sound identified by its alias.\n\n```ink\n# remove sound <alias>\n```",deprecated:true,validation:y__default.default.tuple([y__default.default.literal("remove"),y__default.default.literal("sound"),y__default.default.string()])});O.addMapper(i=>({type:"sound",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"Edit sound",description:"Edits the properties of a sound identified by its alias.\n\n```ink\n# edit sound <alias> [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("edit"),y__default.default.literal("sound"),y__default.default.string()]).rest(y__default.default.string()).refine(i=>(i.length-3)%2===0)});O.addMapper(i=>{let e=i[2],t={type:"sound",operationType:"play",alias:e,url:e};return i.length>3&&(t.props=O.convertListStringToObj(i.slice(3))),t},{name:"Play sound",description:"Plays a sound using its alias as the URL, with optional key/value properties.\n\n```ink\n# play sound <alias> [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("play"),y__default.default.literal("sound"),y__default.default.string()]).rest(y__default.default.string()).refine(i=>(i.length-3)%2===0)});O.addMapper(i=>{let e=i[2],t=i[3],n={type:"sound",operationType:"play",alias:e,url:t};return i.length>4&&(n.props=O.convertListStringToObj(i.slice(4))),n},{name:"Play sound with source",description:"Plays a sound with an explicit source URL and optional key/value properties.\n \n```ink\n# play sound <alias> <source> [<key> <value> \u2026]\n```\n",validation:y__default.default.tuple([y__default.default.literal("play"),y__default.default.literal("sound"),y__default.default.string()]).rest(y__default.default.string()).refine(i=>i.length>3&&(i.length-3)%2!==0)});function ze(i){let e=[],t=0,n="";for(let r of i)r.startsWith("{")?(t++,n+=r):r.endsWith("}")&&t>0?(t--,n+=r,t===0&&(e.push(n),n="")):t>0?n+=r:e.push(r);return e}function gi(i,e){switch(i){case "dissolve":case "fade":case "movein":case "moveout":case "zoomin":case "zoomout":case "pushin":case "pushout":break;default:return}let t={type:i};if(e.length>0)try{t.props=O.convertListStringToObj(e);}catch{}return t}function eu(i,e,t){let n,r;t.length%2===0?(n=e,r=t):(n=t[0],r=t.slice(1));let a={type:i,operationType:"show",alias:e,url:n};if(r.length>0){if(r.includes("with")&&r.length>r.indexOf("with")+1){let s=r[r.indexOf("with")+1],o=r.slice(r.indexOf("with")+2);r=r.slice(0,r.indexOf("with"));let l=gi(s,o);l!==void 0&&(a.transition=l);}r.length>0&&(a.props=O.convertListStringToObj(r));}return a}function ed(i,e){let t,n;e.length%2===0?(t=i,n=e):(t=e[0],n=e.slice(1));let r={type:"text",operationType:"show",alias:i,text:t};if(n.length>0){if(n.includes("with")&&n.length>n.indexOf("with")+1){let a=n[n.indexOf("with")+1],s=n.slice(n.indexOf("with")+2);n=n.slice(0,n.indexOf("with"));let o=gi(a,s);o!==void 0&&(r.transition=o);}n.length>0&&(r.props=O.convertListStringToObj(n));}return r}function An(i,e,t){let n={type:i,operationType:"remove",alias:e};if(t.includes("with")&&t.length>t.indexOf("with")+1){let r=t[t.indexOf("with")+1],a=t.slice(t.indexOf("with")+2),s=gi(r,a);s!==void 0&&(n.transition=s);}return n}function ta(i,e){let t=l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'")||l.startsWith("`")&&l.endsWith("`")?l.substring(1,l.length-1):l,n=[],r=e.findIndex(l=>l.startsWith("[")),a=e.findIndex(l=>l.endsWith("]"));if(r===-1||a===-1){W.error("Show imagecontainer must have a list of image ulrs",e);return}if(n=e.slice(r,a+1),n.length<2){W.error("Show imagecontainer must have a list of image ulrs",e);return}n[0]==="["?n.shift():n[0]=n[0].substring(1),n[n.length-1]==="]"?n.pop():n[n.length-1]=n[n.length-1].substring(0,n[n.length-1].length-1);let s={type:"imagecontainer",operationType:"show",alias:i,urls:n.map(l=>t(l))},o=e.slice(a+1);if(o.length>0){if(o.includes("with")&&o.length>o.indexOf("with")+1){let l=o[o.indexOf("with")+1],u=o.slice(o.indexOf("with")+2);o=o.slice(0,o.indexOf("with"));let h=gi(l,u);h!==void 0&&(s.transition=h);}o.length>0&&(s.props=O.convertListStringToObj(o));}return s}function na(i){let e=i.slice(3),t=e.findIndex(s=>s.startsWith("[")),n=e.findIndex(s=>s.endsWith("]"));if(t===-1||n===-1||n<t)return;let r=e.slice(n+1),a=r.indexOf("with");return a===-1?{beforeWith:r,afterWith:[]}:{beforeWith:r.slice(0,a),afterWith:r.slice(a+1)}}O.addMapper(i=>({alias:i[1],type:"shake",props:O.convertListStringToObj(i.slice(2))}),{name:"Shake",description:"Applies shake effect to a canvas alias with optional key/value parameters.\n\n```ink\n# shake <alias> [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("shake"),y__default.default.string()]).rest(y__default.default.string()).refine(i=>(i.length-2)%2===0)});O.addMapper(i=>{let e=i.slice(2),t=e,n=[];if(e.includes("options")){let a=e.indexOf("options");t=e.slice(0,a),n=e.slice(a+1);}return {alias:i[1],type:"animate",keyframes:O.convertListStringToObj(t),options:O.convertListStringToObj(n)}},{name:"Animate",description:"Animates a canvas alias with keyframes and optional options section, both in key/value pairs.\n\n```ink\n# animate <alias> [<key> <value> \u2026] [options <key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("animate"),y__default.default.string()]).rest(y__default.default.string()).refine(i=>{let e=i.slice(2),t=e.indexOf("options");if(t===-1)return e.length%2===0;if(e.lastIndexOf("options")!==t)return false;let n=e.slice(0,t),r=e.slice(t+1);return n.length%2===0&&r.length%2===0})});O.addMapper(i=>{let e=i[2],t=ze(i.slice(3));return eu("image",e,t)},{name:"Show image",description:"Shows an image canvas element with optional source URL, key/value properties, and transition effect.\n\n```ink\n# show image <alias> [<source>] [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:y__default.default.tuple([y__default.default.literal("show"),y__default.default.literal("image"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>ta(i[2],ze(i.slice(3))),{name:"Show imagecontainer",description:"Shows an image-container canvas element with a list of image URLs and optional key/value properties.\n\n```ink\n# show imagecontainer <alias> [ <url1> <url2> \u2026 ] [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("show"),y__default.default.literal("imagecontainer"),y__default.default.string()]).rest(y__default.default.string()).refine(i=>{let e=na(i);return e===void 0?false:e.afterWith.length===0&&e.beforeWith.length%2===0})});O.addMapper(i=>ta(i[2],ze(i.slice(3))),{name:"Show imagecontainer with transition",description:"Shows an image-container canvas element with a list of image URLs, optional properties, and a transition effect.\n\n```ink\n# show imagecontainer <alias> [ <url1> <url2> \u2026 ] [<key> <value> \u2026] with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout\n```",validation:y__default.default.tuple([y__default.default.literal("show"),y__default.default.literal("imagecontainer"),y__default.default.string()]).rest(y__default.default.string()).refine(i=>{let e=na(i);return e===void 0?false:e.afterWith.length===1&&e.beforeWith.length%2===0})});O.addMapper(i=>ta(i[2],ze(i.slice(3))),{name:"Show imagecontainer with transition and props",description:"Shows an image-container canvas element with a list of image URLs, optional properties, a transition effect, and transition key/value properties.\n\n```ink\n# show imagecontainer <alias> [ <url1> <url2> \u2026 ] [<key> <value> \u2026] with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout <key> <value> \u2026\n```",validation:y__default.default.tuple([y__default.default.literal("show"),y__default.default.literal("imagecontainer"),y__default.default.string()]).rest(y__default.default.string()).refine(i=>{let e=na(i);return e===void 0?false:e.afterWith.length>1&&(e.afterWith.length-1)%2===0&&e.beforeWith.length%2===0})});O.addMapper(i=>{let e=i[2],t=ze(i.slice(3));return eu("video",e,t)},{name:"Show video",description:"Shows a video canvas element with optional source URL, key/value properties, and transition effect.\n\n```ink\n# show video <alias> [<source>] [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:y__default.default.tuple([y__default.default.literal("show"),y__default.default.literal("video"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>{let e=i[2];return ed(e,i.slice(3))},{name:"Show text",description:"Shows a text canvas element with optional text content, key/value properties, and transition effect.\n\n```ink\n# show text <alias> [<text>] [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:y__default.default.tuple([y__default.default.literal("show"),y__default.default.literal("text"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>{let e=i[2],t=ze(i.slice(3));return An("image",e,t)},{name:"Remove image",description:"Removes an image canvas element with an optional transition effect.\n\n```ink\n# remove image <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:y__default.default.tuple([y__default.default.literal("remove"),y__default.default.literal("image"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>{let e=i[2],t=ze(i.slice(3));return An("video",e,t)},{name:"Remove video",description:"Removes a video canvas element with an optional transition effect.\n\n```ink\n# remove video <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:y__default.default.tuple([y__default.default.literal("remove"),y__default.default.literal("video"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>{let e=i[2],t=ze(i.slice(3));return An("canvaselement",e,t)},{name:"Remove canvas element",description:"Removes a canvas element with an optional transition effect.\n\n```ink\n# remove canvaselement <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:y__default.default.tuple([y__default.default.literal("remove"),y__default.default.literal("canvaselement"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>{let e=i[2],t=ze(i.slice(3));return An("text",e,t)},{name:"Remove text",description:"Removes a text canvas element with an optional transition effect.\n\n```ink\n# remove text <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:y__default.default.tuple([y__default.default.literal("remove"),y__default.default.literal("text"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>{let e=i[2],t=ze(i.slice(3));return An("imagecontainer",e,t)},{name:"Remove imagecontainer",description:"Removes an image-container canvas element with an optional transition effect.\n\n```ink\n# remove imagecontainer <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:y__default.default.tuple([y__default.default.literal("remove"),y__default.default.literal("imagecontainer"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>({type:"image",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"Edit image",description:"Edits the properties of an image canvas element identified by its alias.\n\n```ink\n# edit image <alias> [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("edit"),y__default.default.literal("image"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>({type:"imagecontainer",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"Edit imagecontainer",description:"Edits the properties of an image-container canvas element identified by its alias.\n\n```ink\n# edit imagecontainer <alias> [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("edit"),y__default.default.literal("imagecontainer"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>({type:"canvaselement",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"Edit canvas element",description:"Edits the properties of a canvas element identified by its alias.\n\n```ink\n# edit canvaselement <alias> [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("edit"),y__default.default.literal("canvaselement"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>({type:"video",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"Edit video",description:"Edits the properties of a video canvas element identified by its alias.\n\n```ink\n# edit video <alias> [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("edit"),y__default.default.literal("video"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>({type:"text",operationType:"edit",alias:i[2],props:O.convertListStringToObj(i.slice(3))}),{name:"Edit text",description:"Edits the properties of a text canvas element identified by its alias.\n\n```ink\n# edit text <alias> [<key> <value> \u2026]\n```",validation:y__default.default.tuple([y__default.default.literal("edit"),y__default.default.literal("text"),y__default.default.string()]).rest(y__default.default.string())});O.addMapper(i=>({type:"input",operationType:"request"}),{name:"Request input",description:"Requests player input without any additional constraints.\n\n```ink\n# request input\n```",validation:y__default.default.tuple([y__default.default.literal("request"),y__default.default.literal("input")])});O.addMapper(i=>{let e={type:"input",operationType:"request"};try{let t=O.convertListStringToObj(i.slice(2));"type"in t&&typeof t.type=="string"&&(e.valueType=t.type),"default"in t&&(e.defaultValue=t.default);}catch{}return e},{name:"Request input with params",description:"Requests player input with optional key/value parameters (e.g. type, default).\n\n```ink\n# request input <key> <value> [<key> <value> \u2026]\n# request input type number default 18\n```",validation:y__default.default.tuple([y__default.default.literal("request"),y__default.default.literal("input")]).rest(y__default.default.string()).refine(i=>i.length>2&&(i.length-2)%2===0)});var be;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(be||={});var _=class M{static init(e){e.loadAssets&&(M._loadAssets=e.loadAssets),e.soundOperation&&(M._soundOperation=e.soundOperation),e.imageOperation&&(M._imageOperation=e.imageOperation),e.videoOperation&&(M._videoOperation=e.videoOperation),e.imageContainerOperation&&(M._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(M._textOperation=e.textOperation),e.canvasElementOperation&&(M._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(M._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(M._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(M._narrationOperation=e.narrationOperation),e.effectOperation&&(M._effectOperation=e.effectOperation),e.animateOperation&&(M._animateOperation=e.animateOperation),e.getLogichValue&&(M._getLogichValue=e.getLogichValue),e.getConditionalStep&&(M._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return M._loadAssets}static _soundOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return M._soundOperation}static _imageOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return M._imageOperation}static _videoOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return M._videoOperation}static _imageContainerOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return M._imageContainerOperation}static _textOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return M._textOperation}static _canvasElementOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return M._canvasElementOperation}static _setStorageValue=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return M._setStorageValue}static _setInitialStorageValue=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return M._setInitialStorageValue}static _narrationOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return M._narrationOperation}static _effectOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return M._effectOperation}static _animateOperation=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return M._animateOperation}static _getLogichValue=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return M._getLogichValue}static _getConditionalStep=()=>{throw be.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return M._getConditionalStep}};var Jt;(i=>{i.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(u,h){e.unshift({fn:u,opts:h});}i.add=t;function n(u){let h=e.findIndex(c=>c.fn===u);h!==-1&&e.splice(h,1);}i.remove=n;function r(){return e.map(u=>u.opts)}i.info=r;function a(u,h){let c=e.filter(p=>(p.opts.type??"after-translation")===h.type);for(let p of c)u=l(u,p.fn,p.opts.validation);return u}i.replace=a;function s(u){let h=e.filter(c=>c.opts.i18nInterpolation);for(let c of h)u=o(u,c.fn,c.opts);return u}i.runI18nPreStep=s;function o(u,h,c){let{validation:p}=c,f=new RegExp(i.options.replaceRegex.source,"g"),v=[...u.matchAll(f)],g=new Set,A=[];for(let D of v)g.has(D[1])||(g.add(D[1]),A.push(D[1]));for(let D of A){if(p==="characterId"){if(!characters.RegisteredCharacters.has(D))continue}else if(p!=="all"){if(p instanceof RegExp){if(!p.test(D))continue}else if(p instanceof y.ZodType&&!p.safeParse(D).success)continue}h(D)!==void 0&&(u.includes(`{{[${D}]}}`)||(u=u.replaceAll(`[${D}]`,`{{[${D}]}}`)));}return u}function l(u,h,c){let p=new RegExp(i.options.replaceRegex.source,"g"),f=[...u.matchAll(p)],v=new Set,g=[];for(let A of f)v.has(A[1])||(v.add(A[1]),g.push(A[1]));for(let A of g){if(c==="characterId"){if(!characters.RegisteredCharacters.has(A))continue}else if(c!=="all"){if(c instanceof RegExp){if(!c.test(A))continue}else if(c instanceof y.ZodType&&!c.safeParse(A).success)continue}let D=h(A);D!==void 0&&(u=u.replaceAll(`[${A}]`,D));}return u}})(Jt||={});function td(i,e={}){let t="";return i.values.forEach(n=>{if(typeof n=="string")t+=n;else {let r=_.getLogichValue(n,e);t+=`${r}`;}}),t}var iu;(i=>{let e=l=>l;function t(l){return Array.isArray(l)?l.map(u=>n(`${u}`)):n(`${l}`)}i.t=t;function n(l){let u=l;return i.beforeToTranslate&&(u=(0, i.beforeToTranslate)(u)),u=Jt.replace(u,{type:"before-translation"}),u=e(u),i.afterToTranslate&&(u=(0, i.afterToTranslate)(u)),u=Jt.replace(u,{type:"after-translation"}),u}i.translate=n;function r(l){e=l;}i.setTranslate=r;function a(l,u,h){let{defaultValue:c="empty_string"}=h;typeof u=="string"&&(u=[u]),Array.isArray(u)&&u.forEach(p=>{let f=p;if(i.beforeToTranslate&&(f=(0, i.beforeToTranslate)(f)),c==="empty_string")l[f]===void 0&&(l[f]="");else if(c==="copy_key"){let v=p;i.beforeToTranslate&&(v=(0, i.beforeToTranslate)(v));let g=Jt.runI18nPreStep(v);g=Jt.replace(g,{type:"before-translation"}),l[f]=g;}});}function s(l,u=[]){if(typeof l=="object"&&l&&"type"in l)if(l.type==="ifelse")l.then&&s(l.then,u),l.else&&s(l.else,u);else if(l.type==="stepswitch"){if(l.elements)if(Array.isArray(l.elements))l.elements.forEach(h=>{s(h,u);});else if(l.elements.type==="ifelse"){let h=[];s(l.elements,h),h.forEach(c=>{u.push(...c);});}else if(l.elements.type==="stepswitch"){let h=[];s(l.elements,h),h.forEach(c=>{u.push(...c);});}else s(l.elements,u);}else l.type==="resulttocombine"?(l.firstItem&&s(l.firstItem,u),l.secondConditionalItem&&l.secondConditionalItem.forEach(h=>{s(h,u);})):u.push(l);else l&&u.push(l);return u}async function o(l,u={},h={}){let{defaultValue:c="copy_key",operationStringConvert:p}=h,f=l.map(async v=>{if(v.choices){let g=[];Array.isArray(v.choices)?g=[v.choices]:g=s(v.choices),g.forEach(A=>{A.forEach(D=>{if("type"in D){let C=[];D.type==="ifelse"||D.type==="stepswitch"?s(D,C):C=[D],C.map(d=>s(d.text)).forEach(d=>{Array.isArray(d)&&d.forEach(E=>{Array.isArray(E)?E.forEach(m=>{typeof m=="string"?a(u,m,{defaultValue:c}):s(m).forEach(S=>{Array.isArray(S)?S.forEach(w=>{typeof w=="string"&&a(u,w,{defaultValue:c});}):typeof S=="string"&&a(u,S,{defaultValue:c});});}):typeof E=="string"&&a(u,E,{defaultValue:c});});});}});});}if(v.dialogue){let g=[];Array.isArray(v.dialogue)?g=[v.dialogue]:g=s(v.dialogue),g.forEach(A=>{if(typeof A=="string")a(u,A,{defaultValue:c});else if("text"in A){let D=s(A.text);typeof D=="string"&&(D=[D]),D.forEach(C=>{typeof C=="string"?a(u,C,{defaultValue:c}):s(C).forEach(d=>{typeof d=="string"?a(u,d,{defaultValue:c}):Array.isArray(d)&&d.forEach(E=>{typeof E=="string"?a(u,E,{defaultValue:c}):s(E).forEach(m=>{typeof m=="string"&&a(u,m,{defaultValue:c});});});});});}});}if(v.operations)for(let g of v.operations){if(g.type==="operationtoconvert"&&p){let A=td(g),D=await p(A,v,{});if(!D)return;g=D;}g.type==="text"&&g.operationType==="show"&&a(u,g.text,{defaultValue:c});}v.conditionalStep&&s(v.conditionalStep).forEach(g=>{Array.isArray(g)?o(g,u,h):o([g],u,h);});});return await Promise.all(f),u}i.generateJsonTranslation=o;})(iu||={});var Ve=iu;async function ru(i){let e=_.getLogichValue(i,{});if(e)switch(e.type){case "assets":switch(e.operationType){case "load":await canvas.Assets.load(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoad(e.aliases);break}break;case "bundle":switch(e.operationType){case "load":await canvas.Assets.loadBundle(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoadBundle(e.aliases);break}break}}var q;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(q||={});async function vi(i,e,t){switch(t.type){case "fade":await canvas.showWithFade(e.alias,i,t.props,t.priority);break;case "dissolve":await canvas.showWithDissolve(e.alias,i,t.props,t.priority);break;case "movein":case "moveout":await canvas.moveIn(e.alias,i,t.props,t.priority);break;case "zoomin":case "zoomout":await canvas.zoomIn(e.alias,i,t.props,t.priority);break;case "pushin":case "pushout":await canvas.pushIn(e.alias,i,t.props,t.priority);break}}function xn(i){if(i.transition)switch(i.transition.type){case "fade":canvas.removeWithFade(i.alias,i.transition.props,i.transition.priority);break;case "dissolve":canvas.removeWithDissolve(i.alias,i.transition.props,i.transition.priority);break;case "movein":case "moveout":canvas.moveOut(i.alias,i.transition.props,i.transition.priority);break;case "zoomin":case "zoomout":canvas.zoomOut(i.alias,i.transition.props,i.transition.priority);break;case "pushin":case "pushout":canvas.pushOut(i.alias,i.transition.props,i.transition.priority);break}else canvas.canvas.remove(i.alias);}async function su(i){switch(i.operationType){case "show":if(i.transition){let e=new canvas.ImageSprite(i.props,i.url||i.alias);await vi(e,i,i.transition);}else await canvas.showImage(i.alias,i.url,i.props);break;case "edit":{let e=canvas.canvas.find(i.alias);e?i.props&&await e.setMemory({...e.memory,...i.props}):q.error(`Image with alias ${i.alias} not found.`);break}case "remove":xn(i);break}}async function au(i){switch(i.operationType){case "show":if(i.transition){let e=new canvas.VideoSprite(i.props,i.url||i.alias);await vi(e,i,i.transition);}else await canvas.showVideo(i.alias,i.url,i.props);break;case "edit":{let e=canvas.canvas.find(i.alias);e?i.props&&await e.setMemory({...e.memory,...i.props}):q.error(`Video with alias ${i.alias} not found.`);break}case "remove":xn(i);break;case "pause":case "resume":{let e=canvas.canvas.find(i.alias);e?e.paused=i.operationType==="pause":q.error(`Video with alias ${i.alias} not found.`);break}}}async function ou(i){switch(i.operationType){case "show":if(i.transition){let e=new canvas.ImageContainer(i.props,i.urls);await vi(e,i,i.transition);}else await canvas.showImageContainer(i.alias,i.urls,i.props);break;case "edit":{let e=canvas.canvas.find(i.alias);e?i.props&&await e.setMemory({...e.memory,...i.props}):q.error(`ImageContainer with alias ${i.alias} not found.`);break}case "remove":xn(i);break}}async function lu(i){switch(i.operationType){case "show":if(i.props=i.props||{},i.props.text=Ve.t(i.text),i.transition){let e=new canvas.Text(i.props);await vi(e,i,i.transition);}else canvas.showText(i.alias,i.text,i.props);break;case "edit":{let e=canvas.canvas.find(i.alias);e?i.props&&await e.setMemory({...e.memory,...i.props}):q.error(`Text with alias ${i.alias} not found.`);break}case "remove":xn(i);break}}async function uu(i){switch(i.operationType){case "edit":try{let e=canvas.canvas.find(i.alias);e?i.props&&e.setMemory({...e.memory,...i.props}):q.error(`Canvas Element with alias ${i.alias} not found.`);}catch(e){q.error(`There was an error while trying to edit the canvas element with alias ${i.alias}.`,e);}break;case "remove":xn(i);break}}async function hu(i){i.type==="shake"&&await canvas.shakeEffect(i.alias,i.props,i.priority);}function cu(i){switch(i.type){case "animate":canvas.canvas.animate(i.alias,i.keyframes,i.options,i.priority);break;case "animate-sequence":canvas.canvas.animate(i.alias,i.sequence,i.options,i.priority);break}}function du(i){switch(i.type){case "input":narration.narration.requestInput({type:i.valueType},i.defaultValue);break;case "dialogue":narration.narration.dialogue=void 0;break}}function pu(i){switch(i.operationType){case "play":i.url?sound.sound.play(i.alias,i.url,i.props):sound.sound.play(i.alias,i.props);break;case "stop":switch(i.type){case "sound":sound.sound.stop(i.alias);break;case "all":sound.sound.stopAll();break}break;case "pause":switch(i.type){case "sound":sound.sound.pause(i.alias);break;case "channel":sound.sound.findChannel(i.alias).pauseAll();break;case "all":sound.sound.pauseAll();break}break;case "resume":switch(i.type){case "sound":sound.sound.resume(i.alias);break;case "channel":sound.sound.findChannel(i.alias).resumeAll();break;case "all":sound.sound.resumeAll();break}break;case "edit":Object.entries(i.props).forEach(([e,t])=>{let n=sound.sound.find(i.alias);n&&(e==="volume"?n.volume.value=t:n.paused=t);});break}}var ia="___param___",Dd=class G{static init(e){e.loadAssets&&(G._loadAssets=e.loadAssets),e.soundOperation&&(G._soundOperation=e.soundOperation),e.imageOperation&&(G._imageOperation=e.imageOperation),e.videoOperation&&(G._videoOperation=e.videoOperation),e.imageContainerOperation&&(G._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(G._textOperation=e.textOperation),e.canvasElementOperation&&(G._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(G._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(G._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(G._narrationOperation=e.narrationOperation),e.effectOperation&&(G._effectOperation=e.effectOperation),e.animateOperation&&(G._animateOperation=e.animateOperation),e.getLogichValue&&(G._getLogichValue=e.getLogichValue),e.getConditionalStep&&(G._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return G._loadAssets}static _soundOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return G._soundOperation}static _imageOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return G._imageOperation}static _videoOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return G._videoOperation}static _imageContainerOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return G._imageContainerOperation}static _textOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return G._textOperation}static _canvasElementOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return G._canvasElementOperation}static _setStorageValue=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return G._setStorageValue}static _setInitialStorageValue=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return G._setInitialStorageValue}static _narrationOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return G._narrationOperation}static _effectOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return G._effectOperation}static _animateOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return G._animateOperation}static _getLogichValue=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return G._getLogichValue}static _getConditionalStep=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return G._getConditionalStep}};function bd(i,e){if(e&&typeof e=="object"&&typeof i.functionName=="string"&&i.functionName in e){let t=e[i.functionName];if(typeof t=="function"){let n=i.args.map(r=>Dd.getLogichValue(r,e));return t(...n)}else q.warn(`getLogichValue function ${i.functionName} not found in props`);}}function fu(i,e){let t=_.getLogichValue(i,e);return t&&typeof t=="object"&&"type"in t?_.getLogichValue(t,e):t}function mu(i,e={}){let t=fu(i.value,e);switch(i.storageType){case "flagStorage":storage.storage.setFlag(i.key,i.value);break;case "storage":storage.storage.set(i.key,t);break;case "tempstorage":storage.storage.setTempVariable(i.key,t);break;case "params":{let n=storage.storage.get(`${ia}${narration.narration.openedLabels.length-1}`)||[];n.length>i.key&&(n[i.key]=t),storage.storage.setTempVariable(`${ia}${narration.narration.openedLabels.length-1}`,n);break}}}function gu(i,e={}){let t=fu(i.value,e);switch(i.storageType){case "storage":case "tempstorage":storage.storage.default={[i.key]:t};break}}function Cu(i,e={}){let t=yu(i,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return xd(t,e);case "arithmetic":case "arithmeticsingle":return Ad(t,e);case "compare":case "union":return wd(t,e);case "function":return bd(t,e)}return t}function Ad(i,e){let t=_.getLogichValue(i.leftValue,e);switch(i.type){case "arithmetic":{let n=_.getLogichValue(i.rightValue,e);switch(i.operator){case "*":return t*n;case "/":return t/n;case "+":return typeof t=="string"||typeof n=="string"?`${t}${n}`:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:Array.isArray(t)?[...t,n]:Array.isArray(n)?[t,...n]:t+n;case "-":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>!n.includes(r));if(Array.isArray(t))return t.filter(r=>r!==n);if(Array.isArray(n)){q.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-n;case "%":return t%n;case "POW":return t**n;case "RANDOM":return narration.narration.getRandomNumber(t,n);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>n.includes(r));q.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:q.warn("getValueFromArithmeticOperations unknown operator",i);return}}case "arithmeticsingle":switch(i.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function xd(i,e){if(i&&typeof i=="object"&&"type"in i&&i.type==="value"&&i.storageOperationType==="get")switch(i.storageType){case "storage":case "tempstorage":return i.key==="_input_value_"?narration.narration.inputValue:storage.storage.get(i.key);case "flagStorage":return storage.storage.getFlag(i.key);case "label":return narration.narration.getTimesLabelOpened(i.label);case "choice":return narration.narration.getTimesChoiceMade(i.index);case "logic":return _.getLogichValue(i.operation,e);case "params":{let t=storage.storage.get(`${ia}${narration.narration.openedLabels.length-1}`)||[];if(t&&t.length>i.key)return t[i.key];q.warn("getValue params not found");return}}return i}function wd(i,e){if(!i)return false;if(typeof i!="object"||!("type"in i))return !!i;switch(i.type){case "compare":{let t=_.getLogichValue(i.leftValue,e),n=_.getLogichValue(i.rightValue,e);switch(i.operator){case "==":return Array.isArray(t)&&Array.isArray(n)?t.length===n.length&&t.every(r=>n.includes(r)):t===n;case "!=":return Array.isArray(t)&&Array.isArray(n)?t.length!==n.length||!t.every(r=>n.includes(r)):t!==n;case "<":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<0:Array.isArray(t)&&Array.isArray(n)?t.length<n.length:t<n;case "<=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<=0:Array.isArray(t)&&Array.isArray(n)?t.length<=n.length:t<=n;case ">":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>0:Array.isArray(t)&&Array.isArray(n)?t.length>n.length:t>n;case ">=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>=0:Array.isArray(t)&&Array.isArray(n)?t.length>=n.length:t>=n;case "CONTAINS":return Array.isArray(t)&&Array.isArray(n)?n.every(r=>t.includes(r)):Array.isArray(t)?t.includes(n):t.toString().includes(n.toString())}break}case "value":{let t=_.getLogichValue(i,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return _d(i,e)}return !!i}function _d(i,e){if(i.unionType==="not"){let n=Cu(i.condition,e);return Array.isArray(n)?n.length===0:n&&typeof n=="object"?Object.keys(n).length===0:!n}let t=n=>_.getLogichValue(n,e)||false;return i.unionType==="and"?i.conditions.every(t):i.conditions.some(t)}function Od(i,e){return Math.floor(Math.random()*(e-i+1)+i)}function yu(i,e={}){if(Array.isArray(i)||!i)return i;if(i&&typeof i=="object"&&"type"in i)switch(i.type){case "resulttocombine":return Td(i,e);case "ifelse":return _.getLogichValue(i.condition,e)?_.getLogichValue(i.then,e):_.getLogichValue(i.else,e);case "stepswitch":{let t=_.getLogichValue(i.elements,e)||[];if(t.length===0){q.error("getValueFromConditionalStatements elements.length === 0");return}switch(i.choiceType){case "random":{let n=Od(0,t.length-1);return _.getLogichValue(t[n],e)}case "loop":{let n=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return n>t.length-1?(n=n%t.length,_.getLogichValue(t[n],e)):_.getLogichValue(t[n],e)}case "sequential":{let n,r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return i.end==="lastItem"&&(n=_.getLogichValue(t[t.length-1],e)),r>t.length-1?n:_.getLogichValue(t[r],e)}case "sequentialrandom":{let n=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:i.nestedId,onceOnly:true});if(n===void 0&&i.end==="lastItem"){let r=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(i.nestedId);if(!r?.usedRandomNumbers){q.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=r.usedRandomNumbers[`0-${t.length-1}`];return _.getLogichValue(t[a[a.length-1]],e)}if(n===void 0){q.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return _.getLogichValue(t[n],e)}}}}return i}function Si(i,e={}){if(i.conditionalStep){let t=pixiVn.createExportableElement(_.getLogichValue(i.conditionalStep,e));if(t?.glueEnabled===void 0&&delete t?.glueEnabled,t?.goNextStep===void 0&&delete t?.goNextStep,t?.end===void 0&&delete t?.end,t?.choices===void 0&&delete t?.choices,t?.dialogue===void 0&&delete t?.dialogue,t?.labelToOpen===void 0&&delete t?.labelToOpen,t?.operations===void 0&&delete t?.operations,t){let n={...i,conditionalStep:void 0,...t};return Si(n,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return i}function Td(i,e){let t=i.firstItem,n=(i.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>_.getLogichValue(s,e)):[_.getLogichValue(a,e)]),r=t?[t,...n]:n;if(r.length===0){q.warn("combinateResult toCheck.length === 0");return}if(typeof r[0]=="string")return Ve.t(r);if(typeof r[0]=="object"){let a=r,s,o=false,l=a.map((C,d)=>{C=Si(C,e);let E=_.getLogichValue(C.dialogue,e)||"";return d===0?(s=_.getLogichValue(C.glueEnabled,e)||false,E):(typeof E=="object"&&"text"in E&&(E=`${E.character}: ${E.text}`),s===false&&o&&(E=`
65
65
 
66
- ${S}`),S&&(o=true),s=x.getLogichValue(m.glueEnabled,e)||false,S)}),u=x.getLogichValue(l[0],e),h=typeof u=="object"&&"character"in u?u.character:void 0,c=l.flatMap(m=>{let d;m&&typeof m=="object"&&"text"in m?d=m.text:d=m;let S;return Array.isArray(d)?S=d.map(g=>{let E=x.getLogichValue(g,e);return me.t(`${E}`)}):S=x.getLogichValue(d,e)||"",me.t(S)}),p=a.find(m=>m.end),f=a.find(m=>m.choices),y=false,C=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),y=a[a.length-1].glueEnabled,C=a.reverse().find(m=>!(m.operations&&(!m.dialogue||!m.choices)))?.goNextStep);let A=a.find(m=>m.labelToOpen),b=[];return a.forEach(m=>{m.operations&&(b=[...b,...m.operations]);}),{dialogue:h?{character:h,text:c}:c,end:p?.end,choices:f?.choices,glueEnabled:y,goNextStep:C,labelToOpen:A?.labelToOpen,operations:b}}}var Fi;(i=>{let e=new Set;function t(a){e.add(a);}i.add=t;function n(){e.clear();}i.clear=n;function r(a,s={}){let o=h=>Nu(h,s)??void 0,l=Vu(a,s);if(e.size===0)return o(l);let u=o;for(let h of e){let c=u;u=p=>h(p,c)??void 0;}return u(l)}i.getLogichValue=r;})(Fi||(Fi={}));var tp=Object.create,ya=Object.defineProperty,np=Object.getOwnPropertyDescriptor,ip=Object.getOwnPropertyNames,rp=Object.getPrototypeOf,sp=Object.prototype.hasOwnProperty,ap=(i,e,t)=>e in i?ya(i,e,{enumerable:true,configurable:true,writable:true,value:t}):i[e]=t,ku=(i=>typeof Wt<"u"?Wt:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof Wt<"u"?Wt:e)[t]}):i)(function(i){if(typeof Wt<"u")return Wt.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')}),Bu=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),op=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ip(e))!sp.call(i,r)&&r!==t&&ya(i,r,{get:()=>e[r],enumerable:!(n=np(e,r))||n.enumerable});return i},lp=(i,e,t)=>(t=i!=null?tp(rp(i)):{},op(ya(t,"default",{value:i,enumerable:true}),i)),fe=(i,e,t)=>ap(i,typeof e!="symbol"?e+"":e,t),up=Bu((i,e)=>{(function(t,n){typeof i=="object"?e.exports=i=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(i,function(){var t=t||(function(n,r){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof ku=="function")try{a=ku("crypto");}catch{}var s=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||(function(){function m(){}return function(d){var S;return m.prototype=d,S=new m,m.prototype=null,S}})(),l={},u=l.lib={},h=u.Base=(function(){return {extend:function(m){var d=o(this);return m&&d.mixIn(m),(!d.hasOwnProperty("init")||this.init===d.init)&&(d.init=function(){d.$super.init.apply(this,arguments);}),d.init.prototype=d,d.$super=this,d},create:function(){var m=this.extend();return m.init.apply(m,arguments),m},init:function(){},mixIn:function(m){for(var d in m)m.hasOwnProperty(d)&&(this[d]=m[d]);m.hasOwnProperty("toString")&&(this.toString=m.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),c=u.WordArray=h.extend({init:function(m,d){m=this.words=m||[],d!=r?this.sigBytes=d:this.sigBytes=m.length*4;},toString:function(m){return (m||f).stringify(this)},concat:function(m){var d=this.words,S=m.words,g=this.sigBytes,E=m.sigBytes;if(this.clamp(),g%4)for(var _=0;_<E;_++){var T=S[_>>>2]>>>24-_%4*8&255;d[g+_>>>2]|=T<<24-(g+_)%4*8;}else for(var N=0;N<E;N+=4)d[g+N>>>2]=S[N>>>2];return this.sigBytes+=E,this},clamp:function(){var m=this.words,d=this.sigBytes;m[d>>>2]&=4294967295<<32-d%4*8,m.length=n.ceil(d/4);},clone:function(){var m=h.clone.call(this);return m.words=this.words.slice(0),m},random:function(m){for(var d=[],S=0;S<m;S+=4)d.push(s());return new c.init(d,m)}}),p=l.enc={},f=p.Hex={stringify:function(m){for(var d=m.words,S=m.sigBytes,g=[],E=0;E<S;E++){var _=d[E>>>2]>>>24-E%4*8&255;g.push((_>>>4).toString(16)),g.push((_&15).toString(16));}return g.join("")},parse:function(m){for(var d=m.length,S=[],g=0;g<d;g+=2)S[g>>>3]|=parseInt(m.substr(g,2),16)<<24-g%8*4;return new c.init(S,d/2)}},y=p.Latin1={stringify:function(m){for(var d=m.words,S=m.sigBytes,g=[],E=0;E<S;E++){var _=d[E>>>2]>>>24-E%4*8&255;g.push(String.fromCharCode(_));}return g.join("")},parse:function(m){for(var d=m.length,S=[],g=0;g<d;g++)S[g>>>2]|=(m.charCodeAt(g)&255)<<24-g%4*8;return new c.init(S,d)}},C=p.Utf8={stringify:function(m){try{return decodeURIComponent(escape(y.stringify(m)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(m){return y.parse(unescape(encodeURIComponent(m)))}},A=u.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new c.init,this._nDataBytes=0;},_append:function(m){typeof m=="string"&&(m=C.parse(m)),this._data.concat(m),this._nDataBytes+=m.sigBytes;},_process:function(m){var d,S=this._data,g=S.words,E=S.sigBytes,_=this.blockSize,T=_*4,N=E/T;m?N=n.ceil(N):N=n.max((N|0)-this._minBufferSize,0);var te=N*_,be=n.min(te*4,E);if(te){for(var rn=0;rn<te;rn+=_)this._doProcessBlock(g,rn);d=g.splice(0,te),S.sigBytes-=be;}return new c.init(d,be)},clone:function(){var m=h.clone.call(this);return m._data=this._data.clone(),m},_minBufferSize:0});u.Hasher=A.extend({cfg:h.extend(),init:function(m){this.cfg=this.cfg.extend(m),this.reset();},reset:function(){A.reset.call(this),this._doReset();},update:function(m){return this._append(m),this._process(),this},finalize:function(m){m&&this._append(m);var d=this._doFinalize();return d},blockSize:16,_createHelper:function(m){return function(d,S){return new m.init(S).finalize(d)}},_createHmacHelper:function(m){return function(d,S){return new b.HMAC.init(m,S).finalize(d)}}});var b=l.algo={};return l})(Math);return t});}),hp=Bu((i,e)=>{(function(t,n){typeof i=="object"?e.exports=i=n(up()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(i,function(t){return (function(){var n=t,r=n.lib,a=r.WordArray,s=r.Hasher,o=n.algo,l=[],u=o.SHA1=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(h,c){for(var p=this._hash.words,f=p[0],y=p[1],C=p[2],A=p[3],b=p[4],m=0;m<80;m++){if(m<16)l[m]=h[c+m]|0;else {var d=l[m-3]^l[m-8]^l[m-14]^l[m-16];l[m]=d<<1|d>>>31;}var S=(f<<5|f>>>27)+b+l[m];m<20?S+=(y&C|~y&A)+1518500249:m<40?S+=(y^C^A)+1859775393:m<60?S+=(y&C|y&A|C&A)-1894007588:S+=(y^C^A)-899497514,b=A,A=C,C=y<<30|y>>>2,y=f,f=S;}p[0]=p[0]+f|0,p[1]=p[1]+y|0,p[2]=p[2]+C|0,p[3]=p[3]+A|0,p[4]=p[4]+b|0;},_doFinalize:function(){var h=this._data,c=h.words,p=this._nDataBytes*8,f=h.sigBytes*8;return c[f>>>5]|=128<<24-f%32,c[(f+64>>>9<<4)+14]=Math.floor(p/4294967296),c[(f+64>>>9<<4)+15]=p,h.sigBytes=c.length*4,this._process(),this._hash},clone:function(){var h=s.clone.call(this);return h._hash=this._hash.clone(),h}});n.SHA1=s._createHelper(u),n.HmacSHA1=s._createHmacHelper(u);})(),t.SHA1});}),Ru="___param___",se;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(se||(se={}));var Oe=class ${static init(e){e.loadAssets&&($._loadAssets=e.loadAssets),e.soundOperation&&($._soundOperation=e.soundOperation),e.imageOperation&&($._imageOperation=e.imageOperation),e.videoOperation&&($._videoOperation=e.videoOperation),e.imageContainerOperation&&($._imageContainerOperation=e.imageContainerOperation),e.textOperation&&($._textOperation=e.textOperation),e.canvasElementOperation&&($._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&($._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&($._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&($._narrationOperation=e.narrationOperation),e.effectOperation&&($._effectOperation=e.effectOperation),e.animateOperation&&($._animateOperation=e.animateOperation),e.getLogichValue&&($._getLogichValue=e.getLogichValue),e.getConditionalStep&&($._getConditionalStep=e.getConditionalStep);}static get loadAssets(){return $._loadAssets}static get soundOperation(){return $._soundOperation}static get imageOperation(){return $._imageOperation}static get videoOperation(){return $._videoOperation}static get imageContainerOperation(){return $._imageContainerOperation}static get textOperation(){return $._textOperation}static get canvasElementOperation(){return $._canvasElementOperation}static get setStorageValue(){return $._setStorageValue}static get setInitialStorageValue(){return $._setInitialStorageValue}static get narrationOperation(){return $._narrationOperation}static get effectOperation(){return $._effectOperation}static get animateOperation(){return $._animateOperation}static get getLogichValue(){return $._getLogichValue}static get getConditionalStep(){return $._getConditionalStep}};fe(Oe,"_loadAssets",()=>{}),fe(Oe,"_soundOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_imageOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_videoOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_imageContainerOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_textOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_canvasElementOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_setStorageValue",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_setInitialStorageValue",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_narrationOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_effectOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_animateOperation",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_getLogichValue",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),fe(Oe,"_getConditionalStep",()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")});var cp=Oe;function dp(i,e){if(e&&typeof e=="object"&&typeof i.functionName=="string"&&i.functionName in e){let t=e[i.functionName];if(typeof t=="function"){let n=i.args.map(r=>cp.getLogichValue(r,e));return t(...n)}else se.warn(`getLogichValue function ${i.functionName} not found in props`);}}function pp(i,e={}){let t="";return i.values.forEach(n=>{if(typeof n=="string")t+=n;else {let r=x.getLogichValue(n,e);t+=`${r}`;}}),t}async function Wu(i,e,t){let n=x.getLogichValue(i,e);if(n)switch(n.type){case "sound":x.soundOperation(n);break;case "assets":case "bundle":await x.loadAssets(n);break;case "image":await x.imageOperation(n);break;case "video":await x.videoOperation(n);break;case "imagecontainer":await x.imageContainerOperation(n);break;case "text":await x.textOperation(n);break;case "canvaselement":await x.canvasElementOperation(n);break;case "value":x.setStorageValue(n,e);break;case "operationtoconvert":if(t){let r=pp(n,e),a=await t(r);a&&await Wu(a,e,t);}break;case "input":case "dialogue":x.narrationOperation(n);break;case "shake":await x.effectOperation(n);break;case "animate":case "animate-sequence":x.animateOperation(n);break;case "function":await dp(n,e);break}}function Lu(i){let e=x.getLogichValue(i,{});e&&e.type==="value"&&e.storageOperationType==="set"&&(e.storageType==="storage"||e.storageType==="tempstorage")&&x.setInitialStorageValue(e);}var fp=lp(hp()),gp=class extends narration.LabelAbstract{constructor(i,e,t,n={}){t||(t={}),t.onLoadingLabel=async()=>{for(let r of e){let a;if(typeof r=="function"?a=r():a=r,a=x.getConditionalStep(a),a.operations)try{let s=a.operations.map(o=>x.loadAssets(o));await Promise.all(s);}catch(s){se.error("The operation in the onLoadingLabel function of the label has an error:",s);}}},super(i,t),fe(this,"_steps"),fe(this,"operationStringConvert"),fe(this,"skipEmptyDialogs",false),this._steps=e,this.operationStringConvert=n.operationStringConvert,this.skipEmptyDialogs=n.skipEmptyDialogs||false;}get steps(){return this._steps.map(i=>this.stepConverter(i))}get stepCount(){return this._steps.length}getStepById(i){if(i<0||i>=this._steps.length)return;let e=this._steps[i];return this.stepConverter(e)}getStepSha(i){if(i<0||i>=this.steps.length)return;let e=this._steps[i];return (0, fp.default)(e.toString().toLocaleLowerCase()).toString()}getDialogueText(i,e){let t="";if(Array.isArray(i)){let n=[];i.forEach(r=>{if(typeof r=="string")n.push(r);else if(r&&typeof r=="object"){let a=x.getLogichValue(r,e);a?(a&&!Array.isArray(a)&&typeof a=="object"&&(a=x.getLogichValue(a,e)||""),Array.isArray(a)?n=n.map(s=>`${s}`).concat(a):n.push(`${a}`)):n.push(`${r}`);}else n.push(`${r}`);}),t=n;}else {let n=x.getLogichValue(i,e);n&&!Array.isArray(n)&&typeof n=="object"&&(n=x.getLogichValue(n,e)),n&&Array.isArray(n)?t=n.map(r=>`${r}`):t=`${n}`;}return t}getDialogue(i,e){if(i==null)return;let t=x.getLogichValue(i,e);return t==null?`${t}`:typeof t=="object"&&"character"in t&&"text"in t?{character:t.character,text:me.t(this.getDialogueText(t.text,e))}:me.t(this.getDialogueText(t,e))}getChoices(i,e){return x.getLogichValue(i,e)?.map(t=>x.getLogichValue(t,e)).filter(t=>t!==void 0)}stepConverter(i){return async e=>{let t=typeof i=="function"?i():i;t=pixiVn.createExportableElement(t),t=x.getConditionalStep(t,e);let n=this.operationStringConvert?p=>this.operationStringConvert(p,t,e):void 0,{operations:r=[]}=t;for(let p of r)await Wu(p,e,n);let{labelToOpen:a=[]}=t,s=this.getChoices(t.choices,e),o=x.getLogichValue(t.glueEnabled,e),l=this.getDialogue(t.dialogue,e),u=[];Array.isArray(a)||(a=[a]),a.forEach(p=>{let f=x.getLogichValue(p,e);f&&u.push(f);});let h=x.getLogichValue(t.goNextStep,e),c=x.getLogichValue(t.end,e);if(s){let p=s.map(f=>{let y="";if(Array.isArray(f.text)){let C=[];f.text.forEach(A=>{if(typeof A=="string")C.push(me.t(A));else if(A&&typeof A=="object"){let b=x.getLogichValue(A,e);b&&!Array.isArray(b)&&typeof b=="object"&&(b=x.getLogichValue(b,e)||""),b&&(Array.isArray(b)?C=C.concat(me.t(b)):C.push(me.t(b)));}}),y=C;}else typeof f.text=="string"&&(y=me.t(f.text));return {label:f.label,text:y,props:f.props,type:f.type,oneTime:f.oneTime,onlyHaveNoChoice:f.onlyHaveNoChoice,autoSelect:f.autoSelect}});narration.narration.choices=p;}else narration.narration.choices=void 0;l!==void 0&&(narration.narration.dialogue=l,this.skipEmptyDialogs&&typeof l=="string"&&(l===""||RegExp(/^\s+$/).test(l))&&(h=true)),o?narration.narration.dialogGlue=true:o===false&&(narration.narration.dialogGlue=false);for(let p of u){let f=p.label;typeof f=="object"&&(f=x.getLogichValue(f,e)||"");let y=p.params?.map(C=>x.getLogichValue(C,e));e={...e,...p.props},p.type==="jump"?(narration.narration.openedLabels.length>0&&narration.narration.closeCurrentLabel(),storage.storage.setTempVariable(`${Ru}${narration.narration.openedLabels.length}`,y),await narration.narration.call(f,e)):(storage.storage.setTempVariable(`${Ru}${narration.narration.openedLabels.length}`,y),await narration.narration.call(f,e));}c==="game_end"?(narration.narration.closeAllLabels(),await narration.narration.continue(e,{runNow:true})):c==="label_end"&&narration.narration.closeCurrentLabel(),h&&await narration.narration.continue(e,{runNow:true});}}};async function va(i,e={}){if(!Array.isArray(i))if(typeof i=="object"||typeof i=="string")i=[i];else {se.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let t=i.map(a=>{if(typeof a=="string")try{return JSON.parse(a)}catch(s){return se.error("Error parsing imported Pixi'VN JSON",s),{}}return a}),n=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)s.type==="value"&&(typeof s.value!="object"||!s.value||!("type"in s.value))&&Lu(s);return Promise.resolve()});await Promise.all(n);let r=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)(s.type!=="value"||s.type==="value"&&typeof s.value=="object"&&s.value&&"type"in s.value)&&Lu(s);if(a.labels){let s=a.labels;for(let o in s)try{let l=s[o],u=new gp(o,l,void 0,e);narration.RegisteredLabels.add(u);}catch(l){se.error(`Error creating JSON label ${o}`,l);}}return Promise.resolve()});await Promise.all(r);}var Cp=Object.defineProperty,yp=(i,e,t)=>e in i?Cp(i,e,{enumerable:true,configurable:true,writable:true,value:t}):i[e]=t,Ie=(i,e,t)=>yp(i,typeof e!="symbol"?e+"":e,t),vp={version:"1.13.9"},Sp="___param___",qu=`https://pixi-vn.com/schemas/${vp.version}/schema.json`,Mu=["==","!=","<","<=",">",">=","CONTAINS"],Z;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Z||(Z={}));var Pe=class J{static init(e){e.loadAssets&&(J._loadAssets=e.loadAssets),e.soundOperation&&(J._soundOperation=e.soundOperation),e.imageOperation&&(J._imageOperation=e.imageOperation),e.videoOperation&&(J._videoOperation=e.videoOperation),e.imageContainerOperation&&(J._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(J._textOperation=e.textOperation),e.canvasElementOperation&&(J._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(J._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(J._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(J._narrationOperation=e.narrationOperation),e.effectOperation&&(J._effectOperation=e.effectOperation),e.animateOperation&&(J._animateOperation=e.animateOperation),e.getLogichValue&&(J._getLogichValue=e.getLogichValue),e.getConditionalStep&&(J._getConditionalStep=e.getConditionalStep);}static get loadAssets(){return J._loadAssets}static get soundOperation(){return J._soundOperation}static get imageOperation(){return J._imageOperation}static get videoOperation(){return J._videoOperation}static get imageContainerOperation(){return J._imageContainerOperation}static get textOperation(){return J._textOperation}static get canvasElementOperation(){return J._canvasElementOperation}static get setStorageValue(){return J._setStorageValue}static get setInitialStorageValue(){return J._setInitialStorageValue}static get narrationOperation(){return J._narrationOperation}static get effectOperation(){return J._effectOperation}static get animateOperation(){return J._animateOperation}static get getLogichValue(){return J._getLogichValue}static get getConditionalStep(){return J._getConditionalStep}};Ie(Pe,"_loadAssets",()=>{}),Ie(Pe,"_soundOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_imageOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_videoOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_imageContainerOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_textOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_canvasElementOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_setStorageValue",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_setInitialStorageValue",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_narrationOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_effectOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_animateOperation",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_getLogichValue",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),Ie(Pe,"_getConditionalStep",()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")});var Ep=Pe;function bp(i,e){if(e&&typeof e=="object"&&typeof i.functionName=="string"&&i.functionName in e){let t=e[i.functionName];if(typeof t=="function"){let n=i.args.map(r=>Ep.getLogichValue(r,e));return t(...n)}else Z.warn(`getLogichValue function ${i.functionName} not found in props`);}}function Gu(i,e={}){let t=$u(i,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return Ap(t,e);case "arithmetic":case "arithmeticsingle":return Dp(t,e);case "compare":case "union":return wp(t,e);case "function":return bp(t,e)}return t}function Dp(i,e){let t=x.getLogichValue(i.leftValue,e);switch(i.type){case "arithmetic":{let n=x.getLogichValue(i.rightValue,e);switch(i.operator){case "*":return t*n;case "/":return t/n;case "+":return typeof t=="string"||typeof n=="string"?`${t}${n}`:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:Array.isArray(t)?[...t,n]:Array.isArray(n)?[t,...n]:t+n;case "-":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>!n.includes(r));if(Array.isArray(t))return t.filter(r=>r!==n);if(Array.isArray(n)){Z.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-n;case "%":return t%n;case "POW":return t**n;case "RANDOM":return narration.narration.getRandomNumber(t,n);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>n.includes(r));Z.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:Z.warn("getValueFromArithmeticOperations unknown operator",i);return}}case "arithmeticsingle":switch(i.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function Ap(i,e){if(i&&typeof i=="object"&&"type"in i&&i.type==="value"&&i.storageOperationType==="get")switch(i.storageType){case "storage":case "tempstorage":return i.key==="_input_value_"?narration.narration.inputValue:storage.storage.get(i.key);case "flagStorage":return storage.storage.getFlag(i.key);case "label":return narration.narration.getTimesLabelOpened(i.label);case "choice":return narration.narration.getTimesChoiceMade(i.index);case "logic":return x.getLogichValue(i.operation,e);case "params":{let t=storage.storage.get(`${Sp}${narration.narration.openedLabels.length-1}`)||[];if(t&&t.length>i.key)return t[i.key];Z.warn("getValue params not found");return}}return i}function wp(i,e){if(!i)return false;if(typeof i!="object"||!("type"in i))return !!i;switch(i.type){case "compare":{let t=x.getLogichValue(i.leftValue,e),n=x.getLogichValue(i.rightValue,e);switch(i.operator){case "==":return Array.isArray(t)&&Array.isArray(n)?t.length===n.length&&t.every(r=>n.includes(r)):t===n;case "!=":return Array.isArray(t)&&Array.isArray(n)?t.length!==n.length||!t.every(r=>n.includes(r)):t!==n;case "<":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<0:Array.isArray(t)&&Array.isArray(n)?t.length<n.length:t<n;case "<=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<=0:Array.isArray(t)&&Array.isArray(n)?t.length<=n.length:t<=n;case ">":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>0:Array.isArray(t)&&Array.isArray(n)?t.length>n.length:t>n;case ">=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>=0:Array.isArray(t)&&Array.isArray(n)?t.length>=n.length:t>=n;case "CONTAINS":return Array.isArray(t)&&Array.isArray(n)?n.every(r=>t.includes(r)):Array.isArray(t)?t.includes(n):t.toString().includes(n.toString())}break}case "value":{let t=x.getLogichValue(i,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return xp(i,e)}return !!i}function xp(i,e){if(i.unionType==="not"){let n=Gu(i.condition,e);return Array.isArray(n)?n.length===0:n&&typeof n=="object"?Object.keys(n).length===0:!n}let t=n=>x.getLogichValue(n,e)||false;return i.unionType==="and"?i.conditions.every(t):i.conditions.some(t)}function _p(i,e){return Math.floor(Math.random()*(e-i+1)+i)}function $u(i,e={}){if(Array.isArray(i)||!i)return i;if(i&&typeof i=="object"&&"type"in i)switch(i.type){case "resulttocombine":return Op(i,e);case "ifelse":return x.getLogichValue(i.condition,e)?x.getLogichValue(i.then,e):x.getLogichValue(i.else,e);case "stepswitch":{let t=x.getLogichValue(i.elements,e)||[];if(t.length===0){Z.error("getValueFromConditionalStatements elements.length === 0");return}switch(i.choiceType){case "random":{let n=_p(0,t.length-1);return x.getLogichValue(t[n],e)}case "loop":{let n=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return n>t.length-1?(n=n%t.length,x.getLogichValue(t[n],e)):x.getLogichValue(t[n],e)}case "sequential":{let n,r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return i.end==="lastItem"&&(n=x.getLogichValue(t[t.length-1],e)),r>t.length-1?n:x.getLogichValue(t[r],e)}case "sequentialrandom":{let n=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:i.nestedId,onceOnly:true});if(n===void 0&&i.end==="lastItem"){let r=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(i.nestedId);if(!r?.usedRandomNumbers){Z.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=r.usedRandomNumbers[`0-${t.length-1}`];return x.getLogichValue(t[a[a.length-1]],e)}if(n===void 0){Z.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return x.getLogichValue(t[n],e)}}}}return i}function Ju(i,e={}){if(i.conditionalStep){let t=pixiVn.createExportableElement(x.getLogichValue(i.conditionalStep,e));if(t?.glueEnabled===void 0&&delete t?.glueEnabled,t?.goNextStep===void 0&&delete t?.goNextStep,t?.end===void 0&&delete t?.end,t?.choices===void 0&&delete t?.choices,t?.dialogue===void 0&&delete t?.dialogue,t?.labelToOpen===void 0&&delete t?.labelToOpen,t?.operations===void 0&&delete t?.operations,t){let n={...i,conditionalStep:void 0,...t};return Ju(n,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return i}function Op(i,e){let t=i.firstItem,n=(i.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>x.getLogichValue(s,e)):[x.getLogichValue(a,e)]),r=t?[t,...n]:n;if(r.length===0){Z.warn("combinateResult toCheck.length === 0");return}if(typeof r[0]=="string")return me.t(r);if(typeof r[0]=="object"){let a=r,s,o=false,l=a.map((m,d)=>{m=Ju(m,e);let S=x.getLogichValue(m.dialogue,e)||"";return d===0?(s=x.getLogichValue(m.glueEnabled,e)||false,S):(typeof S=="object"&&"text"in S&&(S=`${S.character}: ${S.text}`),s===false&&o&&(S=`
67
-
68
- ${S}`),S&&(o=true),s=x.getLogichValue(m.glueEnabled,e)||false,S)}),u=x.getLogichValue(l[0],e),h=typeof u=="object"&&"character"in u?u.character:void 0,c=l.flatMap(m=>{let d;m&&typeof m=="object"&&"text"in m?d=m.text:d=m;let S;return Array.isArray(d)?S=d.map(g=>{let E=x.getLogichValue(g,e);return me.t(`${E}`)}):S=x.getLogichValue(d,e)||"",me.t(S)}),p=a.find(m=>m.end),f=a.find(m=>m.choices),y=false,C=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),y=a[a.length-1].glueEnabled,C=a.reverse().find(m=>!(m.operations&&(!m.dialogue||!m.choices)))?.goNextStep);let A=a.find(m=>m.labelToOpen),b=[];return a.forEach(m=>{m.operations&&(b=[...b,...m.operations]);}),{dialogue:h?{character:h,text:c}:c,end:p?.end,choices:f?.choices,glueEnabled:y,goNextStep:C,labelToOpen:A?.labelToOpen,operations:b}}}var ju;(i=>{let e=new Set;function t(a){e.add(a);}i.add=t;function n(){e.clear();}i.clear=n;function r(a,s={}){let o=h=>Gu(h,s)??void 0,l=$u(a,s);if(e.size===0)return o(l);let u=o;for(let h of e){let c=u;u=p=>h(p,c)??void 0;}return u(l)}i.getLogichValue=r;})(ju||(ju={}));function Ea(){x.init({animateOperation:xu,canvasElementOperation:Au,effectOperation:wu,imageContainerOperation:bu,imageOperation:Su,textOperation:Du,narrationOperation:_u,loadAssets:vu,soundOperation:Ou,videoOperation:Eu,setStorageValue:Tu,setInitialStorageValue:Fu,getLogichValue:Fi.getLogichValue,getConditionalStep:Vi});}var ki="global decl",Gt="___external_value___",Hu=/\[([^\]]+)\]/;var zu=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],Uu=["+","-","/","*","%","POW","RANDOM","L^"],Ku=["INT","FLOOR","FLOAT"];function sn(i,e){if(i.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(i)&&(i=i.split(".").filter(r=>!r.match(/^[0-9]+$/)).join("."),!i.startsWith(".")))return i.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(i)&&i.includes("g-")){let n=i.split("g-");return ba(e)+"_|_"+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(i);)t++,i=i.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(i)&&e){let n=i.substring(1);return ba(e,t)+"_|_"+n.replaceAll(".","_|_")}return i.replaceAll(".","_|_")||ba(e,t).replaceAll(".","_|_")}function ba(i,e=0){let t=i.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var Xu="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function st(i){return i.startsWith("^")&&(i=i.substring(1)),i=i.replaceAll("\\\\",Xu),i=i.replaceAll("\\n",`
69
- `),i=i.replaceAll("\\t"," "),i=i.replaceAll(" "," "),i=i.replaceAll(Xu,"\\\\"),i}function _t(i,e,t,n){let{functions:r}=n;i=i.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return i.forEach(s=>{if(typeof s=="string")switch(s){case "&&":case "||":if(a.length>=2){let o={type:"union",unionType:s==="&&"?"and":"or",conditions:[a[a.length-2],a[a.length-1]]};a.pop(),a.pop(),a.push(o);}break;case "!":if(a.length===0)W.error("Error parsing ink file: Conditional statement is not valid",i);else {let o={type:"union",unionType:"not",condition:a[a.length-1]};a[a.length-1]=o;}break;case "!?":if(a.length>1){let o={type:"union",unionType:"not",condition:{type:"compare",operator:"CONTAINS",leftValue:a[a.length-2],rightValue:a[a.length-1]}};a.pop(),a.pop(),a.push(o);}else W.error("Error parsing ink file: Conditional statement is not valid",i);break;default:if(Mu.includes(s))if(a.length<2)W.error("Error parsing ink file: Conditional statement is not valid",i);else {let o={type:"compare",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(Uu.includes(s))if(a.length<2)W.error("Error parsing ink file: Conditional statement is not valid",i);else {s==="L^"&&(s="INTERSECTION");let o={type:"arithmetic",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(Ku.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(st(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),l=o.pop(),u=o.pop();if(u===void 0||l===void 0){W.error("Error parsing ink file: Conditional statement is not valid",i);return}let h=Number(u),c=o.join(".");if(c.includes("^.")){let f=c.split("."),y=f[f.length-1].replaceAll(".","_|_");f.pop(),c=`${f.join(".")}.${y}`,l.includes("c-")&&(c=c+"_|_"+l);}else c=c.replaceAll(".","_|_");let p=sn(c,e);if(!p)return;a.push({type:"compare",leftValue:Da(p),operator:">=",rightValue:{type:"value",value:h}});}else {let o=sn(s["CNT?"],e);if(!o)return;a.push(Da(o));}else if(typeof s=="object"&&"VAR?"in s)a.push($t({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],l=r.find(h=>h.name===o);if(!l){W.error(`Error parsing ink file: Function ${o} is not defined`,i);return}let u=[];for(let h=0;h<l.args;h++)a.length!==0&&u.push(a.pop());a.push({type:"function",functionName:o,args:u.reverse()});}else if(typeof s=="object"&&"^->"in s)s["^->"].includes("$r")||a.push(s["^->"]);else if(typeof s=="object"&&"list"in s){let o=Object.values(s.list).map(l=>l);a.push(o);}else a.push(s);}),a}function Aa(i,e,t,n){return _t(i,e,t,n)}function $t(i,e,t){let{key:n,defaultType:r}=i,a=e.indexOf(n);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:r,key:n}}function Bn(i,e,t){let{key:n,value:r,defaultType:a,artmeticValue:s}=i,o=e.indexOf(n);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:r}];if(s){if(typeof r=="object"&&"list"in r){let l=Object.values(r.list).map(u=>u);return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:l}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:r}]}else if(typeof r=="object"){if("list"in r&&typeof r.list=="object"){if("origins"in r&&Array.isArray(r.origins)&&r.origins.length>0)return r.origins.reduce(l=>(l.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(t.enums[n])}),Object.entries(t.enums[n]).forEach(([u,h])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${u}`,value:h});}),l),[]);{let l=new Set,u=Object.entries(r.list).reduce((h,[c,p])=>{let[f,y]=c.split(".");return h.push({type:"value",storageOperationType:"set",storageType:a,key:y,value:p}),l.add(f),h},[]);return l.forEach(h=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:h,value:Object.values(t.enums[h])});}),n in t.enums?Object.entries(t.enums[n]).forEach(([h,c])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${h}`,value:c});}):u.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(r.list)}),u}}else if(typeof r=="object"&&"VAR?"in r){if(typeof r["VAR?"]=="string"&&r["VAR?"].includes(".")){let[l,u]=r["VAR?"].split(".");if(l in t.enums&&u in t.enums[l])return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:t.enums[l][u]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:$t({key:r["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:r}]}function Da(i){return {type:"value",storageType:"label",storageOperationType:"get",label:i}}function wa(i,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(i)?"call":"jump"}function Ri(i,e){if(e){if(typeof e=="string")e.startsWith("^")&&i.push(st(e));else if(typeof e=="object"&&"type"in e)switch(e.type){case "value":case "function":console.warn("Warning: trying to add a value or function operation as text. This is likely a mistake, so it will be ignored.");break;default:i.push(e);}}}function xa(i,e,t,n,r,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:l=false}=a;return Tp(i,e,t,n,r,{isNewLine:s,isHashtagScript:o,isThreads:l})}function Tp(i,e,t,n,r,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:l}=a;if(o){if(Array.isArray(e)&&e.length>0){let u={goNextStep:true},h=[];try{if(e.length===1&&typeof e[0]=="string"&&!e[0].match(Hu)){let c=e[0],p=O.convertTagTolist(c),f=O.convertOperation(p,u);f&&(f.$origin=c,h.push(f));}}catch{}h.length===0&&h.push({type:"operationtoconvert",values:e}),i.push({...u,operations:h});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&i.length>0){let u=i[i.length-1];!u.glueEnabled&&!u.operations&&!u.labelToOpen&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),i[i.length-1]=u;}typeof e=="string"?i.push(Fp(st(e),n.characterIds)):i.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")i.push({end:"game_end"});else if(e==="done")i.push({end:"label_end",goNextStep:true});else if(e==="<>")if(i.length>0){let u=i[i.length-1];u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true),i[i.length-1]=u;}else i.push({glueEnabled:true,goNextStep:false});}else if(typeof e=="object"){if("type"in e)switch(e.type){case "value":e.storageOperationType==="set"?(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=st(e.value)),i.push({goNextStep:true,operations:[e]})):console.warn("Warning: trying to add a value get operation as step. This is likely a mistake, so it will be ignored.");break;case "function":i.push({goNextStep:true,operations:[e]});break;default:if(!s&&i.length>0){let u=i[i.length-1];!u.glueEnabled&&!u.operations&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),i[i.length-1]=u;}i.push({conditionalStep:e});}else if("->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&i.length>0&&i[i.length-1]?.dialogue===void 0&&(u=void 0),!s&&i.length>0){let h=i[i.length-1];h.labelToOpen||(h.goNextStep=true),i[i.length-1]=h;}if(e.params&&e.params.length===0&&delete e.params,e.var)i.push({labelToOpen:{label:$t({key:e["->"],defaultType:"storage"},r),type:l?"call":"jump",params:e.params},glueEnabled:u});else {let h=sn(e["->"],t);if(!h)return;i.push({labelToOpen:{label:h,type:wa(h,l),params:e.params},glueEnabled:u});}}else if("->t->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&i.length>0&&i[i.length-1]?.dialogue===void 0&&(u=void 0),!s&&i.length>0){let c=i[i.length-1];c.labelToOpen||(c.goNextStep=true),i[i.length-1]=c;}e.params&&e.params.length===0&&delete e.params;let h=sn(e["->t->"],t);if(!h)return;i.push({labelToOpen:{label:h,type:"call",params:e.params},glueEnabled:u});}}}function Fp(i,e){let t;if(i.includes(": ")){let n=i.split(": "),r=n[0],a=n.slice(1).join(": ");(e?.has(r)||characters.RegisteredCharacters.has(r))&&(t=r,i=a);}return t?{dialogue:{character:t,text:i}}:{dialogue:i}}function _a(i,e,t,n=true,r=false){return Np(i,e,t,n,r)}function Np(i,e,t,n,r=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?i.push(st(e)):i.push(e):typeof e=="object"&&"type"in e&&i.push(e));}function Li(i,e,t,n){if(i.length===0){W.error("Error parsing ink file: Arithmetic statement is not valid",i);return}let r=_t(i,e,t,n);if(r.length===1){let a=r[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function an(i,e,t,n="",r,a,s=void 0){let o=[],l="sequential",u=false,h=true;i.forEach(f=>{f==="%"&&(l="loop"),f==="seq"&&(l="random"),f==="MIN"&&(u=true);});let c=i[i.length-1];return Object.keys(c).forEach(f=>{let y=c[f];if(Array.isArray(y)&&y.length>3){y=y.slice(1,y.length-2);let C=[];Ot(y,n,r,C,e,e,t,on,s,true,a),C.length===1?o.push(C[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:C});}else Array.isArray(y)&&y.length===3&&(h=false);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:h?"lastItem":void 0,nestedId:s}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:h?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:l}}function Ot(i,e,t,n=[],r,a,s,o,l=void 0,u=true,h=[]){let c=false,p=[],f=false,y=false,C=false,A=[],b=[];if(t.preDialog[e]&&(u=false,r(n,`^${t.preDialog[e].text}`,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),t.preDialog[e].glue&&r(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),delete t.preDialog[e]),i.includes("visit")){let d=an(i,a,s,e,t,h,l);d&&(!u&&n.length>0&&r(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),r(n,d,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}));return}let m=i[0];if(m&&typeof m=="object"&&"temp="in m){for(;i[0]&&typeof i[0]=="object"&&"temp="in i[0];)h.push(i[0]["temp="]),i.shift();h=h.reverse();}if(i.forEach((d,S)=>{if(y){if(typeof d=="string"&&d==="/#"){let g=[];Ot(b,e,t,g,_a,_a,s,o,l,u),r(n,g,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),y=false,b=[];}else b.push(d);return}else if(c)if(Array.isArray(d))p.push(d);else if(d&&typeof d=="object")"CNT?"in d?S>0&&i[S-1]==="ev"?(f=true,A.push(d)):f?A.push(d):(p.push(d),u=false):"VAR="in d||"temp="in d?Bn({key:"VAR="in d?d["VAR="]:d["temp="],value:i[S-1],defaultType:"VAR="in d?"storage":"tempstorage"},h,t).forEach(E=>{if(E.value&&typeof E.value=="string"&&E.value==="/str"&&(E.value=i[S-2]),E.value&&typeof E.value=="object"&&"^->"in E.value&&(E.value=E.value["^->"]),p.length>1){let _=Li(p,e,h,t);p=[],_&&typeof _=="object"&&"type"in _&&_.type==="value"&&"storageType"in _&&_.storageType==="logic"&&(E.value=_.operation);}(typeof E.key!="string"||!E.key.includes("$r"))&&(r(n,E,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),u=true);}):"VAR?"in d?p.push(d):"^->"in d?d["^->"].includes("$r")||p.push(d):("f()"in d||"list"in d&&typeof d.list=="object")&&p.push(d);else switch(d){case "/ev":f&&A.push(d),c=false,p.push(d);break;case "out":if(p.length>0){let g=p[p.length-1];if(g&&typeof g=="object"&&"VAR?"in g){p.pop();let E=$t({key:g["VAR?"],defaultType:"storage"},h);r(n,E,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C});}else {let E=[];for(;p.length>0&&p[p.length-1]!=="/ev";)E.push(p.pop());E=E.reverse();let _=Li(E,e,h,t);p=[],_&&typeof _=="object"&&"type"in _&&_.type==="value"&&"storageType"in _&&_.storageType==="logic"?r(n,{storageOperationType:"get",storageType:"logic",operation:_.operation,type:"value"},e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}):(r(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),_=`^${_}`,r(n,_,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}));}u=false;}break;case "pop":{let g=p[p.length-1];if(g&&typeof g=="object"&&"f()"in g){let E=[];for(;p.length>0&&p[p.length-1]!=="/ev";)E.push(p.pop());E=E.reverse();let _=_t(E,e,h,t);p=[],_.forEach(T=>{T&&typeof T=="object"&&"type"in T&&T.type==="function"?r(n,T,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}):W.warn("Unhandled case: value is not a function",T);}),u=false;}else p.push(d);return}default:p.push(d);}else if(typeof d=="string")if(d.startsWith("^"))r(n,d,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),u=false;else if(d==="ev")c=true;else if(d===`
70
- `)u=true;else if(d==="done"||d==="end")r(n,d,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),u=false;else if(d==="<>")r(n,d,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),u=false;else if(d==="nop"&&f){let g=Yu(A,a,s,e,t,h,l);g&&r(n,g,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),f=false,A=[];}else d==="#"?y=true:d==="thread"&&(C=true);else if(Array.isArray(d))if(f)A.push(d);else if(d.length>1&&typeof d[d.length-2]=="object"&&d[d.length-2]&&"c"in d[d.length-2]&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"b"in d[d.length-1]){p.pop();let g=[],E=[];for(;p.length>0&&p[p.length-1]!=="/ev";)g.push(p.pop());A=[...A,...g.reverse()],f=true,E.push(d.pop()),E.push(d.pop()),A=[...A,...d],A.push(E);}else if(d.length>1&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"#n"in d[d.length-1]){let g=d.pop();if(!g){W.error("Error parsing ink file: el is undefined");return}let E=g["#n"];delete g["#n"],d.push(g),r(n,{"->":e?e+"_|_"+E:E},e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),s({[E]:d},e,t);}else Ot(d,e,t,n,r,a,s,o,l,u,h);else if(d&&typeof d=="object")if("->"in d&&typeof d["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->"])){let g=[];p.length>0&&(g=Aa(["ev",...p],e,h,t)),d.params=g,r(n,d,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),u=false;}else if("->t->"in d&&typeof d["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->t->"])){let g=[];p.length>0&&(g=Aa(["ev",...p],e,h,t)),d.params=g,r(n,d,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C}),u=false;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(p.push(d),u=false);else if("s"in d&&Array.isArray(d.s))p.push(d),u=false;else if("CNT?"in d)p.push(d),u=false;else if("VAR="in d||"temp="in d){let g="VAR="in d?d["VAR="]:d["temp="],E,_=[];if(g!=="$r"){for(p.pop(),p[p.length-1]==="/ev"&&p.pop();p.length>0&&p[p.length-1]!=="/ev";)_.push(p.pop());_=_.reverse(),E=Li(_,e,h,t),p=[],Bn({key:g,value:E,defaultType:"VAR="in d?"storage":"tempstorage",artmeticValue:true},h,t).forEach(N=>{(N.value!==void 0||N.value!==null)&&r(n,N,e,t,h,{isNewLine:u,isHashtagScript:y,isThreads:C});}),u=false;}}else s(d,e,t);}),o(p,n,e,t,h),e.includes("_|_")&&n.length===2){let d=n[0],S=n[1];d&&S&&typeof d=="object"&&"dialogue"in d&&typeof S=="object"&&"labelToOpen"in S&&d.dialogue===" "&&S.labelToOpen&&(n.shift(),delete S.glueEnabled,n[0]=S);}}function Pa(i,e,t,n,r,a){if(e.length===0)return;let s=_t(e,n,t,r);if(s.length===1){let o={type:"ifelse",condition:s[0],then:i,else:a};return o.else||delete o.else,o}else if(s.length>1){let o={type:"ifelse",condition:{type:"union",unionType:"and",conditions:s},then:i,else:a};return o.else||delete o.else,o}}function Yu(i,e,t,n,r,a,s=void 0){if(i.length===0){W.error("Error parsing ink file: Conditional statement is not valid",i);return}let o=[],l=[];if(i.forEach(c=>{Array.isArray(c)?l.push(c):typeof c=="string"&&c==="du"?r.du?o.push(r.du):r.du=o[o.length-1]:(typeof c!="string"||c!=="/ev")&&o.push(c);}),l.length===0){W.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=Oa(l[0],e,t,`${n}${"_|_"}then`,r,a,`${s||""}then`),h;return l.length===2?h=Oa(l[1],e,t,`${n}${"_|_"}else`,r,a,`${s||""}else`):l.length>2?(l.shift(),l.push("nop"),l=[{b:l}],h=Oa(l,e,t,`${n}${"_|_"}else`,r,a,`${s||""}else`)):h=void 0,r.du=void 0,Pa(u,o,a,n,r,h)}function Oa(i,e,t,n,r,a,s=void 0){let o=[];for(let u of i)typeof u=="object"&&"b"in u&&(u.b=u.b.filter(h=>h!==null&&!(typeof h=="object"&&"->"in h&&new RegExp(/.*\.[0-9]/).test(h["->"]))),Ot(u.b,n,r,o,e,e,t,on,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function Ta(i="",e=""){let t=Array.isArray(i)?i:[i],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function on(i,e,t,n,r){if(i.length>0){let a={};Qu(i,a,r,n);for(let[s,o]of Object.entries(a)){let l=t+"_|_"+s,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:wa(l,false),oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let h=Pa(u,o.conditions,r,t,n)||u,c=e[e.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),e.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let p=c.choices;p&&Array.isArray(p)?p.push(h):W.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,p),c.choices=p.sort((f,y)=>{try{let C=f.label.split("."),A=C[C.length-1].replaceAll(".","_|_"),b=y.label.split("."),m=b[b.length-1].replaceAll(".","_|_");if(A.includes("c-")&&m.includes("c-")){let d=A.split("c-")[1],S=Number(d),g=m.split("c-")[1],E=Number(g);return S-E}}catch{}return 0});}else e.push({choices:[h]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function Qu(i,e,t,n,r){let a=[],s="",o="",l=false,u=[];for(let h=0;h<i.length;h++){let c=i[h];if(typeof c=="string")c.startsWith("^")?a.push(st(c)):zu.includes(c)&&u.push(c);else if(Array.isArray(c)&&c.includes("visit")){let p=an(c,Ri,(f,y,C)=>{},r,n,t);a.push(p);}else if(c&&typeof c=="object")if("*"in c&&typeof c["*"]&&typeof c["*"]=="string")c["*"].includes("c")&&(s=`c${c["*"].split("c")[1]}`,c.flg&16&&(l=true));else if("s"in c&&Array.isArray(c.s)){let p=Zu(c.s),f=c.s.includes("<>");p&&(r&&e[r]?(e[r].preDialog={text:p,glue:f},e[r].text=Ta(p,e[r].text)):(a.push(p),o=p));}else ("CNT?"in c||"VAR?"in c)&&u.push(c);else u.push(c);if(s){e[s]?e[s].text=Ta(a,e[s].text):e[s]={text:a,onetime:l,conditions:u},o&&(e[s].preDialog={text:o,glue:false});let p=i.slice(h+1);Qu(p,e,t,n,s);return}}}function Zu(i){for(let e of i)if(typeof e=="string"){if(e.startsWith("^"))return st(e)}else if(Array.isArray(e)){let t=Zu(e);if(t)return t}}var Fa;(r=>{function i(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:l=[],enums:u={},functions:h=[],preDialog:c={},characterIds:p}=s,f={$schema:qu};if(f.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:l,enums:u,functions:h,preDialog:c,characterIds:p}),f.labels&&ki in f.labels){let y=f.labels[ki];delete f.labels[ki],y.forEach(C=>{C.operations&&(f.initialOperations=f.initialOperations?[...f.initialOperations,...C.operations]:[...C.operations]);});}if(f.labels&&Gt in f.labels){let y=f.labels[Gt];delete f.labels[Gt],y.forEach(C=>{C.operations&&(f.initialOperations=f.initialOperations?[...f.initialOperations,...C.operations]:[...C.operations]);});}return o.forEach(y=>{f.labels&&y in f.labels&&delete f.labels[y];}),l.forEach(y=>{f.initialOperations&&(f.initialOperations=f.initialOperations.filter(C=>!(C.type==="value"&&C.key===y)));}),f}r.inkToJson=i;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){W.error("Error parsing ink file",o);}}function t(a,s,o){for(let l of a)if(l)if(Array.isArray(l))if(l.includes("visit")){let u=an(l,Ri,(h,c,p)=>{},"",o,[]);u&&(o.externalSwitch=u);}else t(l,s,o);else typeof l=="object"&&(l&&"VAR="in l&&o.externalSwitch&&(s[Gt]||(s[Gt]=[]),s[Gt].push({operations:Bn({defaultType:"storage",key:l["VAR="],value:o.externalSwitch},[],o)})),n(l,s,"",o));}function n(a,s,o="",l){if(a!==null){for(let[u,h]of Object.entries(a))if(Array.isArray(h)){let c=[],p={},f=(o?o+"_|_":"")+u;Ot(h,f,l,c,xa,xa,(y,C,A)=>{n(y,p,C,A);},on);for(let[y,C]of Object.entries(p))s[y]=C;c.length>0&&(s[f]=c);}}}})(Fa||={});var Uc=oa(Hc()),Kc=oa(ln()),Dy=/(?:^|<>)\s*#\s*([^\r\n]+)/g,zc=new Map;function Xc(i,e){let t=JSON.stringify([e,i]),n=zc.get(t);if(n)return n;let r=new RegExp(i,e);return zc.set(t,r),r}function Di(i,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(s=>Di(i,s));let r=t.oneOf;if(Array.isArray(r))return r.some(s=>Di(i,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>Di(i,s));if(typeof t.const=="string")return i===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===i);if(t.type!=="string"||typeof t.minLength=="number"&&i.length<t.minLength||typeof t.maxLength=="number"&&i.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!Xc(t.pattern,"").test(i))return !1}catch{return false}return true}function aa(i,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(o=>aa(i,o));let r=t.oneOf;if(Array.isArray(r))return r.some(o=>aa(i,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>aa(i,o));if(t.type!=="array"||typeof t.minItems=="number"&&i.length<t.minItems||typeof t.maxItems=="number"&&i.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(i.length<s.length)return false;for(let o=0;o<s.length;o++)if(!Di(i[o],s[o]))return false;return i.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:i.slice(s.length).every(o=>Di(o,t.items))}function Ay(i,e){if(e.type==="regexp")try{let t=Xc(e.source,e.flags);return t.lastIndex=0,t.test(i.join(" "))}catch{return false}return e.type==="literal"?i.join(" ")===e.value:aa(i,e.schema)}function wy(i){let e=i.split(/\r?\n/),t=[];for(let n=0;n<e.length;n++){let r=e[n];for(let a of r.matchAll(Dy)){let s=(a[1]??"").trim();if(!s)continue;let o=O.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:n+1,command:s,tokens:o});}}return t}var Zl;(n=>{function i(r,a={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let s=[];try{return {json:new Uc.Compiler(r,{errorHandler:(h,c)=>{let p=h.replace(/^[A-Z]+: line \d+: ?/,""),f=h.match(/line (\d+)/);s.push({message:p,type:c,line:f?Number(f[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:h=>h,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:s}}catch{let l=false,u={...a,textSource:r};return e(s,()=>{l=true;},u),l?i(u.textSource,a):{issues:s}}}n.compile=i;function e(r,a,s){let{functions:o,initialVarsToRemove:l,labelToRemove:u}=s,h=r.find(c=>c.type===Kc.ErrorType.Error);if(h){if(h.message.includes("Divert target not found")){let c=h.message.match(/Divert target not found: '-> (\w+)'/);if(c?.[1]){let p=c[1],f=`
66
+ ${E}`),E&&(o=true),s=_.getLogichValue(C.glueEnabled,e)||false,E)}),u=_.getLogichValue(l[0],e),h=typeof u=="object"&&"character"in u?u.character:void 0,c=l.flatMap(C=>{let d;C&&typeof C=="object"&&"text"in C?d=C.text:d=C;let E;return Array.isArray(d)?E=d.map(m=>{let S=_.getLogichValue(m,e);return Ve.t(`${S}`)}):E=_.getLogichValue(d,e)||"",Ve.t(E)}),p=a.find(C=>C.end),f=a.find(C=>C.choices),v=false,g=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),v=a[a.length-1].glueEnabled,g=a.reverse().find(C=>!(C.operations&&(!C.dialogue||!C.choices)))?.goNextStep);let A=a.find(C=>C.labelToOpen),D=[];return a.forEach(C=>{C.operations&&(D=[...D,...C.operations]);}),{dialogue:h?{character:h,text:c}:c,end:p?.end,choices:f?.choices,glueEnabled:v,goNextStep:g,labelToOpen:A?.labelToOpen,operations:D}}}var Ei;(i=>{let e=new Set;function t(a){e.add(a);}i.add=t;function n(){e.clear();}i.clear=n;function r(a,s={}){let o=h=>Cu(h,s)??void 0,l=yu(a,s);if(e.size===0)return o(l);let u=o;for(let h of e){let c=u;u=p=>h(p,c)??void 0;}return u(l)}i.getLogichValue=r;})(Ei||={});var Id=Object.create,bu=Object.defineProperty,Vd=Object.getOwnPropertyDescriptor,kd=Object.getOwnPropertyNames,Rd=Object.getPrototypeOf,Ld=Object.prototype.hasOwnProperty,Su=(i=>typeof _t<"u"?_t:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof _t<"u"?_t:e)[t]}):i)(function(i){if(typeof _t<"u")return _t.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')}),Au=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Bd=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of kd(e))!Ld.call(i,r)&&r!==t&&bu(i,r,{get:()=>e[r],enumerable:!(n=Vd(e,r))||n.enumerable});return i},Wd=(i,e,t)=>(t=i!=null?Id(Rd(i)):{},Bd(bu(t,"default",{value:i,enumerable:true}),i)),jd=Au((i,e)=>{(function(t,n){typeof i=="object"?e.exports=i=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(i,function(){var t=t||(function(n,r){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof Su=="function")try{a=Su("crypto");}catch{}var s=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||(function(){function C(){}return function(d){var E;return C.prototype=d,E=new C,C.prototype=null,E}})(),l={},u=l.lib={},h=u.Base=(function(){return {extend:function(C){var d=o(this);return C&&d.mixIn(C),(!d.hasOwnProperty("init")||this.init===d.init)&&(d.init=function(){d.$super.init.apply(this,arguments);}),d.init.prototype=d,d.$super=this,d},create:function(){var C=this.extend();return C.init.apply(C,arguments),C},init:function(){},mixIn:function(C){for(var d in C)C.hasOwnProperty(d)&&(this[d]=C[d]);C.hasOwnProperty("toString")&&(this.toString=C.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),c=u.WordArray=h.extend({init:function(C,d){C=this.words=C||[],d!=r?this.sigBytes=d:this.sigBytes=C.length*4;},toString:function(C){return (C||f).stringify(this)},concat:function(C){var d=this.words,E=C.words,m=this.sigBytes,S=C.sigBytes;if(this.clamp(),m%4)for(var w=0;w<S;w++){var P=E[w>>>2]>>>24-w%4*8&255;d[m+w>>>2]|=P<<24-(m+w)%4*8;}else for(var N=0;N<S;N+=4)d[m+N>>>2]=E[N>>>2];return this.sigBytes+=S,this},clamp:function(){var C=this.words,d=this.sigBytes;C[d>>>2]&=4294967295<<32-d%4*8,C.length=n.ceil(d/4);},clone:function(){var C=h.clone.call(this);return C.words=this.words.slice(0),C},random:function(C){for(var d=[],E=0;E<C;E+=4)d.push(s());return new c.init(d,C)}}),p=l.enc={},f=p.Hex={stringify:function(C){for(var d=C.words,E=C.sigBytes,m=[],S=0;S<E;S++){var w=d[S>>>2]>>>24-S%4*8&255;m.push((w>>>4).toString(16)),m.push((w&15).toString(16));}return m.join("")},parse:function(C){for(var d=C.length,E=[],m=0;m<d;m+=2)E[m>>>3]|=parseInt(C.substr(m,2),16)<<24-m%8*4;return new c.init(E,d/2)}},v=p.Latin1={stringify:function(C){for(var d=C.words,E=C.sigBytes,m=[],S=0;S<E;S++){var w=d[S>>>2]>>>24-S%4*8&255;m.push(String.fromCharCode(w));}return m.join("")},parse:function(C){for(var d=C.length,E=[],m=0;m<d;m++)E[m>>>2]|=(C.charCodeAt(m)&255)<<24-m%4*8;return new c.init(E,d)}},g=p.Utf8={stringify:function(C){try{return decodeURIComponent(escape(v.stringify(C)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(C){return v.parse(unescape(encodeURIComponent(C)))}},A=u.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new c.init,this._nDataBytes=0;},_append:function(C){typeof C=="string"&&(C=g.parse(C)),this._data.concat(C),this._nDataBytes+=C.sigBytes;},_process:function(C){var d,E=this._data,m=E.words,S=E.sigBytes,w=this.blockSize,P=w*4,N=S/P;C?N=n.ceil(N):N=n.max((N|0)-this._minBufferSize,0);var Z=N*w,ye=n.min(Z*4,S);if(Z){for(var $t=0;$t<Z;$t+=w)this._doProcessBlock(m,$t);d=m.splice(0,Z),E.sigBytes-=ye;}return new c.init(d,ye)},clone:function(){var C=h.clone.call(this);return C._data=this._data.clone(),C},_minBufferSize:0});u.Hasher=A.extend({cfg:h.extend(),init:function(C){this.cfg=this.cfg.extend(C),this.reset();},reset:function(){A.reset.call(this),this._doReset();},update:function(C){return this._append(C),this._process(),this},finalize:function(C){C&&this._append(C);var d=this._doFinalize();return d},blockSize:16,_createHelper:function(C){return function(d,E){return new C.init(E).finalize(d)}},_createHmacHelper:function(C){return function(d,E){return new D.HMAC.init(C,E).finalize(d)}}});var D=l.algo={};return l})(Math);return t});}),qd=Au((i,e)=>{(function(t,n){typeof i=="object"?e.exports=i=n(jd()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(i,function(t){return (function(){var n=t,r=n.lib,a=r.WordArray,s=r.Hasher,o=n.algo,l=[],u=o.SHA1=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(h,c){for(var p=this._hash.words,f=p[0],v=p[1],g=p[2],A=p[3],D=p[4],C=0;C<80;C++){if(C<16)l[C]=h[c+C]|0;else {var d=l[C-3]^l[C-8]^l[C-14]^l[C-16];l[C]=d<<1|d>>>31;}var E=(f<<5|f>>>27)+D+l[C];C<20?E+=(v&g|~v&A)+1518500249:C<40?E+=(v^g^A)+1859775393:C<60?E+=(v&g|v&A|g&A)-1894007588:E+=(v^g^A)-899497514,D=A,A=g,g=v<<30|v>>>2,v=f,f=E;}p[0]=p[0]+f|0,p[1]=p[1]+v|0,p[2]=p[2]+g|0,p[3]=p[3]+A|0,p[4]=p[4]+D|0;},_doFinalize:function(){var h=this._data,c=h.words,p=this._nDataBytes*8,f=h.sigBytes*8;return c[f>>>5]|=128<<24-f%32,c[(f+64>>>9<<4)+14]=Math.floor(p/4294967296),c[(f+64>>>9<<4)+15]=p,h.sigBytes=c.length*4,this._process(),this._hash},clone:function(){var h=s.clone.call(this);return h._hash=this._hash.clone(),h}});n.SHA1=s._createHelper(u),n.HmacSHA1=s._createHmacHelper(u);})(),t.SHA1});}),Eu="___param___",se;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(se||={});var Md=class ${static init(e){e.loadAssets&&($._loadAssets=e.loadAssets),e.soundOperation&&($._soundOperation=e.soundOperation),e.imageOperation&&($._imageOperation=e.imageOperation),e.videoOperation&&($._videoOperation=e.videoOperation),e.imageContainerOperation&&($._imageContainerOperation=e.imageContainerOperation),e.textOperation&&($._textOperation=e.textOperation),e.canvasElementOperation&&($._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&($._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&($._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&($._narrationOperation=e.narrationOperation),e.effectOperation&&($._effectOperation=e.effectOperation),e.animateOperation&&($._animateOperation=e.animateOperation),e.getLogichValue&&($._getLogichValue=e.getLogichValue),e.getConditionalStep&&($._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return $._loadAssets}static _soundOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return $._soundOperation}static _imageOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return $._imageOperation}static _videoOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return $._videoOperation}static _imageContainerOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return $._imageContainerOperation}static _textOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return $._textOperation}static _canvasElementOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return $._canvasElementOperation}static _setStorageValue=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return $._setStorageValue}static _setInitialStorageValue=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return $._setInitialStorageValue}static _narrationOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return $._narrationOperation}static _effectOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return $._effectOperation}static _animateOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return $._animateOperation}static _getLogichValue=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return $._getLogichValue}static _getConditionalStep=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return $._getConditionalStep}};function Gd(i,e){if(e&&typeof e=="object"&&typeof i.functionName=="string"&&i.functionName in e){let t=e[i.functionName];if(typeof t=="function"){let n=i.args.map(r=>Md.getLogichValue(r,e));return t(...n)}else se.warn(`getLogichValue function ${i.functionName} not found in props`);}}function $d(i,e={}){let t="";return i.values.forEach(n=>{if(typeof n=="string")t+=n;else {let r=_.getLogichValue(n,e);t+=`${r}`;}}),t}async function xu(i,e,t){let n=_.getLogichValue(i,e);if(n)switch(n.type){case "sound":_.soundOperation(n);break;case "assets":case "bundle":await _.loadAssets(n);break;case "image":await _.imageOperation(n);break;case "video":await _.videoOperation(n);break;case "imagecontainer":await _.imageContainerOperation(n);break;case "text":await _.textOperation(n);break;case "canvaselement":await _.canvasElementOperation(n);break;case "value":_.setStorageValue(n,e);break;case "operationtoconvert":if(t){let r=$d(n,e),a=await t(r);a&&await xu(a,e,t);}break;case "input":case "dialogue":_.narrationOperation(n);break;case "shake":await _.effectOperation(n);break;case "animate":case "animate-sequence":_.animateOperation(n);break;case "function":await Gd(n,e);break}}function Du(i){let e=_.getLogichValue(i,{});e&&e.type==="value"&&e.storageOperationType==="set"&&(e.storageType==="storage"||e.storageType==="tempstorage")&&_.setInitialStorageValue(e);}var Jd=Wd(qd()),Hd=class extends narration.LabelAbstract{constructor(i,e,t,n={}){t||(t={}),t.onLoadingLabel=async()=>{for(let r of e){let a;if(typeof r=="function"?a=r():a=r,a=_.getConditionalStep(a),a.operations)try{let s=a.operations.map(o=>_.loadAssets(o));await Promise.all(s);}catch(s){se.error("The operation in the onLoadingLabel function of the label has an error:",s);}}},super(i,t),this._steps=e,this.operationStringConvert=n.operationStringConvert,this.skipEmptyDialogs=n.skipEmptyDialogs||false;}_steps;get steps(){return this._steps.map(i=>this.stepConverter(i))}get stepCount(){return this._steps.length}getStepById(i){if(i<0||i>=this._steps.length)return;let e=this._steps[i];return this.stepConverter(e)}operationStringConvert;skipEmptyDialogs=false;getStepSha(i){if(i<0||i>=this.steps.length)return;let e=this._steps[i];return (0, Jd.default)(e.toString().toLocaleLowerCase()).toString()}getDialogueText(i,e){let t="";if(Array.isArray(i)){let n=[];i.forEach(r=>{if(typeof r=="string")n.push(r);else if(r&&typeof r=="object"){let a=_.getLogichValue(r,e);a?(a&&!Array.isArray(a)&&typeof a=="object"&&(a=_.getLogichValue(a,e)||""),Array.isArray(a)?n=n.map(s=>`${s}`).concat(a):n.push(`${a}`)):n.push(`${r}`);}else n.push(`${r}`);}),t=n;}else {let n=_.getLogichValue(i,e);n&&!Array.isArray(n)&&typeof n=="object"&&(n=_.getLogichValue(n,e)),n&&Array.isArray(n)?t=n.map(r=>`${r}`):t=`${n}`;}return t}getDialogue(i,e){if(i==null)return;let t=_.getLogichValue(i,e);return t==null?`${t}`:typeof t=="object"&&"character"in t&&"text"in t?{character:t.character,text:Ve.t(this.getDialogueText(t.text,e))}:Ve.t(this.getDialogueText(t,e))}getChoices(i,e){return _.getLogichValue(i,e)?.map(t=>_.getLogichValue(t,e)).filter(t=>t!==void 0)}stepConverter(i){return async e=>{let t=typeof i=="function"?i():i;t=pixiVn.createExportableElement(t),t=_.getConditionalStep(t,e);let n=this.operationStringConvert?p=>this.operationStringConvert(p,t,e):void 0,{operations:r=[]}=t;for(let p of r)await xu(p,e,n);let{labelToOpen:a=[]}=t,s=this.getChoices(t.choices,e),o=_.getLogichValue(t.glueEnabled,e),l=this.getDialogue(t.dialogue,e),u=[];Array.isArray(a)||(a=[a]),a.forEach(p=>{let f=_.getLogichValue(p,e);f&&u.push(f);});let h=_.getLogichValue(t.goNextStep,e),c=_.getLogichValue(t.end,e);if(s){let p=s.map(f=>{let v="";if(Array.isArray(f.text)){let g=[];f.text.forEach(A=>{if(typeof A=="string")g.push(Ve.t(A));else if(A&&typeof A=="object"){let D=_.getLogichValue(A,e);D&&!Array.isArray(D)&&typeof D=="object"&&(D=_.getLogichValue(D,e)||""),D&&(Array.isArray(D)?g=g.concat(Ve.t(D)):g.push(Ve.t(D)));}}),v=g;}else typeof f.text=="string"&&(v=Ve.t(f.text));return {label:f.label,text:v,props:f.props,type:f.type,oneTime:f.oneTime,onlyHaveNoChoice:f.onlyHaveNoChoice,autoSelect:f.autoSelect}});narration.narration.choices=p;}else narration.narration.choices=void 0;l!==void 0&&(narration.narration.dialogue=l,this.skipEmptyDialogs&&typeof l=="string"&&(l===""||RegExp(/^\s+$/).test(l))&&(h=true)),o?narration.narration.dialogGlue=true:o===false&&(narration.narration.dialogGlue=false);for(let p of u){let f=p.label;typeof f=="object"&&(f=_.getLogichValue(f,e)||"");let v=p.params?.map(g=>_.getLogichValue(g,e));e={...e,...p.props},p.type==="jump"?(narration.narration.openedLabels.length>0&&narration.narration.closeCurrentLabel(),storage.storage.setTempVariable(`${Eu}${narration.narration.openedLabels.length}`,v),await narration.narration.call(f,e)):(storage.storage.setTempVariable(`${Eu}${narration.narration.openedLabels.length}`,v),await narration.narration.call(f,e));}c==="game_end"?(narration.narration.closeAllLabels(),await narration.narration.continue(e,{runNow:true})):c==="label_end"&&narration.narration.closeCurrentLabel(),h&&await narration.narration.continue(e,{runNow:true});}}};async function ra(i,e={}){if(!Array.isArray(i))if(typeof i=="object"||typeof i=="string")i=[i];else {se.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let t=i.map(a=>{if(typeof a=="string")try{return JSON.parse(a)}catch(s){return se.error("Error parsing imported Pixi'VN JSON",s),{}}return a}),n=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)s.type==="value"&&(typeof s.value!="object"||!s.value||!("type"in s.value))&&Du(s);return Promise.resolve()});await Promise.all(n);let r=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)(s.type!=="value"||s.type==="value"&&typeof s.value=="object"&&s.value&&"type"in s.value)&&Du(s);if(a.labels){let s=a.labels;for(let o in s)try{let l=s[o],u=new Hd(o,l,void 0,e);narration.RegisteredLabels.add(u);}catch(l){se.error(`Error creating JSON label ${o}`,l);}}return Promise.resolve()});await Promise.all(r);}var zd={version:"1.13.10"};var wu=`https://pixi-vn.com/schemas/${zd.version}/schema.json`,_u=["==","!=","<","<=",">",">=","CONTAINS"];function sa(){_.init({animateOperation:cu,canvasElementOperation:uu,effectOperation:hu,imageContainerOperation:ou,imageOperation:su,textOperation:lu,narrationOperation:du,loadAssets:ru,soundOperation:pu,videoOperation:au,setStorageValue:mu,setInitialStorageValue:gu,getLogichValue:Ei.getLogichValue,getConditionalStep:Si});}var Di="global decl",Pt="___external_value___",Ou=/\[([^\]]+)\]/;var Tu=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],Pu=["+","-","/","*","%","POW","RANDOM","L^"],Fu=["INT","FLOOR","FLOAT"];function Ht(i,e){if(i.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(i)&&(i=i.split(".").filter(r=>!r.match(/^[0-9]+$/)).join("."),!i.startsWith(".")))return i.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(i)&&i.includes("g-")){let n=i.split("g-");return aa(e)+"_|_"+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(i);)t++,i=i.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(i)&&e){let n=i.substring(1);return aa(e,t)+"_|_"+n.replaceAll(".","_|_")}return i.replaceAll(".","_|_")||aa(e,t).replaceAll(".","_|_")}function aa(i,e=0){let t=i.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var Nu="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Ue(i){return i.startsWith("^")&&(i=i.substring(1)),i=i.replaceAll("\\\\",Nu),i=i.replaceAll("\\n",`
67
+ `),i=i.replaceAll("\\t"," "),i=i.replaceAll(" "," "),i=i.replaceAll(Nu,"\\\\"),i}function mt(i,e,t,n){let{functions:r}=n;i=i.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return i.forEach(s=>{if(typeof s=="string")switch(s){case "&&":case "||":if(a.length>=2){let o={type:"union",unionType:s==="&&"?"and":"or",conditions:[a[a.length-2],a[a.length-1]]};a.pop(),a.pop(),a.push(o);}break;case "!":if(a.length===0)W.error("Error parsing ink file: Conditional statement is not valid",i);else {let o={type:"union",unionType:"not",condition:a[a.length-1]};a[a.length-1]=o;}break;case "!?":if(a.length>1){let o={type:"union",unionType:"not",condition:{type:"compare",operator:"CONTAINS",leftValue:a[a.length-2],rightValue:a[a.length-1]}};a.pop(),a.pop(),a.push(o);}else W.error("Error parsing ink file: Conditional statement is not valid",i);break;default:if(_u.includes(s))if(a.length<2)W.error("Error parsing ink file: Conditional statement is not valid",i);else {let o={type:"compare",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(Pu.includes(s))if(a.length<2)W.error("Error parsing ink file: Conditional statement is not valid",i);else {s==="L^"&&(s="INTERSECTION");let o={type:"arithmetic",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(Fu.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(Ue(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),l=o.pop(),u=o.pop();if(u===void 0||l===void 0){W.error("Error parsing ink file: Conditional statement is not valid",i);return}let h=Number(u),c=o.join(".");if(c.includes("^.")){let f=c.split("."),v=f[f.length-1].replaceAll(".","_|_");f.pop(),c=`${f.join(".")}.${v}`,l.includes("c-")&&(c=c+"_|_"+l);}else c=c.replaceAll(".","_|_");let p=Ht(c,e);if(!p)return;a.push({type:"compare",leftValue:oa(p),operator:">=",rightValue:{type:"value",value:h}});}else {let o=Ht(s["CNT?"],e);if(!o)return;a.push(oa(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(Ft({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],l=r.find(h=>h.name===o);if(!l){W.error(`Error parsing ink file: Function ${o} is not defined`,i);return}let u=[];for(let h=0;h<l.args;h++)a.length!==0&&u.push(a.pop());a.push({type:"function",functionName:o,args:u.reverse()});}else if(typeof s=="object"&&"^->"in s)s["^->"].includes("$r")||a.push(s["^->"]);else if(typeof s=="object"&&"list"in s){let o=Object.values(s.list).map(l=>l);a.push(o);}else a.push(s);}),a}function la(i,e,t,n){return mt(i,e,t,n)}function Ft(i,e,t){let{key:n,defaultType:r}=i,a=e.indexOf(n);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:r,key:n}}function wn(i,e,t){let{key:n,value:r,defaultType:a,artmeticValue:s}=i,o=e.indexOf(n);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:r}];if(s){if(typeof r=="object"&&"list"in r){let l=Object.values(r.list).map(u=>u);return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:l}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:r}]}else if(typeof r=="object"){if("list"in r&&typeof r.list=="object"){if("origins"in r&&Array.isArray(r.origins)&&r.origins.length>0)return r.origins.reduce(l=>(l.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(t.enums[n])}),Object.entries(t.enums[n]).forEach(([u,h])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${u}`,value:h});}),l),[]);{let l=new Set,u=Object.entries(r.list).reduce((h,[c,p])=>{let[f,v]=c.split(".");return h.push({type:"value",storageOperationType:"set",storageType:a,key:v,value:p}),l.add(f),h},[]);return l.forEach(h=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:h,value:Object.values(t.enums[h])});}),n in t.enums?Object.entries(t.enums[n]).forEach(([h,c])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${h}`,value:c});}):u.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(r.list)}),u}}else if(typeof r=="object"&&"VAR?"in r){if(typeof r["VAR?"]=="string"&&r["VAR?"].includes(".")){let[l,u]=r["VAR?"].split(".");if(l in t.enums&&u in t.enums[l])return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:t.enums[l][u]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:Ft({key:r["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:r}]}function oa(i){return {type:"value",storageType:"label",storageOperationType:"get",label:i}}function ua(i,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(i)?"call":"jump"}function bi(i,e){if(e){if(typeof e=="string")e.startsWith("^")&&i.push(Ue(e));else if(typeof e=="object"&&"type"in e)switch(e.type){case "value":case "function":console.warn("Warning: trying to add a value or function operation as text. This is likely a mistake, so it will be ignored.");break;default:i.push(e);}}}function ha(i,e,t,n,r,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:l=false}=a;return Kd(i,e,t,n,r,{isNewLine:s,isHashtagScript:o,isThreads:l})}function Kd(i,e,t,n,r,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:l}=a;if(o){if(Array.isArray(e)&&e.length>0){let u={goNextStep:true},h=[];try{if(e.length===1&&typeof e[0]=="string"&&!e[0].match(Ou)){let c=e[0],p=O.convertTagTolist(c),f=O.convertOperation(p,u);f&&(f.$origin=c,h.push(f));}}catch{}h.length===0&&h.push({type:"operationtoconvert",values:e}),i.push({...u,operations:h});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&i.length>0){let u=i[i.length-1];!u.glueEnabled&&!u.operations&&!u.labelToOpen&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),i[i.length-1]=u;}typeof e=="string"?i.push(Xd(Ue(e),n.characterIds)):i.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")i.push({end:"game_end"});else if(e==="done")i.push({end:"label_end",goNextStep:true});else if(e==="<>")if(i.length>0){let u=i[i.length-1];u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true),i[i.length-1]=u;}else i.push({glueEnabled:true,goNextStep:false});}else if(typeof e=="object"){if("type"in e)switch(e.type){case "value":e.storageOperationType==="set"?(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=Ue(e.value)),i.push({goNextStep:true,operations:[e]})):console.warn("Warning: trying to add a value get operation as step. This is likely a mistake, so it will be ignored.");break;case "function":i.push({goNextStep:true,operations:[e]});break;default:if(!s&&i.length>0){let u=i[i.length-1];!u.glueEnabled&&!u.operations&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),i[i.length-1]=u;}i.push({conditionalStep:e});}else if("->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&i.length>0&&i[i.length-1]?.dialogue===void 0&&(u=void 0),!s&&i.length>0){let h=i[i.length-1];h.labelToOpen||(h.goNextStep=true),i[i.length-1]=h;}if(e.params&&e.params.length===0&&delete e.params,e.var)i.push({labelToOpen:{label:Ft({key:e["->"],defaultType:"storage"},r),type:l?"call":"jump",params:e.params},glueEnabled:u});else {let h=Ht(e["->"],t);if(!h)return;i.push({labelToOpen:{label:h,type:ua(h,l),params:e.params},glueEnabled:u});}}else if("->t->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&i.length>0&&i[i.length-1]?.dialogue===void 0&&(u=void 0),!s&&i.length>0){let c=i[i.length-1];c.labelToOpen||(c.goNextStep=true),i[i.length-1]=c;}e.params&&e.params.length===0&&delete e.params;let h=Ht(e["->t->"],t);if(!h)return;i.push({labelToOpen:{label:h,type:"call",params:e.params},glueEnabled:u});}}}function Xd(i,e){let t;if(i.includes(": ")){let n=i.split(": "),r=n[0],a=n.slice(1).join(": ");(e?.has(r)||characters.RegisteredCharacters.has(r))&&(t=r,i=a);}return t?{dialogue:{character:t,text:i}}:{dialogue:i}}function ca(i,e,t,n=true,r=false){return Yd(i,e,t,n,r)}function Yd(i,e,t,n,r=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?i.push(Ue(e)):i.push(e):typeof e=="object"&&"type"in e&&i.push(e));}function Ai(i,e,t,n){if(i.length===0){W.error("Error parsing ink file: Arithmetic statement is not valid",i);return}let r=mt(i,e,t,n);if(r.length===1){let a=r[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function zt(i,e,t,n="",r,a,s=void 0){let o=[],l="sequential",u=false,h=true;i.forEach(f=>{f==="%"&&(l="loop"),f==="seq"&&(l="random"),f==="MIN"&&(u=true);});let c=i[i.length-1];return Object.keys(c).forEach(f=>{let v=c[f];if(Array.isArray(v)&&v.length>3){v=v.slice(1,v.length-2);let g=[];gt(v,n,r,g,e,e,t,Ut,s,true,a),g.length===1?o.push(g[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:g});}else Array.isArray(v)&&v.length===3&&(h=false);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:h?"lastItem":void 0,nestedId:s}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:h?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:l}}function gt(i,e,t,n=[],r,a,s,o,l=void 0,u=true,h=[]){let c=false,p=[],f=false,v=false,g=false,A=[],D=[];if(t.preDialog[e]&&(u=false,r(n,`^${t.preDialog[e].text}`,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),t.preDialog[e].glue&&r(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),delete t.preDialog[e]),i.includes("visit")){let d=zt(i,a,s,e,t,h,l);d&&(!u&&n.length>0&&r(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),r(n,d,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}));return}let C=i[0];if(C&&typeof C=="object"&&"temp="in C){for(;i[0]&&typeof i[0]=="object"&&"temp="in i[0];)h.push(i[0]["temp="]),i.shift();h=h.reverse();}if(i.forEach((d,E)=>{if(v){if(typeof d=="string"&&d==="/#"){let m=[];gt(D,e,t,m,ca,ca,s,o,l,u),r(n,m,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),v=false,D=[];}else D.push(d);return}else if(c)if(Array.isArray(d))p.push(d);else if(d&&typeof d=="object")"CNT?"in d?E>0&&i[E-1]==="ev"?(f=true,A.push(d)):f?A.push(d):(p.push(d),u=false):"VAR="in d||"temp="in d?wn({key:"VAR="in d?d["VAR="]:d["temp="],value:i[E-1],defaultType:"VAR="in d?"storage":"tempstorage"},h,t).forEach(S=>{if(S.value&&typeof S.value=="string"&&S.value==="/str"&&(S.value=i[E-2]),S.value&&typeof S.value=="object"&&"^->"in S.value&&(S.value=S.value["^->"]),p.length>1){let w=Ai(p,e,h,t);p=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"&&(S.value=w.operation);}(typeof S.key!="string"||!S.key.includes("$r"))&&(r(n,S,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),u=true);}):"VAR?"in d?p.push(d):"^->"in d?d["^->"].includes("$r")||p.push(d):("f()"in d||"list"in d&&typeof d.list=="object")&&p.push(d);else switch(d){case "/ev":f&&A.push(d),c=false,p.push(d);break;case "out":if(p.length>0){let m=p[p.length-1];if(m&&typeof m=="object"&&"VAR?"in m){p.pop();let S=Ft({key:m["VAR?"],defaultType:"storage"},h);r(n,S,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g});}else {let S=[];for(;p.length>0&&p[p.length-1]!=="/ev";)S.push(p.pop());S=S.reverse();let w=Ai(S,e,h,t);p=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"?r(n,{storageOperationType:"get",storageType:"logic",operation:w.operation,type:"value"},e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}):(r(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),w=`^${w}`,r(n,w,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}));}u=false;}break;case "pop":{let m=p[p.length-1];if(m&&typeof m=="object"&&"f()"in m){let S=[];for(;p.length>0&&p[p.length-1]!=="/ev";)S.push(p.pop());S=S.reverse();let w=mt(S,e,h,t);p=[],w.forEach(P=>{P&&typeof P=="object"&&"type"in P&&P.type==="function"?r(n,P,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}):W.warn("Unhandled case: value is not a function",P);}),u=false;}else p.push(d);return}default:p.push(d);}else if(typeof d=="string")if(d.startsWith("^"))r(n,d,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),u=false;else if(d==="ev")c=true;else if(d===`
68
+ `)u=true;else if(d==="done"||d==="end")r(n,d,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),u=false;else if(d==="<>")r(n,d,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),u=false;else if(d==="nop"&&f){let m=Iu(A,a,s,e,t,h,l);m&&r(n,m,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),f=false,A=[];}else d==="#"?v=true:d==="thread"&&(g=true);else if(Array.isArray(d))if(f)A.push(d);else if(d.length>1&&typeof d[d.length-2]=="object"&&d[d.length-2]&&"c"in d[d.length-2]&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"b"in d[d.length-1]){p.pop();let m=[],S=[];for(;p.length>0&&p[p.length-1]!=="/ev";)m.push(p.pop());A=[...A,...m.reverse()],f=true,S.push(d.pop()),S.push(d.pop()),A=[...A,...d],A.push(S);}else if(d.length>1&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"#n"in d[d.length-1]){let m=d.pop();if(!m){W.error("Error parsing ink file: el is undefined");return}let S=m["#n"];delete m["#n"],d.push(m),r(n,{"->":e?e+"_|_"+S:S},e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),s({[S]:d},e,t);}else gt(d,e,t,n,r,a,s,o,l,u,h);else if(d&&typeof d=="object")if("->"in d&&typeof d["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->"])){let m=[];p.length>0&&(m=la(["ev",...p],e,h,t)),d.params=m,r(n,d,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),u=false;}else if("->t->"in d&&typeof d["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->t->"])){let m=[];p.length>0&&(m=la(["ev",...p],e,h,t)),d.params=m,r(n,d,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g}),u=false;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(p.push(d),u=false);else if("s"in d&&Array.isArray(d.s))p.push(d),u=false;else if("CNT?"in d)p.push(d),u=false;else if("VAR="in d||"temp="in d){let m="VAR="in d?d["VAR="]:d["temp="],S,w=[];if(m!=="$r"){for(p.pop(),p[p.length-1]==="/ev"&&p.pop();p.length>0&&p[p.length-1]!=="/ev";)w.push(p.pop());w=w.reverse(),S=Ai(w,e,h,t),p=[],wn({key:m,value:S,defaultType:"VAR="in d?"storage":"tempstorage",artmeticValue:true},h,t).forEach(N=>{(N.value!==void 0||N.value!==null)&&r(n,N,e,t,h,{isNewLine:u,isHashtagScript:v,isThreads:g});}),u=false;}}else s(d,e,t);}),o(p,n,e,t,h),e.includes("_|_")&&n.length===2){let d=n[0],E=n[1];d&&E&&typeof d=="object"&&"dialogue"in d&&typeof E=="object"&&"labelToOpen"in E&&d.dialogue===" "&&E.labelToOpen&&(n.shift(),delete E.glueEnabled,n[0]=E);}}function pa(i,e,t,n,r,a){if(e.length===0)return;let s=mt(e,n,t,r);if(s.length===1){let o={type:"ifelse",condition:s[0],then:i,else:a};return o.else||delete o.else,o}else if(s.length>1){let o={type:"ifelse",condition:{type:"union",unionType:"and",conditions:s},then:i,else:a};return o.else||delete o.else,o}}function Iu(i,e,t,n,r,a,s=void 0){if(i.length===0){W.error("Error parsing ink file: Conditional statement is not valid",i);return}let o=[],l=[];if(i.forEach(c=>{Array.isArray(c)?l.push(c):typeof c=="string"&&c==="du"?r.du?o.push(r.du):r.du=o[o.length-1]:(typeof c!="string"||c!=="/ev")&&o.push(c);}),l.length===0){W.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=da(l[0],e,t,`${n}${"_|_"}then`,r,a,`${s||""}then`),h;return l.length===2?h=da(l[1],e,t,`${n}${"_|_"}else`,r,a,`${s||""}else`):l.length>2?(l.shift(),l.push("nop"),l=[{b:l}],h=da(l,e,t,`${n}${"_|_"}else`,r,a,`${s||""}else`)):h=void 0,r.du=void 0,pa(u,o,a,n,r,h)}function da(i,e,t,n,r,a,s=void 0){let o=[];for(let u of i)typeof u=="object"&&"b"in u&&(u.b=u.b.filter(h=>h!==null&&!(typeof h=="object"&&"->"in h&&new RegExp(/.*\.[0-9]/).test(h["->"]))),gt(u.b,n,r,o,e,e,t,Ut,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function fa(i="",e=""){let t=Array.isArray(i)?i:[i],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function Ut(i,e,t,n,r){if(i.length>0){let a={};Vu(i,a,r,n);for(let[s,o]of Object.entries(a)){let l=t+"_|_"+s,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:ua(l,false),oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let h=pa(u,o.conditions,r,t,n)||u,c=e[e.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),e.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let p=c.choices;p&&Array.isArray(p)?p.push(h):W.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,p),c.choices=p.sort((f,v)=>{try{let g=f.label.split("."),A=g[g.length-1].replaceAll(".","_|_"),D=v.label.split("."),C=D[D.length-1].replaceAll(".","_|_");if(A.includes("c-")&&C.includes("c-")){let d=A.split("c-")[1],E=Number(d),m=C.split("c-")[1],S=Number(m);return E-S}}catch{}return 0});}else e.push({choices:[h]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function Vu(i,e,t,n,r){let a=[],s="",o="",l=false,u=[];for(let h=0;h<i.length;h++){let c=i[h];if(typeof c=="string")c.startsWith("^")?a.push(Ue(c)):Tu.includes(c)&&u.push(c);else if(Array.isArray(c)&&c.includes("visit")){let p=zt(c,bi,(f,v,g)=>{},r,n,t);a.push(p);}else if(c&&typeof c=="object")if("*"in c&&typeof c["*"]&&typeof c["*"]=="string")c["*"].includes("c")&&(s=`c${c["*"].split("c")[1]}`,c.flg&16&&(l=true));else if("s"in c&&Array.isArray(c.s)){let p=ku(c.s),f=c.s.includes("<>");p&&(r&&e[r]?(e[r].preDialog={text:p,glue:f},e[r].text=fa(p,e[r].text)):(a.push(p),o=p));}else ("CNT?"in c||"VAR?"in c)&&u.push(c);else u.push(c);if(s){e[s]?e[s].text=fa(a,e[s].text):e[s]={text:a,onetime:l,conditions:u},o&&(e[s].preDialog={text:o,glue:false});let p=i.slice(h+1);Vu(p,e,t,n,s);return}}}function ku(i){for(let e of i)if(typeof e=="string"){if(e.startsWith("^"))return Ue(e)}else if(Array.isArray(e)){let t=ku(e);if(t)return t}}var ma;(r=>{function i(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:l=[],enums:u={},functions:h=[],preDialog:c={},characterIds:p}=s,f={$schema:wu};if(f.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:l,enums:u,functions:h,preDialog:c,characterIds:p}),f.labels&&Di in f.labels){let v=f.labels[Di];delete f.labels[Di],v.forEach(g=>{g.operations&&(f.initialOperations=f.initialOperations?[...f.initialOperations,...g.operations]:[...g.operations]);});}if(f.labels&&Pt in f.labels){let v=f.labels[Pt];delete f.labels[Pt],v.forEach(g=>{g.operations&&(f.initialOperations=f.initialOperations?[...f.initialOperations,...g.operations]:[...g.operations]);});}return o.forEach(v=>{f.labels&&v in f.labels&&delete f.labels[v];}),l.forEach(v=>{f.initialOperations&&(f.initialOperations=f.initialOperations.filter(g=>!(g.type==="value"&&g.key===v)));}),f}r.inkToJson=i;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){W.error("Error parsing ink file",o);}}function t(a,s,o){for(let l of a)if(l)if(Array.isArray(l))if(l.includes("visit")){let u=zt(l,bi,(h,c,p)=>{},"",o,[]);u&&(o.externalSwitch=u);}else t(l,s,o);else typeof l=="object"&&(l&&"VAR="in l&&o.externalSwitch&&(s[Pt]||(s[Pt]=[]),s[Pt].push({operations:wn({defaultType:"storage",key:l["VAR="],value:o.externalSwitch},[],o)})),n(l,s,"",o));}function n(a,s,o="",l){if(a!==null){for(let[u,h]of Object.entries(a))if(Array.isArray(h)){let c=[],p={},f=(o?o+"_|_":"")+u;gt(h,f,l,c,ha,ha,(v,g,A)=>{n(v,p,g,A);},Ut);for(let[v,g]of Object.entries(p))s[v]=g;c.length>0&&(s[f]=c);}}}})(ma||={});var Pc=Us(Oc()),Fc=Us(Kt()),MC=/(?:^|<>)\s*#\s*([^\r\n]+)/g,Tc=new Map;function Nc(i,e){let t=JSON.stringify([e,i]),n=Tc.get(t);if(n)return n;let r=new RegExp(i,e);return Tc.set(t,r),r}function ci(i,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(s=>ci(i,s));let r=t.oneOf;if(Array.isArray(r))return r.some(s=>ci(i,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>ci(i,s));if(typeof t.const=="string")return i===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===i);if(t.type!=="string"||typeof t.minLength=="number"&&i.length<t.minLength||typeof t.maxLength=="number"&&i.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!Nc(t.pattern,"").test(i))return !1}catch{return false}return true}function zs(i,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(o=>zs(i,o));let r=t.oneOf;if(Array.isArray(r))return r.some(o=>zs(i,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>zs(i,o));if(t.type!=="array"||typeof t.minItems=="number"&&i.length<t.minItems||typeof t.maxItems=="number"&&i.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(i.length<s.length)return false;for(let o=0;o<s.length;o++)if(!ci(i[o],s[o]))return false;return i.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:i.slice(s.length).every(o=>ci(o,t.items))}function GC(i,e){if(e.type==="regexp")try{let t=Nc(e.source,e.flags);return t.lastIndex=0,t.test(i.join(" "))}catch{return false}return e.type==="literal"?i.join(" ")===e.value:zs(i,e.schema)}function $C(i){let e=i.split(/\r?\n/),t=[];for(let n=0;n<e.length;n++){let r=e[n];for(let a of r.matchAll(MC)){let s=(a[1]??"").trim();if(!s)continue;let o=O.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:n+1,command:s,tokens:o});}}return t}var Ll;(n=>{function i(r,a={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let s=[];try{return {json:new Pc.Compiler(r,{errorHandler:(h,c)=>{let p=h.replace(/^[A-Z]+: line \d+: ?/,""),f=h.match(/line (\d+)/);s.push({message:p,type:c,line:f?Number(f[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:h=>h,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:s}}catch{let l=false,u={...a,textSource:r};return e(s,()=>{l=true;},u),l?i(u.textSource,a):{issues:s}}}n.compile=i;function e(r,a,s){let{functions:o,initialVarsToRemove:l,labelToRemove:u}=s,h=r.find(c=>c.type===Fc.ErrorType.Error);if(h){if(h.message.includes("Divert target not found")){let c=h.message.match(/Divert target not found: '-> (\w+)'/);if(c?.[1]){let p=c[1],f=`
71
69
 
72
70
  === ${p} ===
73
71
 
@@ -83,9 +81,9 @@ ${S}`),S&&(o=true),s=x.getLogichValue(m.glueEnabled,e)||false,S)}),u=x.getLogich
83
81
 
84
82
  ~ return
85
83
 
86
- `;return s.textSource=s.textSource.concat(f),o.push({name:p,args:0}),u.push(p),a()}}if(h.message.includes(" arguments, but got ")){let c=h.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(c?.[1]){let p=c[1],f=parseInt(c[3]||"0",10),y=f>0?Array.from({length:f},(b,m)=>`arg${m+1}`).join(", "):"",C=`
84
+ `;return s.textSource=s.textSource.concat(f),o.push({name:p,args:0}),u.push(p),a()}}if(h.message.includes(" arguments, but got ")){let c=h.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(c?.[1]){let p=c[1],f=parseInt(c[3]||"0",10),v=f>0?Array.from({length:f},(D,C)=>`arg${C+1}`).join(", "):"",g=`
87
85
 
88
- === function ${p}(${y}) ===
86
+ === function ${p}(${v}) ===
89
87
 
90
88
  ~ return
91
89
 
@@ -95,10 +93,10 @@ ${S}`),S&&(o=true),s=x.getLogichValue(m.glueEnabled,e)||false,S)}),u=x.getLogich
95
93
 
96
94
  ~ return
97
95
 
98
- `,""),s.textSource=s.textSource.concat(C);let A=o.find(b=>b.name===p);return A?A.args=f:(o.push({name:p,args:f}),u.push(p)),a()}}if(h.message.includes("Could not find target for read count")){let c=h.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(c?.[1]){let p=c[1],[f,y]=p.split("."),C=`
96
+ `,""),s.textSource=s.textSource.concat(g);let A=o.find(D=>D.name===p);return A?A.args=f:(o.push({name:p,args:f}),u.push(p)),a()}}if(h.message.includes("Could not find target for read count")){let c=h.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(c?.[1]){let p=c[1],[f,v]=p.split("."),g=`
99
97
 
100
- LIST ${f} = ${y}
98
+ LIST ${f} = ${v}
101
99
 
102
- `;return s.textSource=s.textSource.concat(C),s.initialVarsToRemove.push(f),s.initialVarsToRemove.push(`${f}.${y}`),a()}}if(h.message.includes("variable for increment could not be found")){let c=h.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(c?.[1]){let p=c[1],f=`VAR ${p} = 0
100
+ `;return s.textSource=s.textSource.concat(g),s.initialVarsToRemove.push(f),s.initialVarsToRemove.push(`${f}.${v}`),a()}}if(h.message.includes("variable for increment could not be found")){let c=h.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(c?.[1]){let p=c[1],f=`VAR ${p} = 0
103
101
 
104
- `;return s.textSource=f.concat(s.textSource),s.initialVarsToRemove.push(p),a()}}return r.forEach(c=>{let p=c.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);p?.[1]&&(c.message=`The function '${p[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:r}}return {issues:r}}n.getErrors=e;function t(r,a){return wy(r).filter(({tokens:s})=>!a.some(({validation:o})=>Ay(s,o)))}n.getUnknownHashtagCommands=t;})(Zl||={});var eu=oa(ln());function xy(i){if(!i||i.length===0)return;let e=new Set;for(let t of i){let n=typeof t=="string"?t:t?.id;typeof n=="string"&&n.length>0&&e.add(n);}return e.size>0?e:void 0}function Yc(i,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:i},{json:n,issues:r}=Zl.compile(i,t);if(r.forEach(({message:s,type:o})=>{o===eu.ErrorType.Error?W.error(`Ink compilation error: ${s}`):o===eu.ErrorType.Warning?W.warn(`Ink compilation warning: ${s}`):W.info(`Ink compilation info: ${s}`);}),!n){W.error("No JSON generated from ink file");return}let a;try{a=kn.parse(n);}catch{W.error("Error parsing ink file");return}return t.enums=a.listDefs||{},Fa.inkToJson(a,{...t,characterIds:xy(e.characters)})}async function Qc(i,e={}){Array.isArray(i)||(i=[i]),Ea();let t={functions:[],enums:{},characters:e.characters},n=i.map(async r=>{let a=Yc(r,t);return a&&await va(a,{operationStringConvert:O.run,skipEmptyDialogs:true}),r});return await Promise.all(n)}async function tu(i){return Ea(),await va(i,{operationStringConvert:O.run,skipEmptyDialogs:true})}async function _y(i,e,t={}){let n={importJson:async s=>{await tu(s);},importInkText:s=>Qc(s,{characters:t.characters})},r=i&&typeof i=="object"&&"inkJson"in i?i.inkJson:void 0;if(r&&r.length>0){await n.importJson(r);return}let a=i&&typeof i=="object"&&"inkText"in i?i.inkText:typeof i=="string"?i:void 0;typeof a=="string"&&await n.importInkText(a);}async function Oy(i={}){undefined&&(virtual_pixiVnInk.inkJsons&&virtual_pixiVnInk.inkJsons.length>0&&await tu(virtual_pixiVnInk.inkJsons),undefined.on("ink-updated",async e=>{await _y(e,void 0,i);}),undefined.on("ink-error-cleared",()=>{document.querySelectorAll("vite-error-overlay").forEach(e=>{e.close();});}));}exports.setupInkHmrListener=Oy;
102
+ `;return s.textSource=f.concat(s.textSource),s.initialVarsToRemove.push(p),a()}}return r.forEach(c=>{let p=c.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);p?.[1]&&(c.message=`The function '${p[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:r}}return {issues:r}}n.getErrors=e;function t(r,a){return $C(r).filter(({tokens:s})=>!a.some(({validation:o})=>GC(s,o)))}n.getUnknownHashtagCommands=t;})(Ll||={});var Bl=Us(Kt());function JC(i){if(!i||i.length===0)return;let e=new Set;for(let t of i){let n=typeof t=="string"?t:t?.id;typeof n=="string"&&n.length>0&&e.add(n);}return e.size>0?e:void 0}function Ic(i,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:i},{json:n,issues:r}=Ll.compile(i,t);if(r.forEach(({message:s,type:o})=>{o===Bl.ErrorType.Error?W.error(`Ink compilation error: ${s}`):o===Bl.ErrorType.Warning?W.warn(`Ink compilation warning: ${s}`):W.info(`Ink compilation info: ${s}`);}),!n){W.error("No JSON generated from ink file");return}let a;try{a=bn.parse(n);}catch{W.error("Error parsing ink file");return}return t.enums=a.listDefs||{},ma.inkToJson(a,{...t,characterIds:JC(e.characters)})}async function Vc(i,e={}){Array.isArray(i)||(i=[i]),sa();let t={functions:[],enums:{},characters:e.characters},n=i.map(async r=>{let a=Ic(r,t);return a&&await ra(a,{operationStringConvert:O.run,skipEmptyDialogs:true}),r});return await Promise.all(n)}async function Wl(i){return sa(),await ra(i,{operationStringConvert:O.run,skipEmptyDialogs:true})}async function HC(i,e,t={}){let n={importJson:async s=>{await Wl(s);},importInkText:s=>Vc(s,{characters:t.characters})},r=i&&typeof i=="object"&&"inkJson"in i?i.inkJson:void 0;if(r&&r.length>0){await n.importJson(r);return}let a=i&&typeof i=="object"&&"inkText"in i?i.inkText:typeof i=="string"?i:void 0;typeof a=="string"&&await n.importInkText(a);}async function zC(i={}){undefined&&(virtual_pixiVnInk.inkJsons&&virtual_pixiVnInk.inkJsons.length>0&&await Wl(virtual_pixiVnInk.inkJsons),undefined.on("ink-updated",async e=>{await HC(e,void 0,i);}),undefined.on("ink-error-cleared",()=>{document.querySelectorAll("vite-error-overlay").forEach(e=>{e.close();});}));}exports.setupInkHmrListener=zC;