@drincs/pixi-vn-ink 0.9.7 → 0.9.9

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.
@@ -0,0 +1,50 @@
1
+ var iu=Object.create;var Vr=Object.defineProperty;var ru=Object.getOwnPropertyDescriptor;var su=Object.getOwnPropertyNames;var au=Object.getPrototypeOf,ou=Object.prototype.hasOwnProperty;var lu=(o,t,e)=>t in o?Vr(o,t,{enumerable:true,configurable:true,writable:true,value:e}):o[t]=e;var tp=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var d=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var uu=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of su(t))!ou.call(o,i)&&i!==e&&Vr(o,i,{get:()=>t[i],enumerable:!(n=ru(t,i))||n.enumerable});return o};var so=(o,t,e)=>(e=o!=null?iu(au(o)):{},uu(t||!o||!o.__esModule?Vr(e,"default",{value:o,enumerable:true}):e,o));var ep=(o,t,e)=>lu(o,typeof t!="symbol"?t+"":t,e);var we=d(fn=>{Object.defineProperty(fn,"__esModule",{value:true});fn.ErrorType=void 0;var ao;(function(o){o[o.Author=0]="Author",o[o.Warning=1]="Warning",o[o.Error=2]="Error";})(ao||(fn.ErrorType=ao={}));});var Dr=d(pn=>{Object.defineProperty(pn,"__esModule",{value:true});pn.CompilerOptions=void 0;var Wr=class{constructor(t=null,e=[],n=false,i=null,a=null){this.sourceFilename=t,this.pluginNames=e,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=a;}};pn.CompilerOptions=Wr;});var oo=d(mn=>{Object.defineProperty(mn,"__esModule",{value:true});mn.DebugSourceRange=void 0;var Lr=class{constructor(t,e,n){this.length=t,this.debugMetadata=e,this.text=n;}};mn.DebugSourceRange=Lr;});var lo=d(gn=>{Object.defineProperty(gn,"__esModule",{value:true});gn.Argument=void 0;var qr=class{constructor(t=null,e=null,n=null){this.identifier=t,this.isByReference=e,this.isDivertTarget=n;}get typeName(){return "Argument"}};gn.Argument=qr;});var P=d(D=>{Object.defineProperty(D,"__esModule",{value:true});D.filterUndef=D.isEquatable=D.nullIfUndefined=D.asINamedContentOrNull=D.asBooleanOrThrows=D.asNumberOrThrows=D.asOrThrows=D.asOrNull=void 0;function hu(o,t){return o instanceof t?uo(o):null}D.asOrNull=hu;function cu(o,t){if(o instanceof t)return uo(o);throw new Error(`${o} is not of type ${t}`)}D.asOrThrows=cu;function du(o){if(typeof o=="number")return o;throw new Error(`${o} is not a number`)}D.asNumberOrThrows=du;function fu(o){if(typeof o=="boolean")return o;throw new Error(`${o} is not a boolean`)}D.asBooleanOrThrows=fu;function pu(o){return o.hasValidName&&o.name?o:null}D.asINamedContentOrNull=pu;function mu(o){return typeof o>"u"?null:o}D.nullIfUndefined=mu;function gu(o){return typeof o=="object"&&typeof o.Equals=="function"}D.isEquatable=gu;function uo(o,t){return o}function Cu(o){return o!=null}D.filterUndef=Cu;});var N=d(Cn=>{Object.defineProperty(Cn,"__esModule",{value:true});Cn.ParsedObject=void 0;var ho=P(),jr=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=t=>{this.content===null&&(this.content=[]);let e=Array.isArray(t)?t:[t];for(let n of e)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(t))return t},this.InsertContent=(t,e)=>(this.content===null&&(this.content=[]),e.parent=this,this.content.splice(t,0,e),e),this.Find=t=>(e=null)=>{let n=(0, ho.asOrNull)(this,t);if(n!==null&&(e===null||e(n)===true))return n;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(t)(e);if(a)return a}return null},this.FindAll=t=>(e,n)=>{let i=Array.isArray(n)?n:[],a=(0, ho.asOrNull)(this,t);if(a!==null&&(!e||e(a)===true)&&i.push(a),this.content===null)return [];for(let r of this.content)r.FindAll&&r.FindAll(t)(e,i);return i},this.Warning=(t,e=null)=>{this.Error(t,e,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let t=this;for(;t.parent;)t=t.parent;return t}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(t){this._runtimeObject=t;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let t=[],e=this.parent;for(;e;)t.push(e),e=e.parent;return t=t.reverse(),t}ResolveReferences(t){if(this.content!==null)for(let e of this.content)e.ResolveReferences(t);}Error(t,e=null,n=false){if(e===null&&(e=this),!(e._alreadyHadError&&!n||e._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(t,e,n);else throw new Error(`No parent object to send error to: ${t}`);n?e._alreadyHadWarning=true:e._alreadyHadError=true;}}};Cn.ParsedObject=jr;});var Sn=d(vn=>{Object.defineProperty(vn,"__esModule",{value:true});vn.AuthorWarning=void 0;var vu=N(),Mr=class extends vu.ParsedObject{constructor(t){super(),this.warningMessage=t,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};vn.AuthorWarning=Mr;});var Z=d(Pe=>{Object.defineProperty(Pe,"__esModule",{value:true});Pe.Path=void 0;var te=class o{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let t=arguments[0];this.componentsString=t;}else if(arguments[0]instanceof o.Component&&arguments[1]instanceof o){let t=arguments[0],e=arguments[1];this._components.push(t),this._components=this._components.concat(e._components);}else if(arguments[0]instanceof Array){let t=arguments[0],e=!!arguments[1];this._components=this._components.concat(t),this._isRelative=e;}}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 t=this._components.slice(1,this._components.length);return new o(t)}else return o.self}get length(){return this._components.length}get lastComponent(){let t=this._components.length-1;return t>=0?this._components[t]:null}get containsNamedComponent(){for(let t=0,e=this._components.length;t<e;t++)if(!this._components[t].isIndex)return true;return false}static get self(){let t=new o;return t._isRelative=true,t}GetComponent(t){return this._components[t]}PathByAppendingPath(t){let e=new o,n=0;for(let i=0;i<t._components.length&&t._components[i].isParent;++i)n++;for(let i=0;i<this._components.length-n;++i)e._components.push(this._components[i]);for(let i=n;i<t._components.length;++i)e._components.push(t._components[i]);return e}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(t){if(this._components.length=0,this._componentsString=t,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let e=this._componentsString.split(".");for(let n of e)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new o.Component(parseInt(n))):this._components.push(new o.Component(n));}toString(){return this.componentsString}Equals(t){if(t==null||t._components.length!=this._components.length||t.isRelative!=this.isRelative)return false;for(let e=0,n=t._components.length;e<n;e++)if(!t._components[e].Equals(this._components[e]))return false;return true}PathByAppendingComponent(t){let e=new o;return e._components.push(...this._components),e._components.push(t),e}};Pe.Path=te;te.parentId="^";(function(o){class t{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==o.parentId}static ToParent(){return new t(o.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}}o.Component=t;})(te||(Pe.Path=te={}));});var Oe=d(yn=>{Object.defineProperty(yn,"__esModule",{value:true});yn.Debug=void 0;var co;(function(o){function t(n,i,a){e(n instanceof i,a);}o.AssertType=t;function e(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}o.Assert=e;})(co||(yn.Debug=co={}));});var B=d(ee=>{Object.defineProperty(ee,"__esModule",{value:true});ee.throwNullException=ee.NullException=void 0;var _n=class extends Error{};ee.NullException=_n;function Su(o){throw new _n(`${o} is null or undefined`)}ee.throwNullException=Su;});var Q=d(En=>{Object.defineProperty(En,"__esModule",{value:true});En.InkObject=void 0;var ne=Z(),xe=F(),Br=Oe(),ie=P(),bn=B(),Gr=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(t){this._debugMetadata=t;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(t){if(t===null)return null;let e=this.rootContentContainer;if(e){let n=e.ContentAtPath(t).obj;if(n){let i=n.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new ne.Path;else {let t=[],e=this,n=(0, ie.asOrNull)(e.parent,xe.Container);for(;n!==null;){let i=(0, ie.asINamedContentOrNull)(e);if(i!=null&&i.hasValidName){if(i.name===null)return (0, bn.throwNullException)("namedChild.name");t.unshift(new ne.Path.Component(i.name));}else t.unshift(new ne.Path.Component(n.content.indexOf(e)));e=n,n=(0, ie.asOrNull)(n.parent,xe.Container);}this._path=new ne.Path(t);}return this._path}ResolvePath(t){if(t===null)return (0, bn.throwNullException)("path");if(t.isRelative){let e=(0, ie.asOrNull)(this,xe.Container);return e===null&&(Br.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),e=(0, ie.asOrNull)(this.parent,xe.Container),Br.Debug.Assert(e!==null,"Expected parent to be a container"),Br.Debug.Assert(t.GetComponent(0).isParent),t=t.tail),e===null?(0, bn.throwNullException)("nearestContainer"):e.ContentAtPath(t)}else {let e=this.rootContentContainer;return e===null?(0, bn.throwNullException)("contentContainer"):e.ContentAtPath(t)}}ConvertPathToRelative(t){let e=this.path,n=Math.min(t.length,e.length),i=-1;for(let l=0;l<n;++l){let u=e.GetComponent(l),h=t.GetComponent(l);if(u.Equals(h))i=l;else break}if(i==-1)return t;let a=e.componentCount-1-i,r=[];for(let l=0;l<a;++l)r.push(ne.Path.Component.ToParent());for(let l=i+1;l<t.componentCount;++l)r.push(t.GetComponent(l));return new ne.Path(r,true)}CompactPathString(t){let e=null,n=null;return t.isRelative?(n=t.componentsString,e=this.path.PathByAppendingPath(t).componentsString):(n=this.ConvertPathToRelative(t).componentsString,e=t.componentsString),n.length<e.length?n:e}get rootContentContainer(){let t=this;for(;t.parent;)t=t.parent;return (0, ie.asOrNull)(t,xe.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(t,e,n){t[e]&&(t[e]=null),t[e]=n,t[e]&&(t[e].parent=this);}Equals(t){return t===this}};En.InkObject=Gr;});var Bt=d(wn=>{Object.defineProperty(wn,"__esModule",{value:true});wn.StringBuilder=void 0;var $r=class{constructor(t){t=typeof t<"u"?t.toString():"",this.string=t;}get Length(){return this.string.length}Append(t){t!==null&&(this.string+=t);}AppendLine(t){typeof t<"u"&&this.Append(t),this.string+=`
2
+ `;}AppendFormat(t,...e){this.string+=t.replace(/{(\d+)}/g,(n,i)=>typeof e[i]<"u"?e[i]:n);}toString(){return this.string}Clear(){this.string="";}};wn.StringBuilder=$r;});var et=d(re=>{Object.defineProperty(re,"__esModule",{value:true});re.InkList=re.InkListItem=void 0;var mt=B(),yu=Bt(),tt=class o{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let t=arguments[0],e=arguments[1];this.originName=t,this.itemName=e;}else if(arguments[0]){let e=arguments[0].toString().split(".");this.originName=e[0],this.itemName=e[1];}}static get Null(){return new o(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(t){if(t instanceof o){let e=t;return e.itemName==this.itemName&&e.originName==this.originName}return false}copy(){return new o(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let e=JSON.parse(t);if(!o.isLikeInkListItem(e))return o.Null;let n=e;return new o(n.originName,n.itemName)}static isLikeInkListItem(t){return !(typeof t!="object"||!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName")||typeof t.originName!="string"&&typeof t.originName!==null||typeof t.itemName!="string"&&typeof t.itemName!==null)}};re.InkListItem=tt;var Ur=class o extends Map{constructor(){if(super(arguments[0]instanceof o?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof o){let t=arguments[0],e=t.originNames;e!==null&&(this._originNames=e.slice()),t.origins!==null&&(this.origins=t.origins.slice());}else if(typeof arguments[0]=="string"){let t=arguments[0],e=arguments[1];if(this.SetInitialOriginName(t),e.listDefinitions===null)return (0, mt.throwNullException)("originStory.listDefinitions");let n=e.listDefinitions.TryListGetDefinition(t,null);if(n.exists){if(n.result===null)return (0, mt.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+t)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let t=arguments[0];this.Add(t.Key,t.Value);}}static FromString(t,e){var n;if(t==null||t=="")return new o;let i=(n=e.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(t);if(i)return i.value===null?(0, mt.throwNullException)("listValue.value"):new o(i.value);throw new Error("Could not find the InkListItem from the string '"+t+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(t,e=null){if(t instanceof tt){let n=t;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, mt.throwNullException)("this.origins");for(let i of this.origins)if(i.name==n.originName){let a=i.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(t!==null){let n=t,i=null;if(this.origins===null)return (0, mt.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, mt.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(e==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=o.FromString(n,e).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new tt(i.name,n),r=i.ValueForItem(a);this.Add(a,r);}}}ContainsItemNamed(t){for(let[e]of this)if(tt.fromSerializedKey(e).itemName==t)return true;return false}ContainsKey(t){return this.has(t.serialized())}Add(t,e){let n=t.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${t}`);this.set(n,e);}Remove(t){return this.delete(t.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let t=this.maxItem.Key.originName,e=null;return this.origins.every(n=>n.name==t?(e=n,false):true),e}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let e=tt.fromSerializedKey(t);if(e.originName===null)return (0, mt.throwNullException)("item.originName");this._originNames.push(e.originName);}}return this._originNames}SetInitialOriginName(t){this._originNames=[t];}SetInitialOriginNames(t){t==null?this._originNames=null:this._originNames=t.slice();}get maxItem(){let t={Key:tt.Null,Value:0};for(let[e,n]of this){let i=tt.fromSerializedKey(e);(t.Key.isNull||n>t.Value)&&(t={Key:i,Value:n});}return t}get minItem(){let t={Key:tt.Null,Value:0};for(let[e,n]of this){let i=tt.fromSerializedKey(e);(t.Key.isNull||n<t.Value)&&(t={Key:i,Value:n});}return t}get inverse(){let t=new o;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let a=tt.fromSerializedKey(n);this.ContainsKey(a)||t.Add(a,i);}return t}get all(){let t=new o;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let a=tt.fromSerializedKey(n);t.set(a.serialized(),i);}return t}Union(t){let e=new o(this);for(let[n,i]of t)e.set(n,i);return e}Intersect(t){let e=new o;for(let[n,i]of this)t.has(n)&&e.set(n,i);return e}HasIntersection(t){for(let[e]of this)if(t.has(e))return true;return false}Without(t){let e=new o(this);for(let[n]of t)e.delete(n);return e}Contains(t){if(typeof t=="string")return this.ContainsItemNamed(t);let e=t;if(e.size==0||this.size==0)return false;for(let[n]of e)if(!this.has(n))return false;return true}GreaterThan(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>t.maxItem.Value}GreaterThanOrEquals(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value}LessThan(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<t.minItem.Value}LessThanOrEquals(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<=t.maxItem.Value&&this.minItem.Value<=t.minItem.Value}MaxAsList(){return this.Count>0?new o(this.maxItem):new o}MinAsList(){return this.Count>0?new o(this.minItem):new o}ListWithSubRange(t,e){if(this.Count==0)return new o;let n=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?i=t:t instanceof o&&t.Count>0&&(i=t.minItem.Value),Number.isInteger(e)?a=e:e instanceof o&&e.Count>0&&(a=e.maxItem.Value);let r=new o;r.SetInitialOriginNames(this.originNames);for(let s of n)s.Value>=i&&s.Value<=a&&r.Add(s.Key,s.Value);return r}Equals(t){if(!(t instanceof o)||t.Count!=this.Count)return false;for(let[e]of this)if(!t.has(e))return false;return true}get orderedItems(){let t=new Array;for(let[e,n]of this){let i=tt.fromSerializedKey(e);t.push({Key:i,Value:n});}return t.sort((e,n)=>e.Key.originName===null?(0, mt.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, mt.throwNullException)("y.Key.originName"):e.Value==n.Value?e.Key.originName.localeCompare(n.Key.originName):e.Value<n.Value?-1:e.Value>n.Value?1:0),t}get singleItem(){for(let t of this.orderedItems)return t.Key;return null}toString(){let t=this.orderedItems,e=new yu.StringBuilder;for(let n=0;n<t.length;n++){n>0&&e.Append(", ");let i=t[n].Key;if(i.itemName===null)return (0, mt.throwNullException)("item.itemName");e.Append(i.itemName);}return e.toString()}valueOf(){return NaN}};re.InkList=Ur;});var Te=d(Pn=>{Object.defineProperty(Pn,"__esModule",{value:true});Pn.StoryException=void 0;var Kr=class extends Error{constructor(t){super(t),this.useEndLineNumber=false,this.message=t,this.name="StoryException";}};Pn.StoryException=Kr;});var se=d(Ft=>{Object.defineProperty(Ft,"__esModule",{value:true});Ft.tryParseFloat=Ft.tryParseInt=Ft.tryGetValueFromMap=void 0;function _u(o,t,e){if(o===null)return {result:e,exists:false};let n=o.get(t);return typeof n>"u"?{result:e,exists:false}:{result:n,exists:true}}Ft.tryGetValueFromMap=_u;function bu(o,t=0){let e=parseInt(o);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}Ft.tryParseInt=bu;function Eu(o,t=0){let e=parseFloat(o);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}Ft.tryParseFloat=Eu;});var I=d(A=>{Object.defineProperty(A,"__esModule",{value:true});A.ValueType=A.ListValue=A.VariablePointerValue=A.DivertTargetValue=A.StringValue=A.FloatValue=A.IntValue=A.BoolValue=A.Value=A.AbstractValue=void 0;var fo=Q(),po=Z(),Gt=et(),wu=Te(),Ne=P(),mo=se(),at=B(),On=class o extends fo.InkObject{static Create(t,e){if(e){if(e===T.Int&&Number.isInteger(Number(t)))return new Ct(Number(t));if(e===T.Float&&!isNaN(t))return new vt(Number(t))}if(typeof t=="boolean")return new ae(!!t);if(typeof t=="string")return new xt(String(t));if(Number.isInteger(Number(t)))return new Ct(Number(t));if(isNaN(t)){if(t instanceof po.Path)return new xn((0, Ne.asOrThrows)(t,po.Path));if(t instanceof Gt.InkList)return new Tn((0, Ne.asOrThrows)(t,Gt.InkList))}else return new vt(Number(t));return null}Copy(){return (0, Ne.asOrThrows)(o.Create(this.valueObject),fo.InkObject)}BadCastException(t){return new wu.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+t)}};A.AbstractValue=On;var gt=class extends On{constructor(t){super(),this.value=t;}get valueObject(){return this.value}toString(){return this.value===null?(0, at.throwNullException)("Value.value"):this.value.toString()}};A.Value=gt;var ae=class extends gt{constructor(t){super(t||false);}get isTruthy(){return !!this.value}get valueType(){return T.Bool}Cast(t){if(this.value===null)return (0, at.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==T.Int)return new Ct(this.value?1:0);if(t==T.Float)return new vt(this.value?1:0);if(t==T.String)return new xt(this.value?"true":"false");throw this.BadCastException(t)}toString(){return this.value?"true":"false"}};A.BoolValue=ae;var Ct=class extends gt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return T.Int}Cast(t){if(this.value===null)return (0, at.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==T.Bool)return new ae(this.value!==0);if(t==T.Float)return new vt(this.value);if(t==T.String)return new xt(""+this.value);throw this.BadCastException(t)}};A.IntValue=Ct;var vt=class extends gt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return T.Float}Cast(t){if(this.value===null)return (0, at.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==T.Bool)return new ae(this.value!==0);if(t==T.Int)return new Ct(this.value);if(t==T.String)return new xt(""+this.value);throw this.BadCastException(t)}};A.FloatValue=vt;var xt=class extends gt{constructor(t){if(super(t||""),this._isNewline=this.value==`
3
+ `,this._isInlineWhitespace=true,this.value===null)return (0, at.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(e=>e!=" "&&e!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return T.String}get isTruthy(){return this.value===null?(0, at.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(t){if(t==this.valueType)return this;if(t==T.Int){let e=(0, mo.tryParseInt)(this.value);if(e.exists)return new Ct(e.result);throw this.BadCastException(t)}if(t==T.Float){let e=(0, mo.tryParseFloat)(this.value);if(e.exists)return new vt(e.result);throw this.BadCastException(t)}throw this.BadCastException(t)}};A.StringValue=xt;var xn=class extends gt{constructor(t=null){super(t);}get valueType(){return T.DivertTarget}get targetPath(){return this.value===null?(0, at.throwNullException)("Value.value"):this.value}set targetPath(t){this.value=t;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(t){if(t==this.valueType)return this;throw this.BadCastException(t)}toString(){return "DivertTargetValue("+this.targetPath+")"}};A.DivertTargetValue=xn;var Hr=class o extends gt{constructor(t,e=-1){super(t),this._contextIndex=e;}get contextIndex(){return this._contextIndex}set contextIndex(t){this._contextIndex=t;}get variableName(){return this.value===null?(0, at.throwNullException)("Value.value"):this.value}set variableName(t){this.value=t;}get valueType(){return T.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(t){if(t==this.valueType)return this;throw this.BadCastException(t)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new o(this.variableName,this.contextIndex)}};A.VariablePointerValue=Hr;var Tn=class o extends gt{get isTruthy(){return this.value===null?(0, at.throwNullException)("this.value"):this.value.Count>0}get valueType(){return T.List}Cast(t){if(this.value===null)return (0, at.throwNullException)("Value.value");if(t==T.Int){let e=this.value.maxItem;return e.Key.isNull?new Ct(0):new Ct(e.Value)}else if(t==T.Float){let e=this.value.maxItem;return e.Key.isNull?new vt(0):new vt(e.Value)}else if(t==T.String){let e=this.value.maxItem;return e.Key.isNull?new xt(""):new xt(e.Key.toString())}if(t==this.valueType)return this;throw this.BadCastException(t)}constructor(t,e){super(null),!t&&!e?this.value=new Gt.InkList:t instanceof Gt.InkList?this.value=new Gt.InkList(t):t instanceof Gt.InkListItem&&typeof e=="number"&&(this.value=new Gt.InkList({Key:t,Value:e}));}static RetainListOriginsForAssignment(t,e){let n=(0, Ne.asOrNull)(t,o),i=(0, Ne.asOrNull)(e,o);if(i&&i.value===null)return (0, at.throwNullException)("newList.value");if(n&&n.value===null)return (0, at.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};A.ListValue=Tn;var T;(function(o){o[o.Bool=-1]="Bool",o[o.Int=0]="Int",o[o.Float=1]="Float",o[o.List=2]="List",o[o.String=3]="String",o[o.DivertTarget=4]="DivertTarget",o[o.VariablePointer=5]="VariablePointer";})(T||(A.ValueType=T={}));});var go=d(Nn=>{Object.defineProperty(Nn,"__esModule",{value:true});Nn.SearchResult=void 0;var Pu=F(),Jr=class o{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof Pu.Container?this.obj:null}copy(){let t=new o;return t.obj=this.obj,t.approximate=this.approximate,t}};Nn.SearchResult=Jr;});var F=d(Ae=>{Object.defineProperty(Ae,"__esModule",{value:true});Ae.Container=void 0;var Ou=I(),Co=B(),xu=Bt(),oe=Q(),Tu=go(),vo=Z(),So=Oe(),Nu=se(),kt=P(),Ie=class o extends oe.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(t){this.AddContent(t);}get namedOnlyContent(){let t=new Map;for(let[e,n]of this.namedContent){let i=(0, kt.asOrThrows)(n,oe.InkObject);t.set(e,i);}for(let e of this.content){let n=(0, kt.asINamedContentOrNull)(e);n!=null&&n.hasValidName&&t.delete(n.name);}return t.size==0&&(t=null),t}set namedOnlyContent(t){let e=this.namedOnlyContent;if(e!=null)for(let[n]of e)this.namedContent.delete(n);if(t!=null)for(let[,n]of t){let i=(0, kt.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let t=0;return this.visitsShouldBeCounted&&(t|=o.CountFlags.Visits),this.turnIndexShouldBeCounted&&(t|=o.CountFlags.Turns),this.countingAtStartOnly&&(t|=o.CountFlags.CountStartOnly),t==o.CountFlags.CountStartOnly&&(t=0),t}set countFlags(t){let e=t;(e&o.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(e&o.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(e&o.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let t=[],e=this;for(;e instanceof o;)e.content.length>0&&(t.push(new vo.Path.Component(0)),e=e.content[0]);return new vo.Path(t)}AddContent(t){if(t instanceof Array){let e=t;for(let n of e)this.AddContent(n);}else {let e=t;if(this._content.push(e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}}TryAddNamedContent(t){let e=(0, kt.asINamedContentOrNull)(t);e!=null&&e.hasValidName&&this.AddToNamedContentOnly(e);}AddToNamedContentOnly(t){So.Debug.AssertType(t,oe.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let e=(0, kt.asOrThrows)(t,oe.InkObject);if(e.parent=this,t.name===null)return (0, Co.throwNullException)("namedContentObj.name");this.namedContent.set(t.name,t);}ContentAtPath(t,e=0,n=-1){n==-1&&(n=t.length);let i=new Tu.SearchResult;i.approximate=false;let a=this,r=this;for(let s=e;s<n;++s){let l=t.GetComponent(s);if(a==null){i.approximate=true;break}let u=a.ContentWithPathComponent(l);if(u==null){i.approximate=true;break}let h=(0, kt.asOrNull)(u,o);if(s<n-1&&h==null){i.approximate=true;break}r=u,a=h;}return i.obj=r,i}InsertContent(t,e){if(this.content.splice(e,0,t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}AddContentsOfContainer(t){this.content.push(...t.content);for(let e of t.content)e.parent=this,this.TryAddNamedContent(e);}ContentWithPathComponent(t){if(t.isIndex)return t.index>=0&&t.index<this.content.length?this.content[t.index]:null;if(t.isParent)return this.parent;{if(t.name===null)return (0, Co.throwNullException)("component.name");let e=(0, Nu.tryGetValueFromMap)(this.namedContent,t.name,null);return e.exists?(0, kt.asOrThrows)(e.result,oe.InkObject):null}}BuildStringOfHierarchy(){let t;if(arguments.length==0)return t=new xu.StringBuilder,this.BuildStringOfHierarchy(t,0,null),t.toString();t=arguments[0];let e=arguments[1],n=arguments[2];function i(){for(let s=0;s<4*e;++s)t.Append(" ");}i(),t.Append("["),this.hasValidName&&t.AppendFormat(" ({0})",this.name),this==n&&t.Append(" <---"),t.AppendLine(),e++;for(let r=0;r<this.content.length;++r){let s=this.content[r];s instanceof o?s.BuildStringOfHierarchy(t,e,n):(i(),s instanceof Ou.StringValue?(t.Append('"'),t.Append(s.toString().replace(`
4
+ `,"\\n")),t.Append('"')):t.Append(s.toString())),r!=this.content.length-1&&t.Append(","),!(s instanceof o)&&s==n&&t.Append(" <---"),t.AppendLine();}let a=new Map;for(let[r,s]of this.namedContent)this.content.indexOf((0, kt.asOrThrows)(s,oe.InkObject))>=0||a.set(r,s);if(a.size>0){i(),t.AppendLine("-- named: --");for(let[,r]of a)So.Debug.AssertType(r,o,"Can only print out named Containers"),r.BuildStringOfHierarchy(t,e,n),t.AppendLine();}e--,i(),t.Append("]");}};Ae.Container=Ie;(function(o){(function(e){e[e.Start=0]="Start",e[e.Visits=1]="Visits",e[e.Turns=2]="Turns",e[e.CountStartOnly=4]="CountStartOnly";})(o.CountFlags||(o.CountFlags={}));})(Ie||(Ae.Container=Ie={}));});var G=d(ke=>{Object.defineProperty(ke,"__esModule",{value:true});ke.ControlCommand=void 0;var Iu=Q(),Fe=class o extends Iu.InkObject{get commandType(){return this._commandType}constructor(t=o.CommandType.NotSet){super(),this._commandType=t;}Copy(){return new o(this.commandType)}static EvalStart(){return new o(o.CommandType.EvalStart)}static EvalOutput(){return new o(o.CommandType.EvalOutput)}static EvalEnd(){return new o(o.CommandType.EvalEnd)}static Duplicate(){return new o(o.CommandType.Duplicate)}static PopEvaluatedValue(){return new o(o.CommandType.PopEvaluatedValue)}static PopFunction(){return new o(o.CommandType.PopFunction)}static PopTunnel(){return new o(o.CommandType.PopTunnel)}static BeginString(){return new o(o.CommandType.BeginString)}static EndString(){return new o(o.CommandType.EndString)}static NoOp(){return new o(o.CommandType.NoOp)}static ChoiceCount(){return new o(o.CommandType.ChoiceCount)}static Turns(){return new o(o.CommandType.Turns)}static TurnsSince(){return new o(o.CommandType.TurnsSince)}static ReadCount(){return new o(o.CommandType.ReadCount)}static Random(){return new o(o.CommandType.Random)}static SeedRandom(){return new o(o.CommandType.SeedRandom)}static VisitIndex(){return new o(o.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new o(o.CommandType.SequenceShuffleIndex)}static StartThread(){return new o(o.CommandType.StartThread)}static Done(){return new o(o.CommandType.Done)}static End(){return new o(o.CommandType.End)}static ListFromInt(){return new o(o.CommandType.ListFromInt)}static ListRange(){return new o(o.CommandType.ListRange)}static ListRandom(){return new o(o.CommandType.ListRandom)}static BeginTag(){return new o(o.CommandType.BeginTag)}static EndTag(){return new o(o.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};ke.ControlCommand=Fe;(function(o){(function(e){e[e.NotSet=-1]="NotSet",e[e.EvalStart=0]="EvalStart",e[e.EvalOutput=1]="EvalOutput",e[e.EvalEnd=2]="EvalEnd",e[e.Duplicate=3]="Duplicate",e[e.PopEvaluatedValue=4]="PopEvaluatedValue",e[e.PopFunction=5]="PopFunction",e[e.PopTunnel=6]="PopTunnel",e[e.BeginString=7]="BeginString",e[e.EndString=8]="EndString",e[e.NoOp=9]="NoOp",e[e.ChoiceCount=10]="ChoiceCount",e[e.Turns=11]="Turns",e[e.TurnsSince=12]="TurnsSince",e[e.ReadCount=13]="ReadCount",e[e.Random=14]="Random",e[e.SeedRandom=15]="SeedRandom",e[e.VisitIndex=16]="VisitIndex",e[e.SequenceShuffleIndex=17]="SequenceShuffleIndex",e[e.StartThread=18]="StartThread",e[e.Done=19]="Done",e[e.End=20]="End",e[e.ListFromInt=21]="ListFromInt",e[e.ListRange=22]="ListRange",e[e.ListRandom=23]="ListRandom",e[e.BeginTag=24]="BeginTag",e[e.EndTag=25]="EndTag",e[e.TOTAL_VALUES=26]="TOTAL_VALUES";})(o.CommandType||(o.CommandType={}));})(Fe||(ke.ControlCommand=Fe={}));});var ot=d(In=>{Object.defineProperty(In,"__esModule",{value:true});In.Expression=void 0;var yo=F(),zr=G(),Au=N(),Xr=class extends Au.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let t=new yo.Container;return t.AddContent(zr.ControlCommand.EvalStart()),this.GenerateIntoContainer(t),this.outputWhenComplete&&t.AddContent(zr.ControlCommand.EvalOutput()),t.AddContent(zr.ControlCommand.EvalEnd()),t},this.GenerateConstantIntoContainer=t=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new yo.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let e of this._prototypeRuntimeConstantExpression.content){let n=e.Copy();n&&t.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(t){return false}};In.Expression=Xr;});var $t=d(An=>{Object.defineProperty(An,"__esModule",{value:true});An.Void=void 0;var Fu=Q(),Yr=class extends Fu.InkObject{toString(){return "Void"}};An.Void=Yr;});var St=d(kn=>{Object.defineProperty(kn,"__esModule",{value:true});kn.NativeFunctionCall=void 0;var m=I(),Re=Te(),ku=$t(),Fn=et(),Ru=Q(),lt=P(),nt=B(),_=class o extends Ru.InkObject{static CallWithName(t){return new o(t)}static CallExistsWithName(t){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(t)}get name(){return this._name===null?(0, nt.throwNullException)("NativeFunctionCall._name"):this._name}set name(t){this._name=t,this._isPrototype||(o._nativeFunctions===null?(0, nt.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=o._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(t){this._numberOfParameters=t;}Call(t){if(this._prototype)return this._prototype.Call(t);if(this.numberOfParameters!=t.length)throw new Error("Unexpected number of parameters");let e=false;for(let a of t){if(a instanceof ku.Void)throw new Re.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 m.ListValue&&(e=true);}if(t.length==2&&e)return this.CallBinaryListOperation(t);let n=this.CoerceValuesToSingleType(t),i=n[0].valueType;return i==m.ValueType.Int?this.CallType(n):i==m.ValueType.Float?this.CallType(n):i==m.ValueType.String?this.CallType(n):i==m.ValueType.DivertTarget?this.CallType(n):i==m.ValueType.List?this.CallType(n):null}CallType(t){let e=(0, lt.asOrThrows)(t[0],m.Value),n=e.valueType,i=e,a=t.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, nt.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(n);if(!r){let s=m.ValueType[n];throw new Re.StoryException("Cannot perform operation "+this.name+" on "+s)}if(a==2){let l=(0, lt.asOrThrows)(t[1],m.Value),u=r;if(i.value===null||l.value===null)return (0, nt.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(i.value,l.value);return m.Value.Create(h)}else {let s=r;if(i.value===null)return (0, nt.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=s(i.value);return this.name===o.Int?m.Value.Create(l,m.ValueType.Int):this.name===o.Float?m.Value.Create(l,m.ValueType.Float):m.Value.Create(l,e.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+t.length)}CallBinaryListOperation(t){if((this.name=="+"||this.name=="-")&&t[0]instanceof m.ListValue&&t[1]instanceof m.IntValue)return this.CallListIncrementOperation(t);let e=(0, lt.asOrThrows)(t[0],m.Value),n=(0, lt.asOrThrows)(t[1],m.Value);if((this.name=="&&"||this.name=="||")&&(e.valueType!=m.ValueType.List||n.valueType!=m.ValueType.List)){if(this._operationFuncs===null)return (0, nt.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(m.ValueType.Int);if(i===null)return (0, nt.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, lt.asBooleanOrThrows)(i(e.isTruthy?1:0,n.isTruthy?1:0));return new m.BoolValue(a)}if(e.valueType==m.ValueType.List&&n.valueType==m.ValueType.List)return this.CallType([e,n]);throw new Re.StoryException("Can not call use "+this.name+" operation on "+m.ValueType[e.valueType]+" and "+m.ValueType[n.valueType])}CallListIncrementOperation(t){let e=(0, lt.asOrThrows)(t[0],m.ListValue),n=(0, lt.asOrThrows)(t[1],m.IntValue),i=new Fn.InkList;if(e.value===null)return (0, nt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,r]of e.value){let s=Fn.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, nt.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(m.ValueType.Int);if(n.value===null)return (0, nt.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(r,n.value),h=null;if(e.value.origins===null)return (0, nt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of e.value.origins)if(c.name==s.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(u,Fn.InkListItem.Null);c.exists&&i.Add(c.result,u);}}return new m.ListValue(i)}CoerceValuesToSingleType(t){let e=m.ValueType.Int,n=null;for(let a of t){let r=(0, lt.asOrThrows)(a,m.Value);r.valueType>e&&(e=r.valueType),r.valueType==m.ValueType.List&&(n=(0, lt.asOrNull)(r,m.ListValue));}let i=[];if(m.ValueType[e]==m.ValueType[m.ValueType.List])for(let a of t){let r=(0, lt.asOrThrows)(a,m.Value);if(r.valueType==m.ValueType.List)i.push(r);else if(r.valueType==m.ValueType.Int){let s=parseInt(r.valueObject);if(n=(0, lt.asOrThrows)(n,m.ListValue),n.value===null)return (0, nt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, nt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(s,Fn.InkListItem.Null);if(u.exists){let h=new m.ListValue(u.result,s);i.push(h);}else throw new Re.StoryException("Could not find List item with the value "+s+" in "+l.name)}else {let s=m.ValueType[r.valueType];throw new Re.StoryException("Cannot mix Lists and "+s+" values in this operation")}}else for(let a of t){let s=(0, lt.asOrThrows)(a,m.Value).Cast(e);i.push(s);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)o.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let t=arguments[0];o.GenerateNativeFunctionsIfNecessary(),this.name=t;}else if(arguments.length===2){let t=arguments[0],e=arguments[1];this._isPrototype=true,this.name=t,this.numberOfParameters=e;}}static Identity(t){return t}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,i)=>n+i),this.AddIntBinaryOp(this.Subtract,(n,i)=>n-i),this.AddIntBinaryOp(this.Multiply,(n,i)=>n*i),this.AddIntBinaryOp(this.Divide,(n,i)=>Math.floor(n/i)),this.AddIntBinaryOp(this.Mod,(n,i)=>n%i),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,i)=>n==i),this.AddIntBinaryOp(this.Greater,(n,i)=>n>i),this.AddIntBinaryOp(this.Less,(n,i)=>n<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddIntBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddIntBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddIntBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddIntBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddIntBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddIntUnaryOp(this.Floor,o.Identity),this.AddIntUnaryOp(this.Ceiling,o.Identity),this.AddIntUnaryOp(this.Int,o.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,i)=>n+i),this.AddFloatBinaryOp(this.Subtract,(n,i)=>n-i),this.AddFloatBinaryOp(this.Multiply,(n,i)=>n*i),this.AddFloatBinaryOp(this.Divide,(n,i)=>n/i),this.AddFloatBinaryOp(this.Mod,(n,i)=>n%i),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,i)=>n==i),this.AddFloatBinaryOp(this.Greater,(n,i)=>n>i),this.AddFloatBinaryOp(this.Less,(n,i)=>n<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddFloatBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddFloatBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddFloatBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddFloatBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),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,o.Identity),this.AddStringBinaryOp(this.Add,(n,i)=>n+i),this.AddStringBinaryOp(this.Equal,(n,i)=>n===i),this.AddStringBinaryOp(this.NotEquals,(n,i)=>n!==i),this.AddStringBinaryOp(this.Has,(n,i)=>n.includes(i)),this.AddStringBinaryOp(this.Hasnt,(n,i)=>!n.includes(i)),this.AddListBinaryOp(this.Add,(n,i)=>n.Union(i)),this.AddListBinaryOp(this.Subtract,(n,i)=>n.Without(i)),this.AddListBinaryOp(this.Has,(n,i)=>n.Contains(i)),this.AddListBinaryOp(this.Hasnt,(n,i)=>!n.Contains(i)),this.AddListBinaryOp(this.Intersect,(n,i)=>n.Intersect(i)),this.AddListBinaryOp(this.Equal,(n,i)=>n.Equals(i)),this.AddListBinaryOp(this.Greater,(n,i)=>n.GreaterThan(i)),this.AddListBinaryOp(this.Less,(n,i)=>n.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,i)=>n.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(n,i)=>n.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(n,i)=>!n.Equals(i)),this.AddListBinaryOp(this.And,(n,i)=>n.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(n,i)=>n.Count>0||i.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 t=(n,i)=>n.Equals(i),e=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,m.ValueType.DivertTarget,t),this.AddOpToNativeFunc(this.NotEquals,2,m.ValueType.DivertTarget,e);}}AddOpFuncForType(t,e){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(t,e);}static AddOpToNativeFunc(t,e,n,i){if(this._nativeFunctions===null)return (0, nt.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(t);a||(a=new o(t,e),this._nativeFunctions.set(t,a)),a.AddOpFuncForType(n,i);}static AddIntBinaryOp(t,e){this.AddOpToNativeFunc(t,2,m.ValueType.Int,e);}static AddIntUnaryOp(t,e){this.AddOpToNativeFunc(t,1,m.ValueType.Int,e);}static AddFloatBinaryOp(t,e){this.AddOpToNativeFunc(t,2,m.ValueType.Float,e);}static AddFloatUnaryOp(t,e){this.AddOpToNativeFunc(t,1,m.ValueType.Float,e);}static AddStringBinaryOp(t,e){this.AddOpToNativeFunc(t,2,m.ValueType.String,e);}static AddListBinaryOp(t,e){this.AddOpToNativeFunc(t,2,m.ValueType.List,e);}static AddListUnaryOp(t,e){this.AddOpToNativeFunc(t,1,m.ValueType.List,e);}toString(){return 'Native "'+this.name+'"'}};kn.NativeFunctionCall=_;_.Add="+";_.Subtract="-";_.Divide="/";_.Multiply="*";_.Mod="%";_.Negate="_";_.Equal="==";_.Greater=">";_.Less="<";_.GreaterThanOrEquals=">=";_.LessThanOrEquals="<=";_.NotEquals="!=";_.Not="!";_.And="&&";_.Or="||";_.Min="MIN";_.Max="MAX";_.Pow="POW";_.Floor="FLOOR";_.Ceiling="CEILING";_.Int="INT";_.Float="FLOAT";_.Has="?";_.Hasnt="!?";_.Intersect="^";_.ListMin="LIST_MIN";_.ListMax="LIST_MAX";_.All="LIST_ALL";_.Count="LIST_COUNT";_.ValueOfList="LIST_VALUE";_.Invert="LIST_INVERT";_._nativeFunctions=null;});var Vn=d(Rn=>{Object.defineProperty(Rn,"__esModule",{value:true});Rn.NumberExpression=void 0;var Vu=ot(),Zr=I(),Wu=P(),Qr=class o extends Vu.Expression{constructor(t,e){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 Zr.IntValue(this.value)):this.isFloat()?n.AddContent(new Zr.FloatValue(this.value)):this.isBool()&&n.AddContent(new Zr.BoolValue(this.value));},this.toString=()=>String(this.value),typeof t=="number"&&!Number.isNaN(t)||typeof t=="boolean")this.value=t,this.subtype=e;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(t){let e=(0, Wu.asOrNull)(t,o);return e?e.subtype==this.subtype&&e.value==this.value:false}};Rn.NumberExpression=Qr;});var ts=d(Wn=>{Object.defineProperty(Wn,"__esModule",{value:true});Wn.UnaryExpression=void 0;var Du=ot(),Lu=St(),le=Vn(),qu=P(),Ve=class extends Du.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(t,e){super(),this.op=e,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(Lu.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(t);}get typeName(){return "UnaryExpression"}};Wn.UnaryExpression=Ve;Ve.WithInner=(o,t)=>{let e=(0, qu.asOrNull)(o,le.NumberExpression);if(e){if(t==="-"){if(e.isInt())return new le.NumberExpression(-e.value,"int");if(e.isFloat())return new le.NumberExpression(-e.value,"float")}else if(t=="!"||t=="not"){if(e.isInt())return new le.NumberExpression(e.value==0,"bool");if(e.isFloat())return new le.NumberExpression(e.value==0,"bool");if(e.isBool())return new le.NumberExpression(!e.value,"bool")}throw new Error("Unexpected operation or number type")}return new Ve(o,t)};});var ns=d(Dn=>{Object.defineProperty(Dn,"__esModule",{value:true});Dn.BinaryExpression=void 0;var ju=ot(),Mu=St(),Bu=ts(),Gu=P(),es=class extends ju.Expression{constructor(t,e,n){super(),this.opName=n,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(Mu.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(t),this.rightExpression=this.AddContent(e),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(t){if(super.ResolveReferences(t),this.NativeNameForOp(this.opName)==="?"){let e=(0, Gu.asOrNull)(this.leftExpression,Bu.UnaryExpression);e!==null&&(e.op==="not"||e.op==="!")&&this.Error(`Using 'not' or '!' here negates '${e.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};Dn.BinaryExpression=es;});var De=d(Ln=>{Object.defineProperty(Ln,"__esModule",{value:true});Ln.CharacterSet=void 0;var We=class{constructor(t){this.set=new Set,this.Add=e=>this.set.add(e),this.AddRange=(e,n)=>{for(let i=e.charCodeAt(0);i<=n.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=e=>{if(typeof e=="string"||Array.isArray(e))for(let n of e)this.Add(n);else for(let n of e.set)this.Add(n);return this},t&&this.AddCharacters(t);}};Ln.CharacterSet=We;We.FromRange=(o,t)=>new We().AddRange(o,t);});var bo=d(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.CharacterRange=void 0;var _o=De(),Le=class{constructor(t,e,n=[]){if(this._start=t,this._end=e,this._correspondingCharSet=new _o.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),a;i<=this.end.charCodeAt(0);i+=1)a=String.fromCharCode(i),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},n instanceof _o.CharacterSet)this._excludes=n.set;else for(let i of n)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};qn.CharacterRange=Le;Le.Define=(o,t,e=[])=>new Le(o,t,e);});var Mn=d(jn=>{Object.defineProperty(jn,"__esModule",{value:true});jn.ChoicePoint=void 0;var $u=Q(),Uu=Z(),is=B(),rs=class extends $u.InkObject{constructor(t=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=t;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path);}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t;}get choiceTarget(){return this._pathOnChoice===null?(0, is.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, is.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new Uu.Path(t);}get flags(){let t=0;return this.hasCondition&&(t|=1),this.hasStartContent&&(t|=2),this.hasChoiceOnlyContent&&(t|=4),this.isInvisibleDefault&&(t|=8),this.onceOnly&&(t|=16),t}set flags(t){this.hasCondition=(t&1)>0,this.hasStartContent=(t&2)>0,this.hasChoiceOnlyContent=(t&4)>0,this.isInvisibleDefault=(t&8)>0,this.onceOnly=(t&16)>0;}toString(){if(this.pathOnChoice===null)return (0, is.throwNullException)("ChoicePoint.pathOnChoice");let e=this.pathOnChoice.toString();return "Choice: -> "+e}};jn.ChoicePoint=rs;});var Ut=d(Bn=>{Object.defineProperty(Bn,"__esModule",{value:true});Bn.PushPopType=void 0;var Eo;(function(o){o[o.Tunnel=0]="Tunnel",o[o.Function=1]="Function",o[o.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Eo||(Bn.PushPopType=Eo={}));});var qe=d(Gn=>{Object.defineProperty(Gn,"__esModule",{value:true});Gn.Pointer=void 0;var Ku=Z(),ss=class o{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 Ku.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 o(this.container,this.index)}static StartOf(t){return new o(t,0)}static get Null(){return new o(null,-1)}};Gn.Pointer=ss;});var yt=d(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.Divert=void 0;var Hu=Z(),Ju=Ut(),zu=Bt(),Xu=Q(),as=qe(),wo=F(),$n=B(),os=class o extends Xu.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let t=this.targetPointer.Resolve();t&&(this._targetPath=t.path);}return this._targetPath}set targetPath(t){this._targetPath=t,this._targetPointer=as.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let t=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, $n.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, $n.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(t===null)return (0, $n.throwNullException)("targetObj");this._targetPointer.container=t.parent instanceof wo.Container?t.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=as.Pointer.StartOf(t instanceof wo.Container?t:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(t){t==null?this.targetPath=null:this.targetPath=new Hu.Path(t);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(t){super(),this._targetPath=null,this._targetPointer=as.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof t<"u"&&(this.pushesToStack=true,this.stackPushType=t);}Equals(t){let e=t;return e instanceof o&&this.hasVariableTarget==e.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==e.variableDivertName:this.targetPath===null?(0, $n.throwNullException)("this.targetPath"):this.targetPath.Equals(e.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let t=new zu.StringBuilder,e=this.targetPath.toString();return t.Append("Divert"),this.isConditional&&t.Append("?"),this.pushesToStack&&(this.stackPushType==Ju.PushPopType.Function?t.Append(" function"):t.Append(" tunnel")),t.Append(" -> "),t.Append(this.targetPathString),t.Append(" ("),t.Append(e),t.Append(")"),t.toString()}}};Un.Divert=os;});var Tt=d(Kn=>{Object.defineProperty(Kn,"__esModule",{value:true});Kn.SymbolType=void 0;var Po;(function(o){o[o.Knot=0]="Knot",o[o.List=1]="List",o[o.ListItem=2]="ListItem",o[o.Var=3]="Var",o[o.SubFlowAndWeave=4]="SubFlowAndWeave",o[o.Arg=5]="Arg",o[o.Temp=6]="Temp";})(Po||(Kn.SymbolType=Po={}));});var Rt=d(Hn=>{Object.defineProperty(Hn,"__esModule",{value:true});Hn.VariableAssignment=void 0;var Yu=Q(),ls=class extends Yu.InkObject{constructor(t,e){super(),this.variableName=t||null,this.isNewDeclaration=!!e,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};Hn.VariableAssignment=ls;});var ue=d(zn=>{Object.defineProperty(zn,"__esModule",{value:true});zn.Choice=void 0;var Zu=Mn(),Jn=F(),Vt=G(),us=yt(),Oo=I(),Qu=N(),th=Tt(),xo=Rt(),hs=class extends Qu.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get condition(){return this._condition}set condition(t){this._condition=t,t&&this.AddContent(t);}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(t,e,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 Jn.Container,this._runtimeChoice=new Zu.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Vt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Oo.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new xo.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Vt.ControlCommand.BeginString()),this._divertToStartContentOuter=new us.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new us.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Jn.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Vt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Vt.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Vt.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(Vt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Jn.Container,this.startContent){this._returnToR2=new Oo.DivertTargetValue,this._innerContentContainer.AddContent(Vt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Vt.ControlCommand.EvalEnd());let i=new xo.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new us.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Jn.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}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=t,this.choiceOnlyContent=e,this.innerContent=n,this.indentationDepth=1,t&&this.AddContent(this.startContent),e&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(t){var e;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(t),this.identifier&&(((e=this.identifier)===null||e===void 0?void 0:e.name)||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,th.SymbolType.SubFlowAndWeave);}};zn.Choice=hs;});var To=d(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.StringParserElement=void 0;var Xn=class o{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=t=>{o._uniqueIdCounter++,this.uniqueId=o._uniqueIdCounter,this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.customFlags=t.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=t=>{this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.reportedErrorInScope=t.reportedErrorInScope,this.customFlags=t.customFlags;};}};Yn.StringParserElement=Xn;Xn._uniqueIdCounter=1e3;});var Io=d(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.StringParserState=void 0;var No=To(),cs=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(t){this.currentElement.lineIndex=t;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(t){this.currentElement.characterIndex=t;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(t){this.currentElement.characterInLineIndex=t;}get customFlags(){return this.currentElement.customFlags}set customFlags(t){this.currentElement.customFlags=t;}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 No.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let e=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(e),n.uniqueId},this.Pop=e=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=e)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=e=>{if(this.currentElement.uniqueId!=e)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 e=this._stack[this._numElements-2],n=this._stack[this._numElements-1];e.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let e of this._stack)e.reportedErrorInScope=true;};let t=200;for(let e=0;e<t;e++)this._stack[e]=new No.StringParserElement;this._numElements=1;}};Zn.StringParserState=cs;});var fs=d(Kt=>{Object.defineProperty(Kt,"__esModule",{value:true});Kt.StringParser=Kt.ParseSuccess=void 0;var ds=De(),eh=Io();Kt.ParseSuccess=Symbol("ParseSuccessStruct");var je=class o{constructor(t){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,i=null)=>{let a=this.state.Peek(n),r=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,r,a),this.state.Squash();let s=i;return s===null&&(s=o.ParseSuccess),s},this.Expect=(n,i=null,a=null)=>{let r=this.ParseObject(n);if(r===null){i===null&&(i=n.name);let s,l=this.LineRemainder();l===null||l.length===0?s="end of line":s=`'${l}'`,this.Error(`Expected ${i} but saw ${s}`),a!==null&&(r=a());}return r},this.Error=(n,i=false)=>{this.ErrorOnLine(n,this.lineIndex+1,i);},this.ErrorWithParsedObject=(n,i,a=false)=>{this.ErrorOnLine(n,i.debugMetadata?i.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(n,i,a)=>{if(!this.state.errorReportedAlreadyInScope){let r=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,i-1,a);else throw new Error(`${r} on line ${i}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
5
+ \r`)),this.SetFlag=(n,i)=>{i?this.state.customFlags|=n:this.state.customFlags&=~n;},this.GetFlag=n=>!!(this.state.customFlags&n),this.ParseObject=n=>{let i=this.BeginRule(),a=this.state.stackHeight,r=n();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return r===null?this.FailRule(i):(this.SucceedRule(i,r),r)},this.Parse=n=>{let i=this.BeginRule(),a=n();return a===null?(this.FailRule(i),null):(this.SucceedRule(i,a),a)},this.OneOf=n=>{for(let i of n){let a=this.ParseObject(i);if(a!==null)return a}return null},this.OneOrMore=n=>{let i=[],a=null;do a=this.ParseObject(n),a!==null&&i.push(a);while(a!==null);return i.length>0?i:null},this.Optional=n=>()=>{let i=this.ParseObject(n);return i===null?o.ParseSuccess:i},this.Exclude=n=>()=>this.ParseObject(n)&&o.ParseSuccess,this.OptionalExclude=n=>()=>(this.ParseObject(n),o.ParseSuccess),this.String=n=>()=>this.ParseString(n),this.TryAddResultToList=(n,i,a=true)=>{if(n!==o.ParseSuccess){if(a&&Array.isArray(n)){let r=n;if(r!==null){for(let s of r)i.push(s);return}}i.push(n);}},this.Interleave=(n,i,a=null,r=true)=>{let s=this.BeginRule(),l=[],u=this.ParseObject(n);if(u===null)return this.FailRule(s);this.TryAddResultToList(u,l,r);let h=null,c=null;do{if(a!==null&&this.Peek(a)!==null||(h=this.ParseObject(i),h===null))break;if(this.TryAddResultToList(h,l,r),c=null,h!==null){if(c=this.ParseObject(n),c===null)break;this.TryAddResultToList(c,l,r);}}while((h!==null||c!==null)&&!(h===o.ParseSuccess&&c==o.ParseSuccess)&&this.remainingLength>0);return l.length===0?this.FailRule(s):this.SucceedRule(s,l)},this.ParseString=n=>{if(n.length>this.remainingLength)return null;let i=this.BeginRule(),a=this.index,r=this.characterInLineIndex,s=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
+ `&&(s++,r=-1),a++,r++;}return this.index=a,this.characterInLineIndex=r,this.lineIndex=s,l?this.SucceedRule(i,n):this.FailRule(i)},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,i=-1)=>this.ParseCharactersFromString(n,false,i),this.ParseUntilCharactersFromCharSet=(n,i=-1)=>this.ParseCharactersFromCharSet(n,false,i),this.ParseCharactersFromString=(n,i=-1,a=-1)=>{let r=new ds.CharacterSet(n);return typeof i=="number"?this.ParseCharactersFromCharSet(r,true,i):this.ParseCharactersFromCharSet(r,i,a)},this.ParseCharactersFromCharSet=(n,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let r=this.index,s=this.index,l=this.characterInLineIndex,u=this.lineIndex,h=0;for(;s<this._chars.length&&n.set.has(this._chars[s])===i&&h<a;)this._chars[s]===`
8
+ `&&(u+=1,l=-1),s+=1,l+=1,h+=1;return this.index=s,this.characterInLineIndex=l,this.lineIndex=u,this.index>r?this._chars.slice(r,this.index).join(""):null},this.Peek=n=>{let i=this.BeginRule(),a=n();return this.CancelRule(i),a},this.ParseInt=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");let r=this.ParseCharactersFromCharSet(o.numbersCharacterSet);if(r===null)return this.index=n,this.characterInLineIndex=i,null;let s;return Number.isNaN(Number(r))?(this.Error("Failed to read integer value: "+r+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(s=Number(r),a?-s:s)},this.ParseFloat=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let r=this.ParseCharactersFromCharSet(o.numbersCharacterSet);return +`${a}.${r}`}return this.index=n,this.characterInLineIndex=i,null},this.ParseNewline=()=>{let n=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
9
+ `)===null?this.FailRule(n):this.SucceedRule(n,`
10
+ `)};let e=this.PreProcessInputString(t);this.state=new eh.StringParserState,t?this._chars=e.split(""):this._chars=[],this.inputString=e;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(t){return t}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(t){this.state.lineIndex=t;}set characterInLineIndex(t){this.state.characterInLineIndex=t;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(t){this.state.characterIndex=t;}ParseUntil(t,e=null,n=null){let i=this.BeginRule(),a=new ds.CharacterSet;e!==null&&(a.set=new Set([...a.set.values(),...e.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let r="",s=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(r+=l),s=this.Peek(t),s!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(e!==null&&e.set.has(u)){r+=u,u===`
11
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return r.length>0?this.SucceedRule(i,String(r)):this.FailRule(i)}};Kt.StringParser=je;je.ParseSuccess=Kt.ParseSuccess;je.numbersCharacterSet=new ds.CharacterSet("0123456789");});var Ao=d(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.CommentEliminator=void 0;var ps=De(),nh=fs(),ms=class extends nh.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new ps.CharacterSet(`/\r
12
+ `),this._commentBlockEndCharacter=new ps.CharacterSet("*"),this._newlineCharacters=new ps.CharacterSet(`
13
+ \r`),this.Process=()=>{let t=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return t!==null?t.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let t=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return t!==null?t.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 t=this.lineIndex,e=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),e!=null?`
14
+ `.repeat(this.lineIndex-t):null};}PreProcessInputString(t){return t}};Qn.CommentEliminator=ms;});var ei=d(ti=>{Object.defineProperty(ti,"__esModule",{value:true});ti.Conditional=void 0;var ih=F(),Fo=G(),rh=N(),gs=class extends rh.ParsedObject{constructor(t,e){super(),this.initialCondition=t,this.branches=e,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new ih.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let a=i.runtimeObject;n.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(Fo.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Fo.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(t){let e=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=e;}super.ResolveReferences(t);}};ti.Conditional=gs;});var Wt=d(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.Text=void 0;var sh=N(),ah=I(),Cs=class extends sh.ParsedObject{constructor(t){super(),this.text=t,this.GenerateRuntimeObject=()=>new ah.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};ni.Text=Cs;});var ri=d(ii=>{Object.defineProperty(ii,"__esModule",{value:true});ii.ConstantDeclaration=void 0;var oh=N(),lh=Tt(),vs=class extends oh.ParsedObject{get constantName(){var t;return (t=this.constantIdentifier)===null||t===void 0?void 0:t.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(t,e){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=t,e&&(this._expression=this.AddContent(e));}get typeName(){return "CONST"}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.constantIdentifier,lh.SymbolType.Var);}};ii.ConstantDeclaration=vs;});var he=d(si=>{Object.defineProperty(si,"__esModule",{value:true});si.FlowLevel=void 0;var ko;(function(o){o[o.Story=0]="Story",o[o.Knot=1]="Knot",o[o.Stitch=2]="Stitch",o[o.WeavePoint=3]="WeavePoint";})(ko||(si.FlowLevel=ko={}));});var Me=d(ai=>{Object.defineProperty(ai,"__esModule",{value:true});ai.Gather=void 0;var uh=F(),hh=N(),ch=Tt(),Ss=class extends hh.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(t,e){super(),this.indentationDepth=e,this.GenerateRuntimeObject=()=>{let n=new uh.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let i of this.content)n.AddContent(i.runtimeObject);return n},this.toString=()=>{var n,i;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},t&&(this.identifier=t);}get typeName(){return "Gather"}ResolveReferences(t){super.ResolveReferences(t),this.identifier&&(this.identifier.name||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,ch.SymbolType.SubFlowAndWeave);}};ai.Gather=Ss;});var Ht=d(li=>{Object.defineProperty(li,"__esModule",{value:true});li.Path=void 0;var oi=P(),Ro=_t(),ce=he(),dh=Jt(),ys=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?ce.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(t=>t.name).filter(oi.filterUndef).join(".")),this._dotSeparatedComponents}constructor(t,e){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===ce.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(n);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=n=>{let i=this.firstComponent,a=n;for(;a;){let r=a===n,s=this.GetChildFromContext(a,i,null,r);if(s)return s;a=a.parent;}return null},this.ResolveTailComponents=n=>{let i=n;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let r=this.components[a].name,s,l=(0, oi.asOrNull)(i,Ro.FlowBase);if(l!==null?s=l.flowLevel+1:s=ce.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,r,s),i===null)break}return i},this.GetChildFromContext=(n,i,a,r=false)=>{let s=a===null,l=(0, oi.asOrNull)(n,dh.Weave);if(i&&l!==null&&(s||a===ce.FlowLevel.WeavePoint))return l.WeavePointNamed(i);let u=(0, oi.asOrNull)(n,Ro.FlowBase);if(i&&u!==null){let h=r||u.flowLevel===ce.FlowLevel.Knot;return u.ContentWithNameAtLevel(i,a,h)}return null},Object.values(ce.FlowLevel).includes(t)?(this._baseTargetLevel=t,this.components=e||[]):Array.isArray(t)?(this._baseTargetLevel=null,this.components=t||[]):(this._baseTargetLevel=null,this.components=[t]);}get typeName(){return "Path"}};li.Path=ys;});var Es=d(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.ReturnType=void 0;var fh=N(),ph=F(),_s=G(),mh=$t(),bs=class extends fh.ParsedObject{constructor(t=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let e=new ph.Container;return this.returnedExpression?e.AddContent(this.returnedExpression.runtimeObject):(e.AddContent(_s.ControlCommand.EvalStart()),e.AddContent(new mh.Void),e.AddContent(_s.ControlCommand.EvalEnd())),e.AddContent(_s.ControlCommand.PopFunction()),e},t&&(this.returnedExpression=this.AddContent(t));}get typeName(){return "ReturnType"}};ui.ReturnType=bs;});var Be=d(hi=>{Object.defineProperty(hi,"__esModule",{value:true});hi.ClosestFlowBase=void 0;function gh(o){let t=o.parent;for(;t;){if(t.hasOwnProperty("iamFlowbase")&&t.iamFlowbase())return t;t=t.parent;}return null}hi.ClosestFlowBase=gh;});var di=d(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.Identifier=void 0;var ws=class o{constructor(t){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=t;}get typeName(){return "Identifier"}static Done(){return new o("DONE")}};ci.Identifier=ws;});var _t=d(fi=>{Object.defineProperty(fi,"__esModule",{value:true});fi.FlowBase=void 0;var Ch=ue(),Ps=fe(),vh=de(),bt=he(),Sh=Me(),yh=N(),_h=Ht(),bh=Es(),Eh=F(),wh=yt(),Ph=Rt(),Os=Tt(),Oh=Jt(),xh=Be(),Th=di(),Vo=P(),xs=class o extends yh.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 t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e=null,n=null,i=false,a=false){super(),this.isFunction=i,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=(r,s)=>{var l,u;let h=[],c=[];this._subFlowsByName=new Map;for(let p of r){let v=(0, Vo.asOrNull)(p,o);v?(this._firstChildFlow===null&&(this._firstChildFlow=v),c.push(p),!((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(p);}s&&h.push(new Sh.Gather(null,1),new Ps.Divert(new _h.Path(Th.Identifier.Done())));let f=[];return h.length>0&&(this._rootWeave=new Oh.Weave(h,0),f.push(this._rootWeave)),c.length>0&&f.push(...c),f},this.ResolveVariableWithName=(r,s)=>{var l;let u={},h=s===null?this:(0, xh.ClosestFlowBase)(s);if(h){if(h.args!==null){for(let c of h.args)if(((l=c.identifier)===null||l===void 0?void 0:l.name)===r)return u.found=true,u.isArgument=true,u.ownerFlow=h,u}if(h!==this.story&&h.variableDeclarations.has(r))return u.found=true,u.ownerFlow=h,u.isTemporary=true,u}return this.story.variableDeclarations.has(r)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=r=>{let s=r.variableName;if(this.variableDeclarations.has(s)){let l=this.variableDeclarations.get(s),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${s}' that was already declared${u}`,r,false);return}this.variableDeclarations.set(r.variableName,r);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,r]of this._subFlowsByName)r.hasOwnProperty("ResolveWeavePointNaming")&&r.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var r;let s=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===bt.FlowLevel.Knot||this.flowLevel===bt.FlowLevel.Stitch)&&(s=this.Find(bh.ReturnType)(),s!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,s));let l=new Eh.Container;l.name=(r=this.identifier)===null||r===void 0?void 0:r.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 o){let c=h,f=c.runtimeObject;u===0&&!c.hasParameters&&this.flowLevel===bt.FlowLevel.Knot&&(this._startingSubFlowDivert=new wh.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let p=f,v=l.namedContent.get(p.name)||null;if(v){let w=`${this.GetType()} already contains flow named '${p.name}' (at ${v.debugMetadata})`;this.Error(w,c);}l.AddToNamedContentOnly(p);}else h&&l.AddContent(h.runtimeObject);u+=1;}return this.flowLevel!==bt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&s===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=r=>{var s;if(!(this.args===null||this.args.length===0))for(let l=this.args.length-1;l>=0;--l){let u=((s=this.args[l].identifier)===null||s===void 0?void 0:s.name)||null,h=new Ph.VariableAssignment(u,true);r.AddContent(h);}},this.ContentWithNameAtLevel=(r,s=null,l=false)=>{var u;if((s===this.flowLevel||s===null)&&r===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(s===bt.FlowLevel.WeavePoint||s===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(r),c))return c;if(s===bt.FlowLevel.WeavePoint)return l?this.DeepSearchForAnyLevelContent(r):null}if(s!==null&&s<this.flowLevel)return null;let h=this._subFlowsByName.get(r)||null;return h&&(s===null||s===h.flowLevel)?h:l?this.DeepSearchForAnyLevelContent(r):null},this.DeepSearchForAnyLevelContent=r=>{let s=this.ContentWithNameAtLevel(r,bt.FlowLevel.WeavePoint,false);if(s)return s;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(r,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==bt.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 r=this._rootWeave.FindAll(Ps.Divert)();for(let l of r)!l.isFunctionCall&&!(l.parent instanceof vh.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let s=this._rootWeave.FindAll(Ch.Choice)();for(let l of s)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},this.WarningInTermination=r=>{let s="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";r.parent===this._rootWeave&&this._firstChildFlow&&(s=`${s} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let l=(0, Vo.asOrNull)(r,Ps.Divert);l&&l.isTunnel&&(s+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(s,r);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=t,this.args=n,e===null&&(e=[]),this.PreProcessTopLevelObjects(e),e=this.SplitWeaveAndSubFlowContent(e,this.GetType()=="Story"&&!a),this.AddContent(e);}PreProcessTopLevelObjects(t){}ResolveReferences(t){var e,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(t),this.args!==null){for(let i of this.args)t.CheckForNamingCollisions(this,i.identifier,Os.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((e=this.args[i].identifier)===null||e===void 0?void 0:e.name)==((n=this.args[a].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==bt.FlowLevel.Story){let i=this.flowLevel===bt.FlowLevel.Knot?Os.SymbolType.Knot:Os.SymbolType.SubFlowAndWeave;t.CheckForNamingCollisions(this,this.identifier,i);}}};fi.FlowBase=xs;});var mi=d(pi=>{Object.defineProperty(pi,"__esModule",{value:true});pi.ContentList=void 0;var Nh=F(),Ih=N(),Ah=Wt(),Fh=P(),Ts=class extends Ih.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(t,...e){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let i=(0, Fh.asOrNull)(this.content[n],Ah.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new Nh.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,t&&this.AddContent(t),e&&this.AddContent(e);}get typeName(){return "ContentList"}};pi.ContentList=Ts;});var pe=d(gi=>{Object.defineProperty(gi,"__esModule",{value:true});gi.VariableReference=void 0;var kh=Q(),Rh=Z(),Ns=class extends kh.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(t){t===null?this.pathForCount=null:this.pathForCount=new Rh.Path(t);}constructor(t=null){super(),this.pathForCount=null,this.name=t;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};gi.VariableReference=Ns;});var me=d(Ci=>{Object.defineProperty(Ci,"__esModule",{value:true});Ci.VariableReference=void 0;var Vh=mi(),Wh=ot(),Wo=_t(),Dh=Ht(),Lh=pe(),qh=Jt(),jh=di(),Do=P(),Is=class extends Wh.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(t=>t.name).filter(Do.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let t=this.path.join(".");return new jh.Identifier(t)}get runtimeVarRef(){return this._runtimeVarRef}constructor(t){super(),this.pathIdentifiers=t,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=e=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(e),this.isConstantReference=true;return}if(this._runtimeVarRef=new Lh.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",a="";this.path.length===1?i=this.path[0]:(a=this.path[0],i=this.path[1]),this.story.ResolveListItem(a,i,this)&&(this.isListItemReference=true);}e.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(t){if(super.ResolveReferences(t),this.isConstantReference||this.isListItemReference)return;let e=new Dh.Path(this.pathIdentifiers),n=e.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 i=(0, Do.asOrNull)(n,Wo.FlowBase);i&&i.isFunction&&(this.parent instanceof qh.Weave||this.parent instanceof Vh.ContentList||this.parent instanceof Wo.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${e}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}t.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};Ci.VariableReference=Is;});var Ge=d(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.FunctionCall=void 0;var Et=G(),Mh=fe(),Bh=de(),Gh=ot(),$h=et(),Uh=I(),Si=St(),Lo=Vn(),Kh=Ht(),Hh=I(),Jh=me(),vi=P(),yi=class o extends Gh.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(t,e){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=n=>{let i=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(Et.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(Et.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let r=(0, vi.asOrNull)(this.args[0],Bh.DivertTarget),s=(0, vi.asOrNull)(this.args[0],Jh.VariableReference);if(this.args.length!==1||r===null&&s===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}r?(this._divertTargetToCount=r,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):s&&(this._variableReferenceToCount=s,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(Et.ControlCommand.TurnsSince()):n.AddContent(Et.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 r=0;r<this.args.length;r+=1){let s=(0, vi.asOrNull)(this.args[r],Lo.NumberExpression);if(s&&!s.isInt()){let l=r===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[r].GenerateIntoContainer(n);}n.AddContent(Et.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let r=(0, vi.asOrNull)(this.args[0],Lo.NumberExpression);r&&!r.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(Et.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 r=0;r<this.args.length;r+=1)this.args[r].GenerateIntoContainer(n);n.AddContent(Et.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(Et.ControlCommand.ListRandom());else if(Si.NativeFunctionCall.CallExistsWithName(this.name)){let r=Si.NativeFunctionCall.CallWithName(this.name);if(r.numberOfParameters!==this.args.length){let s=`${o.name} should take ${r.numberOfParameters} parameter`;r.numberOfParameters>1&&(s+="s"),this.Error(s);}for(let s=0;s<this.args.length;s+=1)this.args[s].GenerateIntoContainer(n);n.AddContent(Si.NativeFunctionCall.CallWithName(this.name));}else if(i!==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 Hh.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(Et.ControlCommand.ListFromInt());else {let r=new $h.InkList;r.SetInitialOriginName(this.name),n.AddContent(new Uh.ListValue(r));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(Et.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new Mh.Divert(new Kh.Path(t),e),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(t){if(super.ResolveReferences(t),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let e of this.args)e.ResolveReferences(t);if(this._divertTargetToCount){let e=this._divertTargetToCount.divert,n=e.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(${e.runtimeDivert.variableDivertName})`);return}let i=e.targetContent;if(i===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${e.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let e=this._variableReferenceToCount.runtimeVarRef;if(!e)throw new Error;e.pathForCount!==null&&this.Error(`Should be '${o.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};_i.FunctionCall=yi;yi.IsBuiltIn=o=>Si.NativeFunctionCall.CallExistsWithName(o)?true:o==="CHOICE_COUNT"||o==="TURNS_SINCE"||o==="TURNS"||o==="RANDOM"||o==="SEED_RANDOM"||o==="LIST_VALUE"||o==="LIST_RANDOM"||o==="READ_COUNT";});var Fs=d(bi=>{Object.defineProperty(bi,"__esModule",{value:true});bi.MultipleConditionExpression=void 0;var zh=ot(),Xh=St(),As=class extends zh.Expression{get subExpressions(){return this.content}constructor(t){super(),this.GenerateIntoContainer=e=>{let n=true;for(let i of this.subExpressions)i.GenerateIntoContainer(e),n||e.AddContent(Xh.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(t);}get typeName(){return "MultipleConditionExpression"}};bi.MultipleConditionExpression=As;});var de=d(Ei=>{Object.defineProperty(Ei,"__esModule",{value:true});Ei.DivertTarget=void 0;var Yh=ns(),Zh=ue(),Qh=ei(),tc=Ws(),ec=I(),ks=ot(),nc=_t(),qo=Ge(),ic=Fs(),jo=me(),Rs=P(),Vs=class o extends ks.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(t){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=e=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new ec.DivertTargetValue,e.AddContent(this.runtimeDivertTargetValue);},this.Equals=e=>{let n=(0, Rs.asOrNull)(e,o);if(!n||!this.divert.target||!n.divert.target)return false;let i=this.divert.target.dotSeparatedComponents,a=n.divert.target.dotSeparatedComponents;return i===a},this.divert=this.AddContent(t);}get typeName(){return "DivertTarget"}ResolveReferences(t){if(super.ResolveReferences(t),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let e=this;for(;e&&e instanceof ks.Expression;){let i=false,a=false,r=e.parent;if(r instanceof Yh.BinaryExpression){let s=r;s.opName!=="=="&&s.opName!=="!="?i=true:(s.leftExpression instanceof o||s.leftExpression instanceof jo.VariableReference)&&(s.rightExpression instanceof o||s.rightExpression instanceof jo.VariableReference)||(i=true),a=true;}else if(r instanceof qo.FunctionCall){let s=r;!s.isTurnsSince&&!s.isReadCount&&(i=true),a=true;}else (r instanceof ks.Expression||r instanceof ic.MultipleConditionExpression||r instanceof Zh.Choice&&r.condition===e||r instanceof Qh.Conditional||r instanceof tc.ConditionalSingleBranch)&&(i=true,a=true);if(i&&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;e=r;}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 i=n.containerForCounting;if(i!==null){let r=(0, Rs.asOrNull)(this.parent,qo.FunctionCall);r&&r.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, Rs.asOrNull)(n,nc.FlowBase);if(a!=null&&a.args!==null)for(let r of a.args)r.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${r.identifier}').`);}}};Ei.DivertTarget=Vs;});var fe=d(wi=>{Object.defineProperty(wi,"__esModule",{value:true});wi.Divert=void 0;var rc=F(),$e=G(),sc=yt(),Ds=de(),Ls=_t(),ac=Ge(),oc=N(),Mo=Ht(),lc=Z(),Bo=Ut(),uc=I(),Go=me(),hc=Be(),Ue=P(),qs=class extends oc.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(t){this._runtimeDivert=t;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(t,e){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 $e.ControlCommand.End();if(this.isDone)return $e.ControlCommand.Done();this.runtimeDivert=new sc.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let n=this.args!==null&&this.args.length>0;if(n||this.isFunctionCall||this.isTunnel||this.isThread){let i=new rc.Container;if(n){this.isFunctionCall||i.AddContent($e.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let r=0;r<this.args.length;++r){let s=this.args[r],l=null;if(a&&r<a.length&&(l=a[r]),l&&l.isByReference){let u=(0, Ue.asOrNull)(s,Go.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${s}`);break}let h=new Mo.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 f=new uc.VariablePointerValue(u.name);i.AddContent(f);}else s.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent($e.ControlCommand.EvalEnd());}return this.isThread?i.AddContent($e.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Bo.PushPopType.Function:Bo.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}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 i=(0, Ue.asOrNull)((0, hc.ClosestFlowBase)(this),Ls.FlowBase);if(i){let a=i.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let r=a.ownerFlow.args.find(s=>{var l;return ((l=s.identifier)===null||l===void 0?void 0:l.name)==n});r&&!r.isDivertTarget&&this.Error(`Since '${r.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${r.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 i=(0, Ue.asOrNull)(this.targetContent,Ls.FlowBase);if(n===0&&(i===null||!i.hasParameters))return;if(i===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&n>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof Ds.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==n){let r;n===0?r="but there weren't any passed to it":n<a?r=`but only got ${n}`:r=`but got ${n}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${r}`);return}for(let r=0;r<a;++r){let s=i.args[r],l=this.args[r];if(s.isDivertTarget){let u=(0, Ue.asOrNull)(l,Go.VariableReference);if(!(l instanceof Ds.DivertTarget)&&u===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${s.identifier} but saw ${l}`,l);else if(u){let h=new Mo.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let i=this.target?this.target.firstComponent:null,a=n.externals.get(i);if(!a)throw new Error("external not found");let r=a.argumentNames.length,s=0;this.args&&(s=this.args.length),s!==r&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${r} but got ${s}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},t&&(this.target=t),e&&(this.args=e,this.AddContent(e));}get typeName(){return "Divert"}ResolveReferences(t){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(t);let e=(0, Ue.asOrNull)(this.targetContent,Ls.FlowBase);e&&(!e.isFunction&&this.isFunctionCall?super.Error(`${e.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${e.identifier} =='?`):e.isFunction&&!this.isFunctionCall&&!(this.parent instanceof Ds.DivertTarget)&&super.Error(e.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+e.identifier+"(...)'"));let n=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=ac.FunctionCall.IsBuiltIn(this.target.firstComponent),a=t.IsExternal(this.target.firstComponent),i||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 lc.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(t));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(t,e=null,n=false){if(e!==this&&e){super.Error(t,e);return}this.isFunctionCall?super.Error(`Function call ${t}`,e,n):super.Error(`Divert ${t}`,e,n);}};wi.Divert=qs;});var $o=d(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.GatherPointToResolve=void 0;var js=class{constructor(t,e){this.divert=t,this.targetRuntimeObj=e;}};Pi.GatherPointToResolve=js;});var Uo=d(Oi=>{Object.defineProperty(Oi,"__esModule",{value:true});Oi.SequenceDivertToResolve=void 0;var Ms=class{constructor(t,e){this.divert=t,this.targetContent=e;}};Oi.SequenceDivertToResolve=Ms;});var Bs=d(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.SequenceType=void 0;var Ko;(function(o){o[o.Stopping=1]="Stopping",o[o.Cycle=2]="Cycle",o[o.Shuffle=4]="Shuffle",o[o.Once=8]="Once";})(Ko||(xi.SequenceType=Ko={}));});var Us=d(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.Sequence=void 0;var Ho=F(),ft=G(),Gs=yt(),Ke=I(),Ti=St(),cc=N(),dc=Uo(),Ni=Bs(),fc=Jt(),$s=class extends cc.ParsedObject{constructor(t,e){super(),this.sequenceType=e,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new Ho.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(ft.ControlCommand.EvalStart()),n.AddContent(ft.ControlCommand.VisitIndex());let i=(this.sequenceType&Ni.SequenceType.Once)>0,a=(this.sequenceType&Ni.SequenceType.Cycle)>0,r=(this.sequenceType&Ni.SequenceType.Stopping)>0,s=(this.sequenceType&Ni.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(i&&(l+=1),r||i?(n.AddContent(new Ke.IntValue(l-1)),n.AddContent(Ti.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new Ke.IntValue(this.sequenceElements.length)),n.AddContent(Ti.NativeFunctionCall.CallWithName("%"))),s){let h=ft.ControlCommand.NoOp();if(i||r){let f=r?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(ft.ControlCommand.Duplicate()),n.AddContent(new Ke.IntValue(f)),n.AddContent(Ti.NativeFunctionCall.CallWithName("=="));let p=new Gs.Divert;p.isConditional=true,n.AddContent(p),this.AddDivertToResolve(p,h);}let c=this.sequenceElements.length;r&&(c-=1),n.AddContent(new Ke.IntValue(c)),n.AddContent(ft.ControlCommand.SequenceShuffleIndex()),(i||r)&&n.AddContent(h);}n.AddContent(ft.ControlCommand.EvalEnd());let u=ft.ControlCommand.NoOp();for(let h=0;h<l;h+=1){n.AddContent(ft.ControlCommand.EvalStart()),n.AddContent(ft.ControlCommand.Duplicate()),n.AddContent(new Ke.IntValue(h)),n.AddContent(Ti.NativeFunctionCall.CallWithName("==")),n.AddContent(ft.ControlCommand.EvalEnd());let c=new Gs.Divert;c.isConditional=true,n.AddContent(c);let f;h<this.sequenceElements.length?f=this.sequenceElements[h].runtimeObject:f=new Ho.Container,f.name=`s${h}`,f.InsertContent(ft.ControlCommand.PopEvaluatedValue(),0);let p=new Gs.Divert;f.AddContent(p),n.AddToNamedContentOnly(f),this.AddDivertToResolve(c,f),this.AddDivertToResolve(p,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new dc.SequenceDivertToResolve(n,i));},this.sequenceType=e,this.sequenceElements=[];for(let n of t){let i=n.content,a=null;i===null||i.length===0?a=n:a=new fc.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(t){super.ResolveReferences(t);for(let e of this._sequenceDivertsToResolve)e.divert.targetPath=e.targetContent.path;}};Ii.Sequence=$s;});var Hs=d(Ai=>{Object.defineProperty(Ai,"__esModule",{value:true});Ai.TunnelOnwards=void 0;var pc=F(),He=G(),mc=yt(),gc=I(),Cc=N(),vc=$t(),Sc=P(),yc=pe(),Ks=class extends Cc.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let t=new pc.Container;if(t.AddContent(He.ControlCommand.EvalStart()),this.divertAfter){let e=this.divertAfter.GenerateRuntimeObject(),n=e;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let r=-1,s=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(r==-1&&u.commandType===He.ControlCommand.CommandType.EvalStart?r=l:u.commandType===He.ControlCommand.CommandType.EvalEnd&&(s=l));}for(let l=r+1;l<s;l+=1){let u=n.content[l];u.parent=null,t.AddContent(n.content[l]);}}}let i=(0, Sc.asOrNull)(e,mc.Divert);if(i!=null&&i.hasVariableTarget){let a=new yc.VariableReference(i.variableDivertName);t.AddContent(a);}else this._overrideDivertTarget=new gc.DivertTargetValue,t.AddContent(this._overrideDivertTarget);}else t.AddContent(new vc.Void);return t.AddContent(He.ControlCommand.EvalEnd()),t.AddContent(He.ControlCommand.PopTunnel()),t},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(t){this._divertAfter=t,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(t){super.ResolveReferences(t),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};Ai.TunnelOnwards=Ks;});var Xs=d(Fi=>{Object.defineProperty(Fi,"__esModule",{value:true});Fi.ListDefinition=void 0;var Js=et(),zs=class{constructor(t,e){this._name=t||"",this._items=null,this._itemNameToValues=e||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[t,e]of this._itemNameToValues){let n=new Js.InkListItem(this.name,t);this._items.set(n.serialized(),e);}}return this._items}ValueForItem(t){if(!t.itemName)return 0;let e=this._itemNameToValues.get(t.itemName);return typeof e<"u"?e:0}ContainsItem(t){return !t.itemName||t.originName!=this.name?false:this._itemNameToValues.has(t.itemName)}ContainsItemWithName(t){return this._itemNameToValues.has(t)}TryGetItemWithValue(t,e){for(let[n,i]of this._itemNameToValues)if(i==t)return e=new Js.InkListItem(this.name,n),{result:e,exists:true};return e=Js.InkListItem.Null,{result:e,exists:false}}TryGetValueForItem(t,e){if(!t.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(t.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};Fi.ListDefinition=zs;});var Ri=d(ki=>{Object.defineProperty(ki,"__esModule",{value:true});ki.ListDefinition=void 0;var _c=et(),bc=et(),Ec=Xs(),wc=I(),Pc=N(),Oc=Tt(),Ys=class extends Pc.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var t;let e=new Map;for(let n of this.itemDefinitions)e.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):e.set(n.name,n.seriesValue);return new Ec.ListDefinition(((t=this.identifier)===null||t===void 0?void 0:t.name)||"",e)}constructor(t){super(),this.itemDefinitions=t,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,i;let a=new _c.InkList;for(let r of this.itemDefinitions)if(r.inInitialList){let s=new bc.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,r.name||null);a.Add(s,r.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new wc.ListValue(a)};let e=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(e=n.explicitValue),n.seriesValue=e,e+=1;this.AddContent(t);}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.identifier,Oc.SymbolType.List);}};ki.ListDefinition=Ys;});var Qs=d(Vi=>{Object.defineProperty(Vi,"__esModule",{value:true});Vi.VariableAssignment=void 0;var xc=F(),Tc=Be(),Nc=Ri(),Ic=N(),Jo=Tt(),Ac=Rt(),Fc=me(),kc=P(),Zs=class extends Ic.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:t,isGlobalDeclaration:e,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let r=null;if(this.isGlobalDeclaration?r=this.story:this.isNewTemporaryDeclaration&&(r=(0, Tc.ClosestFlowBase)(this)),r&&r.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let s=new xc.Container;return this.expression?s.AddContent(this.expression.runtimeObject):this.listDefinition&&s.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Ac.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),s.AddContent(this._runtimeAssignment),s},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!e,this.isNewTemporaryDeclaration=!!n,i instanceof Nc.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):t&&(this.expression=this.AddContent(t));}ResolveReferences(t){if(super.ResolveReferences(t),this.isDeclaration&&this.listDefinition===null&&t.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?Jo.SymbolType.Var:Jo.SymbolType.Temp),this.isGlobalDeclaration){let e=(0, kc.asOrNull)(this.expression,Fc.VariableReference);e&&!e.isConstantReference&&!e.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let e=t.ResolveVariableWithName(this.variableName,this);e.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=e.isGlobal);}}};Vi.VariableAssignment=Zs;});var Jt=d(Li=>{Object.defineProperty(Li,"__esModule",{value:true});Li.Weave=void 0;var zo=Sn(),ut=ue(),Wi=ei(),Rc=ri(),Vc=F(),Di=fe(),Wc=yt(),Dc=de(),Lc=_t(),wt=Me(),qc=$o(),jc=N(),ta=Us(),Mc=Wt(),Bc=Hs(),Gc=Qs(),ht=P(),ea=class o extends jc.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 t=null;for(let n=this.content.length-1;n>=0;--n){t=this.content[n];let i=(0, ht.asOrNull)(t,Mc.Text);if(!(i&&i.text===`
15
+ `)&&!this.IsGlobalDeclaration(t))break}let e=(0, ht.asOrNull)(t,o);return e&&(t=e.lastParsedSignificantObject),t}constructor(t,e=-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,i,a;let r=[...this.FindAll(wt.Gather)(s=>!(s.name===null||s.name===void 0)),...this.FindAll(ut.Choice)(s=>!(s.name===null||s.name===void 0))];this._namedWeavePoints=new Map;for(let s of r){let l=this.namedWeavePoints.get(((n=s.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof wt.Gather?"gather":"choice",h=l;this.Error(`A ${u} with the same label name '${s.name}' already exists in this context on line ${h.debugMetadata?h.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,s);}!((i=s.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((a=s.identifier)===null||a===void 0?void 0:a.name,s);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;n<this.content.length;){let i=this.content[n];if(i instanceof ut.Choice||i instanceof wt.Gather){let r=i.indentationDepth-1;if(r>this.baseIndentIndex){let s=n;for(;n<this.content.length;){let c=(0, ht.asOrNull)(this.content[n],ut.Choice)||(0, ht.asOrNull)(this.content[n],wt.Gather);if(c!==null&&c.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let l=n-s,u=this.content.slice(s,s+l);this.content.splice(s,l);let h=new o(u,r);this.InsertContent(s,h),n=s;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let i of n)if(i instanceof ut.Choice||i instanceof wt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new Vc.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof ut.Choice||n instanceof wt.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof o){let i=n;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let r of this.looseEnds){let s=r;if(s instanceof wt.Gather&&s.indentationDepth==n.indentationDepth)continue;let l=null;if(s instanceof Di.Divert)l=s.runtimeObject;else {l=new Wc.Divert;let u=s;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new qc.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof wt.Gather)this.AddRuntimeForGather(n);else if(n instanceof ut.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof wt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=n;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, ht.asOrNull)(n,ut.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,i=null,a=false;for(let r=this.parent;r!==null;r=r.parent){let s=(0, ht.asOrNull)(r,o);s&&(!a&&n===null&&(n=s),a&&i===null&&(i=s)),(r instanceof ta.Sequence||r instanceof Wi.Conditional)&&(a=true);}if(!(n===null&&i===null))for(let r=this.looseEnds.length-1;r>=0;r-=1){let s=this.looseEnds[r],l=false;if(a){if(s instanceof ut.Choice&&n!==null)n.ReceiveLooseEnd(s),l=true;else if(!(s instanceof ut.Choice)){let u=n||i;u!==null&&(u.ReceiveLooseEnd(s),l=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(s),l=true;l&&this.looseEnds.splice(r,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(n);return i||null},this.IsGlobalDeclaration=n=>{let i=(0, ht.asOrNull)(n,Gc.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, ht.asOrNull)(n,Rc.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let i=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||i.push(l);let r=(0, ht.asOrNull)(a.parent,o);if(r===null)throw new Error("Expected weave point parent to be weave?");let s=r.content.indexOf(a);for(let l=s+1;l<r.content.length;l+=1){let u=r.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof ut.Choice||u instanceof wt.Gather||u instanceof o)break;i.push(u);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof zo.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let r=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(r,a,n);}else {for(let a of this.content)if(a instanceof ut.Choice||a instanceof Di.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let i=null;for(let r=n.parent;r!==null;r=r.parent)if(r instanceof ta.Sequence||r instanceof Wi.Conditional){i=(0, ht.asOrNull)(r,Wi.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(ut.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,i,a)=>{let r=false,s=i;for(let l of n){if(l.Find(Di.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof Dc.DivertTarget))!==null&&(r=true),l.Find(Bc.TunnelOnwards)()!=null){r=true;break}s=l;}if(!r){if(s instanceof zo.AuthorWarning)return;a(s);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return true;for(let i=n.content.length-1;i>=0;--i){let a=(0, ht.asOrNull)(n.content[i],Di.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let i of this.ancestry){let a=(0, ht.asOrNull)(i,Lc.FlowBase);if(a)n.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let r of n){let s=r.ContentWithNameAtLevel(i);if(s&&s!==a){let l=`${a.GetType()} '${i}' has the same label name as a ${s.GetType()} (on ${s.debugMetadata})`;this.Error(l,a);}}},e==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(t):this.baseIndentIndex=e,this.AddContent(t),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(t){if(super.ResolveReferences(t),this.looseEnds!==null&&this.looseEnds.length>0){let e=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof ta.Sequence||n instanceof Wi.Conditional){e=true;break}e&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let e of this.gatherPointsToResolve)e.divert.targetPath=e.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};Li.Weave=ea;});var Ws=d(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.ConditionalSingleBranch=void 0;var Xo=F(),qi=G(),Yo=yt(),$c=N(),Uc=St(),Kc=I(),Hc=Wt(),Jc=Jt(),zc=P(),na=class extends $c.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(t){this._ownExpression=t,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(t){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 i of this._innerWeave.content){let a=(0, zc.asOrNull)(i,Hc.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let e=new Xo.Container,n=this.matchingEquality&&!this.isElse;if(n&&e.AddContent(qi.ControlCommand.Duplicate()),this._conditionalDivert=new Yo.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&e.AddContent(qi.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(e),this.matchingEquality&&e.AddContent(Uc.NativeFunctionCall.CallWithName("==")),i&&e.AddContent(qi.ControlCommand.EvalEnd());}return e.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new Kc.StringValue(`
16
+ `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(qi.ControlCommand.PopEvaluatedValue(),0),e.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Yo.Divert,this._contentContainer.AddContent(this.returnDivert),e},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new Xo.Container:this._innerWeave.rootContainer,t&&(this._innerWeave=new Jc.Weave(t),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(t){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(t);}};ji.ConditionalSingleBranch=na;});var Qo=d(Mi=>{Object.defineProperty(Mi,"__esModule",{value:true});Mi.CustomFlags=void 0;var Zo;(function(o){o[o.ParsingString=1]="ParsingString",o[o.TagActive=2]="TagActive";})(Zo||(Mi.CustomFlags=Zo={}));});var tl=d(Bi=>{Object.defineProperty(Bi,"__esModule",{value:true});Bi.DebugMetadata=void 0;var ia=class o{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(t){let e=new o;return e.fileName=this.fileName,e.sourceName=this.sourceName,this.startLineNumber<t.startLineNumber?(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>t.startLineNumber?(e.startLineNumber=t.startLineNumber,e.startCharacterNumber=t.startCharacterNumber):(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=Math.min(this.startCharacterNumber,t.startCharacterNumber)),this.endLineNumber>t.endLineNumber?(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<t.endLineNumber?(e.endLineNumber=t.endLineNumber,e.endCharacterNumber=t.endCharacterNumber):(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=Math.max(this.endCharacterNumber,t.endCharacterNumber)),e}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};Bi.DebugMetadata=ia;});var el=d(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.ExternalDeclaration=void 0;var Xc=N(),ra=class extends Xc.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e){super(),this.identifier=t,this.argumentNames=e,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var t;return `EXTERNAL ${(t=this.identifier)===null||t===void 0?void 0:t.name}`}};Gi.ExternalDeclaration=ra;});var nl=d($i=>{Object.defineProperty($i,"__esModule",{value:true});$i.FlowDecl=void 0;var sa=class{constructor(t,e,n){this.name=t,this.args=e,this.isFunction=n;}};$i.FlowDecl=sa;});var oa=d(Ui=>{Object.defineProperty(Ui,"__esModule",{value:true});Ui.Wrap=void 0;var Yc=N(),aa=class extends Yc.ParsedObject{constructor(t){super(),this._objToWrap=t,this.GenerateRuntimeObject=()=>this._objToWrap;}};Ui.Wrap=aa;});var il=d(Ki=>{Object.defineProperty(Ki,"__esModule",{value:true});Ki.Glue=void 0;var Zc=oa(),la=class extends Zc.Wrap{constructor(t){super(t);}get typeName(){return "Glue"}};Ki.Glue=la;});var Ji=d(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.Glue=void 0;var Qc=Q(),ua=class extends Qc.InkObject{toString(){return "Glue"}};Hi.Glue=ua;});var sl=d(zi=>{Object.defineProperty(zi,"__esModule",{value:true});zi.IncDecExpression=void 0;var td=mi(),rl=ot(),ed=_t(),nd=St(),id=I(),rd=Rt(),sd=pe(),ad=Jt(),ha=class extends rl.Expression{constructor(t,e,n){super(),this.varIdentifier=t,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,r;i.AddContent(new sd.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new id.IntValue(1)),i.AddContent(nd.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new rd.VariableAssignment(((r=this.varIdentifier)===null||r===void 0?void 0:r.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,a;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},e instanceof rl.Expression?(this.expression=e,this.AddContent(this.expression),this.isInc=!!n):this.isInc=e;}get typeName(){return "IncDecExpression"}ResolveReferences(t){var e;super.ResolveReferences(t);let n=t.ResolveVariableWithName(((e=this.varIdentifier)===null||e===void 0?void 0:e.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 ad.Weave)&&!(this.parent instanceof ed.FlowBase)&&!(this.parent instanceof td.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};zi.IncDecExpression=ha;});var da=d(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.IncludedFile=void 0;var od=N(),ca=class extends od.ParsedObject{constructor(t){super(),this.includedStory=t,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Xi.IncludedFile=ca;});var al=d(Yi=>{Object.defineProperty(Yi,"__esModule",{value:true});Yi.InfixOperator=void 0;var fa=class{constructor(t,e,n){this.type=t,this.precedence=e,this.requireWhitespace=n,this.toString=()=>this.type;}};Yi.InfixOperator=fa;});var ma=d(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.Knot=void 0;var ld=_t(),ol=he(),pa=class extends ld.FlowBase{get flowLevel(){return ol.FlowLevel.Knot}constructor(t,e,n,i){super(t,e,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(t){super.ResolveReferences(t);let e=this.story;for(let n in this.subFlowsByName){let i=e.ContentWithNameAtLevel(n,ol.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(n),r=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(r,a);}}}};Zi.Knot=pa;});var ll=d(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.List=void 0;var ud=ot(),hd=et(),cd=et(),dd=I(),ga=class extends ud.Expression{constructor(t){super(),this.itemIdentifierList=t,this.GenerateIntoContainer=e=>{var n,i;let a=new hd.InkList;if(this.itemIdentifierList!=null)for(let r of this.itemIdentifierList){let s=((n=r?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";s.length>1?(l=s[0],u=s[1]):u=s[0];let h=this.story.ResolveListItem(l,u,this);if(h===null)l===null?this.Error(`Could not find list definition that contains item '${r}'`):this.Error(`Could not find list item ${r}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${r}`);return}l||(l=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new cd.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${r}' in list.`):a.Add(c,h.seriesValue);}}e.AddContent(new dd.ListValue(a));};}get typeName(){return "List"}};Qi.List=ga;});var va=d(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.ListElementDefinition=void 0;var fd=N(),pd=Tt(),Ca=class extends fd.ParsedObject{get fullName(){var t;let e=this.parent;if(e===null)throw new Error("Can't get full name without a parent list.");return `${(t=e.identifier)===null||t===void 0?void 0:t.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var t;return ((t=this.indentifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e,n=null){super(),this.indentifier=t,this.inInitialList=e,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(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.indentifier,pd.SymbolType.ListItem);}};tr.ListElementDefinition=Ca;});var Sa=d(er=>{Object.defineProperty(er,"__esModule",{value:true});er.StatementLevel=void 0;var ul;(function(o){o[o.InnerBlock=0]="InnerBlock",o[o.Stitch=1]="Stitch",o[o.Knot=2]="Knot",o[o.Top=3]="Top";})(ul||(er.StatementLevel=ul={}));});var _a=d(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.Stitch=void 0;var md=_t(),gd=he(),ya=class extends md.FlowBase{get flowLevel(){return gd.FlowLevel.Stitch}constructor(t,e,n,i){super(t,e,n,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};nr.Stitch=ya;});var rr=d(ir=>{Object.defineProperty(ir,"__esModule",{value:true});ir.Tag=void 0;var Cd=Q(),ba=class extends Cd.InkObject{constructor(t){super(),this.text=t.toString()||"";}toString(){return "# "+this.text}};ir.Tag=ba;});var wa=d(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.Choice=void 0;var vd=Z(),Sd=B(),yd=Q(),Ea=class o extends yd.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, Sd.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new vd.Path(t);}Clone(){let t=new o;return t.text=this.text,t.sourcePath=this.sourcePath,t.index=this.index,t.targetPath=this.targetPath,t.originalThreadIndex=this.originalThreadIndex,t.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(t.threadAtGeneration=this.threadAtGeneration.Copy()),t}};sr.Choice=Ea;});var Oa=d(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.ListDefinitionsOrigin=void 0;var _d=et(),bd=I(),Ed=B(),Pa=class{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let e of t){this._lists.set(e.name,e);for(let[n,i]of e.items){let a=_d.InkListItem.fromSerializedKey(n),r=new bd.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,r),this._allUnambiguousListValueCache.set(a.fullName,r);}}}get lists(){let t=[];for(let[,e]of this._lists)t.push(e);return t}TryListGetDefinition(t,e){if(t===null)return {result:e,exists:false};let n=this._lists.get(t);return n?{result:n,exists:true}:{result:e,exists:false}}FindSingleItemListWithName(t){if(t===null)return (0, Ed.throwNullException)("name");let e=this._allUnambiguousListValueCache.get(t);return typeof e<"u"?e:null}};ar.ListDefinitionsOrigin=Pa;});var Ce=d(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.JsonSerialisation=void 0;var or=F(),it=I(),hl=Ji(),b=G(),ge=Ut(),cl=yt(),dl=Mn(),xa=pe(),fl=Rt(),Ta=St(),pl=$t(),ml=rr(),wd=Z(),gl=wa(),Pd=Xs(),Od=Oa(),lr=et(),k=P(),zt=B(),ur=class o{static JArrayToRuntimeObjList(t,e=false){let n=t.length;e&&n--;let i=[];for(let a=0;a<n;a++){let r=t[a],s=this.JTokenToRuntimeObject(r);if(s===null)return (0, zt.throwNullException)("runtimeObj");i.push(s);}return i}static WriteDictionaryRuntimeObjs(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WritePropertyStart(n),this.WriteRuntimeObject(t,i),t.WritePropertyEnd();t.WriteObjectEnd();}static WriteListRuntimeObjs(t,e){t.WriteArrayStart();for(let n of e)this.WriteRuntimeObject(t,n);t.WriteArrayEnd();}static WriteIntDictionary(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WriteIntProperty(n,i);t.WriteObjectEnd();}static WriteRuntimeObject(t,e){let n=(0, k.asOrNull)(e,or.Container);if(n){this.WriteRuntimeContainer(t,n);return}let i=(0, k.asOrNull)(e,cl.Divert);if(i){let C="->";i.isExternal?C="x()":i.pushesToStack&&(i.stackPushType==ge.PushPopType.Function?C="f()":i.stackPushType==ge.PushPopType.Tunnel&&(C="->t->"));let O;i.hasVariableTarget?O=i.variableDivertName:O=i.targetPathString,t.WriteObjectStart(),t.WriteProperty(C,O),i.hasVariableTarget&&t.WriteProperty("var",true),i.isConditional&&t.WriteProperty("c",true),i.externalArgs>0&&t.WriteIntProperty("exArgs",i.externalArgs),t.WriteObjectEnd();return}let a=(0, k.asOrNull)(e,dl.ChoicePoint);if(a){t.WriteObjectStart(),t.WriteProperty("*",a.pathStringOnChoice),t.WriteIntProperty("flg",a.flags),t.WriteObjectEnd();return}let r=(0, k.asOrNull)(e,it.BoolValue);if(r){t.WriteBool(r.value);return}let s=(0, k.asOrNull)(e,it.IntValue);if(s){t.WriteInt(s.value);return}let l=(0, k.asOrNull)(e,it.FloatValue);if(l){t.WriteFloat(l.value);return}let u=(0, k.asOrNull)(e,it.StringValue);if(u){u.isNewline?t.Write(`
17
+ `,false):(t.WriteStringStart(),t.WriteStringInner("^"),t.WriteStringInner(u.value),t.WriteStringEnd());return}let h=(0, k.asOrNull)(e,it.ListValue);if(h){this.WriteInkList(t,h);return}let c=(0, k.asOrNull)(e,it.DivertTargetValue);if(c){if(t.WriteObjectStart(),c.value===null)return (0, zt.throwNullException)("divTargetVal.value");t.WriteProperty("^->",c.value.componentsString),t.WriteObjectEnd();return}let f=(0, k.asOrNull)(e,it.VariablePointerValue);if(f){t.WriteObjectStart(),t.WriteProperty("^var",f.value),t.WriteIntProperty("ci",f.contextIndex),t.WriteObjectEnd();return}if((0, k.asOrNull)(e,hl.Glue)){t.Write("<>");return}let v=(0, k.asOrNull)(e,b.ControlCommand);if(v){t.Write(o._controlCommandNames[v.commandType]);return}let w=(0, k.asOrNull)(e,Ta.NativeFunctionCall);if(w){let C=w.name;C=="^"&&(C="L^"),t.Write(C);return}let H=(0, k.asOrNull)(e,xa.VariableReference);if(H){t.WriteObjectStart();let C=H.pathStringForCount;C!=null?t.WriteProperty("CNT?",C):t.WriteProperty("VAR?",H.name),t.WriteObjectEnd();return}let R=(0, k.asOrNull)(e,fl.VariableAssignment);if(R){t.WriteObjectStart();let C=R.isGlobal?"VAR=":"temp=";t.WriteProperty(C,R.variableName),R.isNewDeclaration||t.WriteProperty("re",true),t.WriteObjectEnd();return}if((0, k.asOrNull)(e,pl.Void)){t.Write("void");return}let st=(0, k.asOrNull)(e,ml.Tag);if(st){t.WriteObjectStart(),t.WriteProperty("#",st.text),t.WriteObjectEnd();return}let hn=(0, k.asOrNull)(e,gl.Choice);if(hn){this.WriteChoice(t,hn);return}throw new Error("Failed to convert runtime object to Json token: "+e)}static JObjectToDictionaryRuntimeObjs(t){let e=new Map;for(let n in t)if(t.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(t[n]);if(i===null)return (0, zt.throwNullException)("inkObject");e.set(n,i);}return e}static JObjectToIntDictionary(t){let e=new Map;for(let n in t)t.hasOwnProperty(n)&&e.set(n,parseInt(t[n]));return e}static JTokenToRuntimeObject(t){if(typeof t=="number"&&!isNaN(t)||typeof t=="boolean")return it.Value.Create(t);if(typeof t=="string"){let e=t.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(e);if(n)return new it.FloatValue(parseFloat(n[0]));let i=e[0];if(i=="^")return new it.StringValue(e.substring(1));if(i==`
18
+ `&&e.length==1)return new it.StringValue(`
19
+ `);if(e=="<>")return new hl.Glue;for(let a=0;a<o._controlCommandNames.length;++a){let r=o._controlCommandNames[a];if(e==r)return new b.ControlCommand(a)}if(e=="L^"&&(e="^"),Ta.NativeFunctionCall.CallExistsWithName(e))return Ta.NativeFunctionCall.CallWithName(e);if(e=="->->")return b.ControlCommand.PopTunnel();if(e=="~ret")return b.ControlCommand.PopFunction();if(e=="void")return new pl.Void}if(typeof t=="object"&&!Array.isArray(t)){let e=t,n;if(e["^->"])return n=e["^->"],new it.DivertTargetValue(new wd.Path(n.toString()));if(e["^var"]){n=e["^var"];let h=new it.VariablePointerValue(n.toString());return "ci"in e&&(n=e.ci,h.contextIndex=parseInt(n)),h}let i=false,a=false,r=ge.PushPopType.Function,s=false;if((n=e["->"])?i=true:(n=e["f()"])?(i=true,a=true,r=ge.PushPopType.Function):(n=e["->t->"])?(i=true,a=true,r=ge.PushPopType.Tunnel):(n=e["x()"])&&(i=true,s=true,a=false,r=ge.PushPopType.Function),i){let h=new cl.Divert;h.pushesToStack=a,h.stackPushType=r,h.isExternal=s;let c=n.toString();return (n=e.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!e.c,s&&(n=e.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=e["*"]){let h=new dl.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=e.flg)&&(h.flags=parseInt(n)),h}if(n=e["VAR?"])return new xa.VariableReference(n.toString());if(n=e["CNT?"]){let h=new xa.VariableReference;return h.pathStringForCount=n.toString(),h}let l=false,u=false;if((n=e["VAR="])?(l=true,u=true):(n=e["temp="])&&(l=true,u=false),l){let h=n.toString(),c=!e.re,f=new fl.VariableAssignment(h,c);return f.isGlobal=u,f}if(e["#"]!==void 0)return n=e["#"],new ml.Tag(n.toString());if(n=e.list){let h=n,c=new lr.InkList;if(n=e.origins){let f=n;c.SetInitialOriginNames(f);}for(let f in h)if(h.hasOwnProperty(f)){let p=h[f],v=new lr.InkListItem(f),w=parseInt(p);c.Add(v,w);}return new it.ListValue(c)}if(e.originalChoicePath!=null)return this.JObjectToChoice(e)}if(Array.isArray(t))return this.JArrayToContainer(t);if(t==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(t,["parent"]))}static toJson(t,e,n){return JSON.stringify(t,(i,a)=>e?.some(r=>r===i)?void 0:a,n)}static WriteRuntimeContainer(t,e,n=false){if(t.WriteArrayStart(),e===null)return (0, zt.throwNullException)("container");for(let l of e.content)this.WriteRuntimeObject(t,l);let i=e.namedOnlyContent,a=e.countFlags,r=e.name!=null&&!n,s=i!=null||a>0||r;if(s&&t.WriteObjectStart(),i!=null)for(let[l,u]of i){let h=l,c=(0, k.asOrNull)(u,or.Container);t.WritePropertyStart(h),this.WriteRuntimeContainer(t,c,true),t.WritePropertyEnd();}a>0&&t.WriteIntProperty("#f",a),r&&t.WriteProperty("#n",e.name),s?t.WriteObjectEnd():t.WriteNull(),t.WriteArrayEnd();}static JArrayToContainer(t){let e=new or.Container;e.content=this.JArrayToRuntimeObjList(t,true);let n=t[t.length-1];if(n!=null){let i=new Map;for(let a in n)if(a=="#f")e.countFlags=parseInt(n[a]);else if(a=="#n")e.name=n[a].toString();else {let r=this.JTokenToRuntimeObject(n[a]),s=(0, k.asOrNull)(r,or.Container);s&&(s.name=a),i.set(a,r);}e.namedOnlyContent=i;}return e}static JObjectToChoice(t){let e=new gl.Choice;return e.text=t.text.toString(),e.index=parseInt(t.index),e.sourcePath=t.originalChoicePath.toString(),e.originalThreadIndex=parseInt(t.originalThreadIndex),e.pathStringOnChoice=t.targetPath.toString(),e.tags=this.JArrayToTags(t),e}static JArrayToTags(t){return t.tags?t.tags:null}static WriteChoice(t,e){t.WriteObjectStart(),t.WriteProperty("text",e.text),t.WriteIntProperty("index",e.index),t.WriteProperty("originalChoicePath",e.sourcePath),t.WriteIntProperty("originalThreadIndex",e.originalThreadIndex),t.WriteProperty("targetPath",e.pathStringOnChoice),this.WriteChoiceTags(t,e),t.WriteObjectEnd();}static WriteChoiceTags(t,e){if(e.tags&&e.tags.length>0){t.WritePropertyStart("tags"),t.WriteArrayStart();for(let n of e.tags)t.Write(n);t.WriteArrayEnd(),t.WritePropertyEnd();}}static WriteInkList(t,e){let n=e.value;if(n===null)return (0, zt.throwNullException)("rawList");t.WriteObjectStart(),t.WritePropertyStart("list"),t.WriteObjectStart();for(let[i,a]of n){let r=lr.InkListItem.fromSerializedKey(i),s=a;if(r.itemName===null)return (0, zt.throwNullException)("item.itemName");t.WritePropertyNameStart(),t.WritePropertyNameInner(r.originName?r.originName:"?"),t.WritePropertyNameInner("."),t.WritePropertyNameInner(r.itemName),t.WritePropertyNameEnd(),t.Write(s),t.WritePropertyEnd();}if(t.WriteObjectEnd(),t.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){t.WritePropertyStart("origins"),t.WriteArrayStart();for(let i of n.originNames)t.Write(i);t.WriteArrayEnd(),t.WritePropertyEnd();}t.WriteObjectEnd();}static ListDefinitionsToJToken(t){let e={};for(let n of t.lists){let i={};for(let[a,r]of n.items){let s=lr.InkListItem.fromSerializedKey(a);if(s.itemName===null)return (0, zt.throwNullException)("item.itemName");i[s.itemName]=r;}e[n.name]=i;}return e}static JTokenToListDefinitions(t){let e=t,n=[];for(let i in e)if(e.hasOwnProperty(i)){let a=i.toString(),r=e[i],s=new Map;for(let u in r)if(e.hasOwnProperty(i)){let h=r[u];s.set(u,parseInt(h));}let l=new Pd.ListDefinition(a,s);n.push(l);}return new Od.ListDefinitionsOrigin(n)}};hr.JsonSerialisation=ur;ur._controlCommandNames=(()=>{let o=[];o[b.ControlCommand.CommandType.EvalStart]="ev",o[b.ControlCommand.CommandType.EvalOutput]="out",o[b.ControlCommand.CommandType.EvalEnd]="/ev",o[b.ControlCommand.CommandType.Duplicate]="du",o[b.ControlCommand.CommandType.PopEvaluatedValue]="pop",o[b.ControlCommand.CommandType.PopFunction]="~ret",o[b.ControlCommand.CommandType.PopTunnel]="->->",o[b.ControlCommand.CommandType.BeginString]="str",o[b.ControlCommand.CommandType.EndString]="/str",o[b.ControlCommand.CommandType.NoOp]="nop",o[b.ControlCommand.CommandType.ChoiceCount]="choiceCnt",o[b.ControlCommand.CommandType.Turns]="turn",o[b.ControlCommand.CommandType.TurnsSince]="turns",o[b.ControlCommand.CommandType.ReadCount]="readc",o[b.ControlCommand.CommandType.Random]="rnd",o[b.ControlCommand.CommandType.SeedRandom]="srnd",o[b.ControlCommand.CommandType.VisitIndex]="visit",o[b.ControlCommand.CommandType.SequenceShuffleIndex]="seq",o[b.ControlCommand.CommandType.StartThread]="thread",o[b.ControlCommand.CommandType.Done]="done",o[b.ControlCommand.CommandType.End]="end",o[b.ControlCommand.CommandType.ListFromInt]="listInt",o[b.ControlCommand.CommandType.ListRange]="range",o[b.ControlCommand.CommandType.ListRandom]="lrnd",o[b.ControlCommand.CommandType.BeginTag]="#",o[b.ControlCommand.CommandType.EndTag]="/#";for(let t=0;t<b.ControlCommand.CommandType.TOTAL_VALUES;++t)if(o[t]==null)throw new Error("Control command not accounted for in serialisation");return o})();});var Aa=d(Xe=>{Object.defineProperty(Xe,"__esModule",{value:true});Xe.CallStack=void 0;var Na=Ut(),Cl=Z(),xd=Ye(),vl=Ce(),Td=I(),Nd=Bt(),Je=qe(),Id=Oe(),Sl=se(),Ia=B(),ze=class o{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let e=this._threads[this._threads.length-1].callstack;return e[e.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(t){Id.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(t);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=Je.Pointer.Null,arguments[0]instanceof xd.Story){let t=arguments[0];this._startOfRoot=Je.Pointer.StartOf(t.rootContentContainer),this.Reset();}else {let t=arguments[0];this._threads=[];for(let e of t._threads)this._threads.push(e.Copy());this._threadCounter=t._threadCounter,this._startOfRoot=t._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new o.Thread),this._threads[0].callstack.push(new o.Element(Na.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(t,e){this._threads.length=0;let n=t.threads;for(let i of n){let a=i,r=new o.Thread(a,e);this._threads.push(r);}this._threadCounter=parseInt(t.threadCounter),this._startOfRoot=Je.Pointer.StartOf(e.rootContentContainer);}WriteJson(t){t.WriteObject(e=>{e.WritePropertyStart("threads"),e.WriteArrayStart();for(let n of this._threads)n.WriteJson(e);e.WriteArrayEnd(),e.WritePropertyEnd(),e.WritePropertyStart("threadCounter"),e.WriteInt(this._threadCounter),e.WritePropertyEnd();});}PushThread(){let t=this.currentThread.Copy();this._threadCounter++,t.threadIndex=this._threadCounter,this._threads.push(t);}ForkThread(){let t=this.currentThread.Copy();return this._threadCounter++,t.threadIndex=this._threadCounter,t}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==Na.PushPopType.FunctionEvaluationFromGame}Push(t,e=0,n=0){let i=new o.Element(t,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=e,i.functionStartInOutputStream=n,this.callStack.push(i);}CanPop(t=null){return this.canPop?t==null?true:this.currentElement.type==t:false}Pop(t=null){if(this.CanPop(t)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(t,e=-1){e==-1&&(e=this.currentElementIndex+1);let n=this.callStack[e-1],i=(0, Sl.tryGetValueFromMap)(n.temporaryVariables,t,null);return i.exists?i.result:null}SetTemporaryVariable(t,e,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!n&&!a.temporaryVariables.get(t))throw new Error("Could not find temporary variable to set: "+t);let r=(0, Sl.tryGetValueFromMap)(a.temporaryVariables,t,null);r.exists&&Td.ListValue.RetainListOriginsForAssignment(r.result,e),a.temporaryVariables.set(t,e);}ContextForVariableNamed(t){return this.currentElement.temporaryVariables.get(t)?this.currentElementIndex+1:0}ThreadWithIndex(t){let e=this._threads.filter(n=>{if(n.threadIndex==t)return n});return e.length>0?e[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let t=new Nd.StringBuilder;for(let e=0;e<this._threads.length;e++){let n=this._threads[e],i=e==this._threads.length-1;t.AppendFormat(`=== THREAD {0}/{1} {2}===
20
+ `,e+1,this._threads.length,i?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==Na.PushPopType.Function?t.Append(" [FUNCTION] "):t.Append(" [TUNNEL] ");let r=n.callstack[a].currentPointer;if(!r.isNull){if(t.Append("<SOMEWHERE IN "),r.container===null)return (0, Ia.throwNullException)("pointer.container");t.Append(r.container.path.toString()),t.AppendLine(">");}}}return t.toString()}};Xe.CallStack=ze;(function(o){class t{constructor(i,a,r=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=r,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new t(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}o.Element=t;class e{constructor(){if(this.threadIndex=0,this.previousPointer=Je.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let r=i.callstack;for(let l of r){let u=l,h=parseInt(u.type),c=Je.Pointer.Null,f,p=u.cPath;if(typeof p<"u"){f=p.toString();let R=a.ContentAtPath(new Cl.Path(f));if(c.container=R.container,c.index=parseInt(u.idx),R.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+f+". Has the story changed since this save data was created?");R.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"', 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: '"+f+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let v=!!u.exp,w=new t(h,c,v),H=u.temp;typeof H<"u"?w.temporaryVariables=vl.JsonSerialisation.JObjectToDictionaryRuntimeObjs(H):w.temporaryVariables.clear(),this.callstack.push(w);}let s=i.previousContentObject;if(typeof s<"u"){let l=new Cl.Path(s.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let i=new e;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, Ia.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",a.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",a.currentPointer.index);}i.WriteProperty("exp",a.inExpressionEvaluation),i.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),vl.JsonSerialisation.WriteDictionaryRuntimeObjs(i,a.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, Ia.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}o.Thread=e;})(ze||(Xe.CallStack=ze={}));});var _l=d(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.VariablesState=void 0;var M=I(),Ad=Te(),yl=Ce(),$=P(),Ze=se(),Dt=B();function Fd(){return class{}}var cr=class o extends Fd(){variableChangedEvent(t,e){for(let n of this.variableChangedEventCallbacks)n(t,e);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let t=new Map;if(this._changedVariablesForBatchObs!=null)for(let e of this._changedVariablesForBatchObs){let n=this._globalVariables.get(e);this.variableChangedEvent(e,n);}if(this.patch!=null)for(let e of this.patch.changedVariables){let n=this.patch.TryGetGlobal(e,null);n.exists&&t.set(e,n);}return this._changedVariablesForBatchObs=null,t}NotifyObservers(t){for(let[e,n]of t)this.variableChangedEvent(e,n);}get callStack(){return this._callStack}set callStack(t){this._callStack=t;}$(t,e){if(typeof e>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(t),typeof n>"u"&&(n=this._defaultGlobalVariables.get(t)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(t)>"u")throw new Ad.StoryException("Cannot assign to a variable ("+t+") that hasn't been declared in the story");let n=M.Value.Create(e);if(n==null)throw e==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+e.toString());this.SetGlobal(t,n);}}constructor(t,e){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=t,this._listDefsOrigin=e;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,r){return a in i?i[a]=r:i.$(a,r),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,a){return {enumerable:!0,configurable:!0,value:i.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Dt.throwNullException)("this.patch");for(let[t,e]of this.patch.globals)this._globalVariables.set(t,e);if(this._changedVariablesForBatchObs!==null)for(let t of this.patch.changedVariables)this._changedVariablesForBatchObs.add(t);this.patch=null;}SetJsonToken(t){this._globalVariables.clear();for(let[e,n]of this._defaultGlobalVariables){let i=t[e];if(typeof i<"u"){let a=yl.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Dt.throwNullException)("tokenInkObject");this._globalVariables.set(e,a);}else this._globalVariables.set(e,n);}}WriteJson(t){t.WriteObjectStart();for(let[e,n]of this._globalVariables){let i=e,a=n;if(o.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let r=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,r))continue}t.WritePropertyStart(i),yl.JsonSerialisation.WriteRuntimeObject(t,a),t.WritePropertyEnd();}t.WriteObjectEnd();}RuntimeObjectsEqual(t,e){if(t===null)return (0, Dt.throwNullException)("obj1");if(e===null)return (0, Dt.throwNullException)("obj2");if(t.constructor!==e.constructor)return false;let n=(0, $.asOrNull)(t,M.BoolValue);if(n!==null)return n.value===(0, $.asOrThrows)(e,M.BoolValue).value;let i=(0, $.asOrNull)(t,M.IntValue);if(i!==null)return i.value===(0, $.asOrThrows)(e,M.IntValue).value;let a=(0, $.asOrNull)(t,M.FloatValue);if(a!==null)return a.value===(0, $.asOrThrows)(e,M.FloatValue).value;let r=(0, $.asOrNull)(t,M.Value),s=(0, $.asOrNull)(e,M.Value);if(r!==null&&s!==null)return (0, $.isEquatable)(r.valueObject)&&(0, $.isEquatable)(s.valueObject)?r.valueObject.Equals(s.valueObject):r.valueObject===s.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+t.constructor.name)}GetVariableWithName(t,e=-1){let n=this.GetRawVariableWithName(t,e),i=(0, $.asOrNull)(n,M.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(t){let e=(0, Ze.tryGetValueFromMap)(this._defaultGlobalVariables,t,null);return e.exists?e.result:null}GlobalVariableExistsWithName(t){return this._globalVariables.has(t)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(t)}GetRawVariableWithName(t,e){let n=null;if(e==0||e==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(t,null),i.exists)||(i=(0, Ze.tryGetValueFromMap)(this._globalVariables,t,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Ze.tryGetValueFromMap)(this._defaultGlobalVariables,t,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Dt.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(t);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(t,e),n}ValueAtVariablePointer(t){return this.GetVariableWithName(t.variableName,t.contextIndex)}Assign(t,e){let n=t.variableName;if(n===null)return (0, Dt.throwNullException)("name");let i=-1,a=false;if(t.isNewDeclaration?a=t.isGlobal:a=this.GlobalVariableExistsWithName(n),t.isNewDeclaration){let r=(0, $.asOrNull)(e,M.VariablePointerValue);r!==null&&(e=this.ResolveVariablePointer(r));}else {let r=null;do r=(0, $.asOrNull)(this.GetRawVariableWithName(n,i),M.VariablePointerValue),r!=null&&(n=r.variableName,i=r.contextIndex,a=i==0);while(r!=null)}a?this.SetGlobal(n,e):this._callStack.SetTemporaryVariable(n,e,t.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(t,e){let n=(0, $.asOrThrows)(t,M.ListValue),i=(0, $.asOrThrows)(e,M.ListValue);n.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(t,e){let n=null;if(this.patch===null&&(n=(0, Ze.tryGetValueFromMap)(this._globalVariables,t,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists||(n=(0, Ze.tryGetValueFromMap)(this._globalVariables,t,null))),M.ListValue.RetainListOriginsForAssignment(n.result,e),t===null)return (0, Dt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(t,e):this._globalVariables.set(t,e),this.variableChangedEvent!==null&&n!==null&&e!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Dt.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(t):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(t);}else this.variableChangedEvent(t,e);}ResolveVariablePointer(t){let e=t.contextIndex;e==-1&&(e=this.GetContextIndexOfVariableNamed(t.variableName));let n=this.GetRawVariableWithName(t.variableName,e),i=(0, $.asOrNull)(n,M.VariablePointerValue);return i??new M.VariablePointerValue(t.variableName,e)}GetContextIndexOfVariableNamed(t){return this.GlobalVariableExistsWithName(t)?0:this._callStack.currentElementIndex}ObserveVariableChange(t){this.variableChangedEventCallbacks.push(t);}};dr.VariablesState=cr;cr.dontSaveDefaultValues=true;});var ka=d(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.PRNG=void 0;var Fa=class{constructor(t){this.seed=t%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};fr.PRNG=Fa;});var bl=d(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.StatePatch=void 0;var Ra=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 t=arguments[0];this._globals=new Map(t._globals),this._changedVariables=new Set(t._changedVariables),this._visitCounts=new Map(t._visitCounts),this._turnIndices=new Map(t._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(t,e){return t!==null&&this._globals.has(t)?{result:this._globals.get(t),exists:true}:{result:e,exists:false}}SetGlobal(t,e){this._globals.set(t,e);}AddChangedVariable(t){return this._changedVariables.add(t)}TryGetVisitCount(t,e){return this._visitCounts.has(t)?{result:this._visitCounts.get(t),exists:true}:{result:e,exists:false}}SetVisitCount(t,e){this._visitCounts.set(t,e);}SetTurnIndex(t,e){this._turnIndices.set(t,e);}TryGetTurnIndex(t,e){return this._turnIndices.has(t)?{result:this._turnIndices.get(t),exists:true}:{result:e,exists:false}}};pr.StatePatch=Ra;});var Va=d(tn=>{Object.defineProperty(tn,"__esModule",{value:true});tn.SimpleJson=void 0;var Qe=class o{static TextToDictionary(t){return new o.Reader(t).ToDictionary()}static TextToArray(t){return new o.Reader(t).ToArray()}};tn.SimpleJson=Qe;(function(o){class t{constructor(i){if(JSON.parse("0",(r,s,l)=>l!=null)){let r=(s,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(i,r);}else {let r=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(r);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}o.Reader=t;class e{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===o.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===o.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===o.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new o.Writer.StateElement(o.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===o.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let r=arguments[1];r(this);}else {let r=arguments[1];this.Write(r);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===o.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new o.Writer.StateElement(o.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===o.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===o.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new o.Writer.StateElement(o.Writer.State.Property)),this._stateStack.push(new o.Writer.StateElement(o.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===o.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===o.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===o.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===o.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===o.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new o.Writer.StateElement(o.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===o.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new o.Writer.StateElement(o.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==o.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===o.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===o.Writer.State.None||this.state===o.Writer.State.Property||this.state===o.Writer.State.Array):this.Assert(this.state===o.Writer.State.Property||this.state===o.Writer.State.Array),this.state===o.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===o.Writer.State.Array||this.state===o.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:o.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 i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===o.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===o.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}o.Writer=e,(function(n){(function(r){r[r.None=0]="None",r[r.Object=1]="Object",r[r.Array=2]="Array",r[r.Property=3]="Property",r[r.PropertyName=4]="PropertyName",r[r.String=5]="String";})(n.State||(n.State={}));class a{constructor(s){this.type=o.Writer.State.None,this.childCount=0,this.type=s;}}n.StateElement=a;})(e=o.Writer||(o.Writer={}));})(Qe||(tn.SimpleJson=Qe={}));});var wl=d(gr=>{Object.defineProperty(gr,"__esModule",{value:true});gr.Flow=void 0;var El=Aa(),mr=Ce(),kd=B(),Wa=class{constructor(){let t=arguments[0],e=arguments[1];if(this.name=t,this.callStack=new El.CallStack(e),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,e),this.outputStream=mr.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=mr.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let i=n.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,e);}else this.outputStream=[],this.currentChoices=[];}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),t.WriteProperty("outputStream",n=>mr.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let e=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, kd.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(e||(e=true,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(t),t.WritePropertyEnd());}e&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let i of this.currentChoices)mr.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),t.WriteObjectEnd();}LoadFlowChoiceThreads(t,e){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let a=t[`${n.originalThreadIndex}`];n.threadAtGeneration=new El.CallStack.Thread(a,e);}}}};gr.Flow=Wa;});var xl=d(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.StoryState=void 0;var Rd=Aa(),Vd=_l(),L=I(),Lt=Ut(),Wd=rr(),Da=Ji(),Pl=Z(),X=G(),La=Bt(),qt=Ce(),Dd=ka(),Ld=$t(),ve=qe(),en=se(),V=P(),qd=Oe(),ct=B(),jd=Ye(),Md=bl(),Ol=Va(),Cr=wl(),Bd=et(),qa=class o{ToJson(t=false){let e=new Ol.SimpleJson.Writer;return this.WriteJson(e),e.toString()}toJson(t=false){return this.ToJson(t)}LoadJson(t){let e=Ol.SimpleJson.TextToDictionary(t);this.LoadJsonObj(e),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(t){let e;if(this._patch!==null){let n=this.story.ContentAtPath(new Pl.Path(t)).container;if(n===null)throw new Error("Content at path not found: "+t);if(e=this._patch.TryGetVisitCount(n,0),e.exists)return e.result}return e=(0, en.tryGetValueFromMap)(this._visitCounts,t,null),e.exists?e.result:0}VisitCountForContainer(t){if(t===null)return (0, ct.throwNullException)("container");if(!t.visitsShouldBeCounted)return this.story.Error("Read count for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(t,0);if(i.exists)return i.result}let e=t.path.toString(),n=(0, en.tryGetValueFromMap)(this._visitCounts,e,null);return n.exists?n.result:0}IncrementVisitCountForContainer(t){if(this._patch!==null){let i=this.VisitCountForContainer(t);i++,this._patch.SetVisitCount(t,i);return}let e=t.path.toString(),n=(0, en.tryGetValueFromMap)(this._visitCounts,e,null);n.exists?this._visitCounts.set(e,n.result+1):this._visitCounts.set(e,1);}RecordTurnIndexVisitToContainer(t){if(this._patch!==null){this._patch.SetTurnIndex(t,this.currentTurnIndex);return}let e=t.path.toString();this._turnIndices.set(e,this.currentTurnIndex);}TurnsSinceForContainer(t){if(t.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(t,0);if(i.exists)return this.currentTurnIndex-i.result}let e=t.path.toString(),n=(0, en.tryGetValueFromMap)(this._turnIndices,e,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(t){this._variablesState=t;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(t){this._currentTurnIndex=t;}get currentPathString(){let t=this.currentPointer;return t.isNull?null:t.path===null?(0, ct.throwNullException)("pointer.path"):t.path.toString()}get previousPathString(){let t=this.previousPointer;return t.isNull?null:t.path===null?(0, ct.throwNullException)("previousPointer.path"):t.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(t){this.callStack.currentElement.currentPointer=t.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(t){this.callStack.currentThread.previousPointer=t.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 t=new La.StringBuilder,e=false;for(let n of this.outputStream){let i=(0, V.asOrNull)(n,L.StringValue);if(!e&&i!==null)t.Append(i.value);else {let a=(0, V.asOrNull)(n,X.ControlCommand);a!==null&&(a.commandType==X.ControlCommand.CommandType.BeginTag?e=true:a.commandType==X.ControlCommand.CommandType.EndTag&&(e=false));}}this._currentText=this.CleanOutputWhitespace(t.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(t){let e=new La.StringBuilder,n=-1,i=0;for(let a=0;a<t.length;a++){let r=t.charAt(a),s=r==" "||r==" ";s&&n==-1&&(n=a),s||(r!=`
21
+ `&&n>0&&n!=i&&e.Append(" "),n=-1),r==`
22
+ `&&(i=a+1),s||e.Append(r);}return e.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let t=false,e=new La.StringBuilder;for(let n of this.outputStream){let i=(0, V.asOrNull)(n,X.ControlCommand);if(i!=null){if(i.commandType==X.ControlCommand.CommandType.BeginTag){if(t&&e.Length>0){let a=this.CleanOutputWhitespace(e.toString());this._currentTags.push(a),e.Clear();}t=true;}else if(i.commandType==X.ControlCommand.CommandType.EndTag){if(e.Length>0){let a=this.CleanOutputWhitespace(e.toString());this._currentTags.push(a),e.Clear();}t=false;}}else if(t){let a=(0, V.asOrNull)(n,L.StringValue);a!==null&&e.Append(a.value);}else {let a=(0, V.asOrNull)(n,Wd.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(e.Length>0){let n=this.CleanOutputWhitespace(e.toString());this._currentTags.push(n),e.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 t of this._namedFlows.keys())t!=this.kDefaultFlowName&&this._aliveFlowNames.push(t);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(t){this.callStack.currentElement.inExpressionEvaluation=t;}constructor(t){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=ve.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=t,this._currentFlow=new Cr.Flow(this.kDefaultFlowName,t),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new Vd.VariablesState(this.callStack,t.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let e=new Date().getTime();this.storySeed=new Dd.PRNG(e).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=ve.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(t){if(t===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)),t===this._currentFlow.name)return;let e,n=(0, en.tryGetValueFromMap)(this._namedFlows,t,null);n.exists?e=n.result:(e=new Cr.Flow(t,this.story),this._namedFlows.set(t,e),this._aliveFlowNamesDirty=true),this._currentFlow=e,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(t){if(t===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(t===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===t&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, ct.throwNullException)("this._namedFlows");this._namedFlows.delete(t),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(t){let e=new o(this.story);if(e._patch=new Md.StatePatch(this._patch),e._currentFlow.name=this._currentFlow.name,e._currentFlow.callStack=new Rd.CallStack(this._currentFlow.callStack),e._currentFlow.outputStream.push(...this._currentFlow.outputStream),e.OutputStreamDirty(),t)for(let n of this._currentFlow.currentChoices)e._currentFlow.currentChoices.push(n.Clone());else e._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){e._namedFlows=new Map;for(let[n,i]of this._namedFlows)e._namedFlows.set(n,i),e._aliveFlowNamesDirty=true;e._namedFlows.set(this._currentFlow.name,e._currentFlow);}return this.hasError&&(e._currentErrors=[],e._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(e._currentWarnings=[],e._currentWarnings.push(...this.currentWarnings||[])),e.variablesState=this.variablesState,e.variablesState.callStack=e.callStack,e.variablesState.patch=e._patch,e.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(e.divertedPointer=this.divertedPointer.copy()),e.previousPointer=this.previousPointer.copy(),e._visitCounts=this._visitCounts,e._turnIndices=this._turnIndices,e.currentTurnIndex=this.currentTurnIndex,e.storySeed=this.storySeed,e.previousRandom=this.previousRandom,e.didSafeExit=this.didSafeExit,e}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[t,e]of this._patch.visitCounts)this.ApplyCountChanges(t,e,true);for(let[t,e]of this._patch.turnIndices)this.ApplyCountChanges(t,e,false);this._patch=null;}}ApplyCountChanges(t,e,n){(n?this._visitCounts:this._turnIndices).set(t.path.toString(),e);}WriteJson(t){if(t.WriteObjectStart(),t.WritePropertyStart("flows"),t.WriteObjectStart(),this._namedFlows!==null)for(let[e,n]of this._namedFlows)t.WriteProperty(e,i=>n.WriteJson(i));else t.WriteProperty(this._currentFlow.name,e=>this._currentFlow.WriteJson(e));if(t.WriteObjectEnd(),t.WritePropertyEnd(),t.WriteProperty("currentFlowName",this._currentFlow.name),t.WriteProperty("variablesState",e=>this.variablesState.WriteJson(e)),t.WriteProperty("evalStack",e=>qt.JsonSerialisation.WriteListRuntimeObjs(e,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, ct.throwNullException)("divertedPointer");t.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}t.WriteProperty("visitCounts",e=>qt.JsonSerialisation.WriteIntDictionary(e,this._visitCounts)),t.WriteProperty("turnIndices",e=>qt.JsonSerialisation.WriteIntDictionary(e,this._turnIndices)),t.WriteIntProperty("turnIdx",this.currentTurnIndex),t.WriteIntProperty("storySeed",this.storySeed),t.WriteIntProperty("previousRandom",this.previousRandom),t.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),t.WriteIntProperty("inkFormatVersion",jd.Story.inkVersionCurrent),t.WriteObjectEnd();}LoadJsonObj(t){let e=t,n=e.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 i=e.flows;if(i!=null){let r=i;Object.keys(r).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let s=Object.entries(r);for(let[l,u]of s){let h=l,c=u,f=new Cr.Flow(h,this.story,c);if(Object.keys(r).length===1)this._currentFlow=new Cr.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, ct.throwNullException)("this._namedFlows");this._namedFlows.set(h,f);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let l=e.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(e.callstackThreads,this.story),this._currentFlow.outputStream=qt.JsonSerialisation.JArrayToRuntimeObjList(e.outputStream),this._currentFlow.currentChoices=qt.JsonSerialisation.JArrayToRuntimeObjList(e.currentChoices);let r=e.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(r,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(e.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=qt.JsonSerialisation.JArrayToRuntimeObjList(e.evalStack);let a=e.currentDivertTarget;if(a!=null){let r=new Pl.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(r);}this._visitCounts=qt.JsonSerialisation.JObjectToIntDictionary(e.visitCounts),this._turnIndices=qt.JsonSerialisation.JObjectToIntDictionary(e.turnIndices),this.currentTurnIndex=parseInt(e.turnIdx),this.storySeed=parseInt(e.storySeed),this.previousRandom=parseInt(e.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(t=null){this.outputStream.length=0,t!==null&&this.outputStream.push(...t),this.OutputStreamDirty();}PushToOutputStream(t){let e=(0, V.asOrNull)(t,L.StringValue);if(e!==null){let n=this.TrySplittingHeadTailWhitespace(e);if(n!==null){for(let i of n)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(t),this.OutputStreamDirty();}PopFromOutputStream(t){this.outputStream.splice(this.outputStream.length-t,t),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(t){let e=t.value;if(e===null)return (0, ct.throwNullException)("single.value");let n=-1,i=-1;for(let h=0;h<e.length;h++){let c=e[h];if(c==`
23
+ `)n==-1&&(n=h),i=h;else {if(c==" "||c==" ")continue;break}}let a=-1,r=-1;for(let h=e.length-1;h>=0;h--){let c=e[h];if(c==`
24
+ `)a==-1&&(a=h),r=h;else {if(c==" "||c==" ")continue;break}}if(n==-1&&a==-1)return null;let s=[],l=0,u=e.length;if(n!=-1){if(n>0){let h=new L.StringValue(e.substring(0,n));s.push(h);}s.push(new L.StringValue(`
25
+ `)),l=i+1;}if(a!=-1&&(u=r),u>l){let h=e.substring(l,u);s.push(new L.StringValue(h));}if(a!=-1&&r>i&&(s.push(new L.StringValue(`
26
+ `)),a<e.length-1)){let h=e.length-a-1,c=new L.StringValue(e.substring(a+1,a+1+h));s.push(c);}return s}PushToOutputStreamIndividual(t){let e=(0, V.asOrNull)(t,Da.Glue),n=(0, V.asOrNull)(t,L.StringValue),i=true;if(e)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let a=-1,r=this.callStack.currentElement;r.type==Lt.PushPopType.Function&&(a=r.functionStartInOutputStream);let s=-1;for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u],c=h instanceof X.ControlCommand?h:null;if((h instanceof Da.Glue?h:null)!=null){s=u;break}else if(c!=null&&c.commandType==X.ControlCommand.CommandType.BeginString){u>=a&&(a=-1);break}}let l=-1;if(s!=-1&&a!=-1?l=Math.min(a,s):s!=-1?l=s:l=a,l!=-1){if(n.isNewline)i=false;else if(n.isNonWhitespace&&(s>-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==Lt.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(t===null)return (0, ct.throwNullException)("obj");this.outputStream.push(t),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let t=-1,e=this.outputStream.length-1;for(;e>=0;){let n=this.outputStream[e],i=(0, V.asOrNull)(n,X.ControlCommand),a=(0, V.asOrNull)(n,L.StringValue);if(i!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(t=e),e--;}if(t>=0)for(e=t;e<this.outputStream.length;)(0, V.asOrNull)(this.outputStream[e],L.StringValue)?this.outputStream.splice(e,1):e++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let t=this.outputStream.length-1;t>=0;t--){let e=this.outputStream[t];if(e instanceof Da.Glue)this.outputStream.splice(t,1);else if(e instanceof X.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let t=this.outputStream.length-1;t>=0&&!(this.outputStream[t]instanceof X.ControlCommand);t--){let n=this.outputStream[t];if(n instanceof L.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let t of this.outputStream)if(t instanceof L.StringValue)return true;return false}get inStringEvaluation(){for(let t=this.outputStream.length-1;t>=0;t--){let e=(0, V.asOrNull)(this.outputStream[t],X.ControlCommand);if(e instanceof X.ControlCommand&&e.commandType==X.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(t){let e=(0, V.asOrNull)(t,L.ListValue);if(e){let n=e.value;if(n===null)return (0, ct.throwNullException)("rawList");if(n.originNames!=null){n.origins||(n.origins=[]),n.origins.length=0;for(let i of n.originNames){if(this.story.listDefinitions===null)return (0, ct.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, ct.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(t===null)return (0, ct.throwNullException)("obj");this.evaluationStack.push(t);}PopEvaluationStack(t){if(typeof t>"u"){let e=this.evaluationStack.pop();return (0, V.nullIfUndefined)(e)}else {if(t>this.evaluationStack.length)throw new Error("trying to pop too many objects");let e=this.evaluationStack.splice(this.evaluationStack.length-t,t);return (0, V.nullIfUndefined)(e)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=ve.Pointer.Null,this.previousPointer=ve.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){qd.Debug.Assert(this.callStack.currentElement.type==Lt.PushPopType.Function);let t=this.callStack.currentElement.functionStartInOutputStream;t==-1&&(t=0);for(let e=this.outputStream.length-1;e>=t;e--){let n=this.outputStream[e],i=(0, V.asOrNull)(n,L.StringValue),a=(0, V.asOrNull)(n,X.ControlCommand);if(i!=null){if(a)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(e,1),this.OutputStreamDirty();else break}}}PopCallStack(t=null){this.callStack.currentElement.type==Lt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(t);}SetChosenPath(t,e){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(t);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,e&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(t,e){this.callStack.Push(Lt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=ve.Pointer.StartOf(t),this.PassArgumentsToEvaluationStack(e);}PassArgumentsToEvaluationStack(t){if(t!==null)for(let e=0;e<t.length;e++){if(!(typeof t[e]=="number"||typeof t[e]=="string"||typeof t[e]=="boolean"||t[e]instanceof Bd.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, V.nullIfUndefined)(t[e])===null?"null":t[e].constructor.name));this.PushEvaluationStack(L.Value.Create(t[e]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Lt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=ve.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Lt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let t=this.callStack.currentElement.evaluationStackHeightWhenPushed,e=null;for(;this.evaluationStack.length>t;){let n=this.PopEvaluationStack();e===null&&(e=n);}if(this.PopCallStack(Lt.PushPopType.FunctionEvaluationFromGame),e){if(e instanceof Ld.Void)return null;let n=(0, V.asOrThrows)(e,L.Value);return n.valueType==L.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(t,e){e?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(t)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(t));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};vr.StoryState=qa;});var Tl=d(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.Stopwatch=void 0;var ja=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;}};Sr.Stopwatch=ja;});var Il=d(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.ErrorType=void 0;var Nl;(function(o){o[o.Author=0]="Author",o[o.Warning=1]="Warning",o[o.Error=2]="Error";})(Nl||(yr.ErrorType=Nl={}));});var Ye=d(Zt=>{Object.defineProperty(Zt,"__esModule",{value:true});Zt.Story=Zt.InkList=void 0;var U=F(),Ma=Q(),Ba=Ce(),Gd=xl(),S=G(),dt=Ut(),$d=Mn(),Ud=wa(),Al=yt(),g=I(),Ga=Z(),nn=$t(),_r=rr(),Kd=Rt(),Hd=pe(),Jd=St(),Xt=Te(),$a=ka(),Yt=Bt(),zd=Oa(),Xd=Tl(),jt=qe(),rn=et(),y=P(),E=B(),Fl=Va(),kl=Il(),Yd=et();Object.defineProperty(Zt,"InkList",{enumerable:true,get:function(){return Yd.InkList}});Number.isInteger||(Number.isInteger=function(t){return typeof t=="number"&&isFinite(t)&&t>-9007199254740992&&t<9007199254740992&&Math.floor(t)===t});var Se=class o extends Ma.InkObject{get currentChoices(){let t=[];if(this._state===null)return (0, E.throwNullException)("this._state");for(let e of this._state.currentChoices)e.isInvisibleDefault||(e.index=t.length,t.push(e));return t}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 t,e=null,n=null;if(arguments[0]instanceof U.Container)t=arguments[0],typeof arguments[1]<"u"&&(e=arguments[1]),this._mainContentContainer=t;else if(typeof arguments[0]=="string"){let i=arguments[0];n=Fl.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(e!=null&&(this._listDefinitions=new zd.ListDefinitionsOrigin(e)),this._externals=new Map,n!==null){let i=n,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let r=parseInt(a);if(r>o.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(r<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");r!=o.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${o.inkVersionCurrent} used to build story doesn't match current version of engine (${r}). Non-critical, but recommend synchronising.`);let s=i.root;if(s==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let l;(l=i.listDefs)&&(this._listDefinitions=Ba.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, y.asOrThrows)(Ba.JsonSerialisation.JTokenToRuntimeObject(s),U.Container),this.ResetState();}}ToJson(t){let e=false;if(t||(e=true,t=new Fl.SimpleJson.Writer),t.WriteObjectStart(),t.WriteIntProperty("inkVersion",o.inkVersionCurrent),t.WriteProperty("root",n=>Ba.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){t.WritePropertyStart("listDefs"),t.WriteObjectStart();for(let n of this._listDefinitions.lists){t.WritePropertyStart(n.name),t.WriteObjectStart();for(let[i,a]of n.items){let r=rn.InkListItem.fromSerializedKey(i),s=a;t.WriteIntProperty(r.itemName,s);}t.WriteObjectEnd(),t.WritePropertyEnd();}t.WriteObjectEnd(),t.WritePropertyEnd();}if(t.WriteObjectEnd(),e)return t.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new Gd.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, E.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, E.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let t=this.state.currentPointer.copy();this.ChoosePath(new Ga.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=t;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(t){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+t);this.state.SwitchFlow_Internal(t);}RemoveFlow(t){this.state.RemoveFlow_Internal(t);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(t){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(t);}ContinueInternal(t=0){this._profiler!=null&&this._profiler.PreContinue();let e=t>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!e&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=e,!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 Xd.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(r){if(!(r instanceof Xt.StoryException))throw r;this.AddError(r.message,void 0,r.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>t)break}while(this.canContinue);n.Stop();let a=null;if((i||!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(dt.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(dt.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 r of this.state.currentErrors)this.onError(r,kl.ErrorType.Error);if(this.state.hasWarning)for(let r of this.state.currentWarnings)this.onError(r,kl.ErrorType.Warning);this.ResetErrors();}else {let r=new Yt.StringBuilder;throw r.Append("Ink had "),this.state.hasError&&(r.Append(`${this.state.currentErrors.length}`),r.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&r.Append(" and ")),this.state.hasWarning&&(r.Append(`${this.state.currentWarnings.length}`),r.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&r.Append(" and ")),r.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),r.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new Xt.StoryException(r.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, E.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, E.throwNullException)("this.state.currentTags");let t=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(t==o.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;t==o.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(t,e,n,i){if(t===null)return (0, E.throwNullException)("prevText");if(e===null)return (0, E.throwNullException)("currText");let a=e.length>=t.length&&t.length>0&&e.charAt(t.length-1)==`
27
+ `;if(n==i&&t.length==e.length&&a)return o.OutputStateChange.NoChange;if(!a)return o.OutputStateChange.NewlineRemoved;if(i>n)return o.OutputStateChange.ExtendedBeyondNewline;for(let r=t.length;r<e.length;r++){let s=e.charAt(r);if(s!=" "&&s!=" ")return o.OutputStateChange.ExtendedBeyondNewline}return o.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let t=new Yt.StringBuilder;for(;this.canContinue;)t.Append(this.Continue());return t.toString()}ContentAtPath(t){return this.mainContentContainer.ContentAtPath(t)}KnotContainerWithName(t){let e=this.mainContentContainer.namedContent.get(t);return e instanceof U.Container?e:null}PointerAtPath(t){if(t.length==0)return jt.Pointer.Null;let e=new jt.Pointer,n=t.length,i=null;return t.lastComponent===null?(0, E.throwNullException)("path.lastComponent"):(t.lastComponent.isIndex?(n=t.length-1,i=this.mainContentContainer.ContentAtPath(t,void 0,n),e.container=i.container,e.index=t.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(t),e.container=i.container,e.index=-1),i.obj==null||i.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+t+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+t+"', so it was approximated to: '"+i.obj.path+"'."),e)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, E.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 t=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,t}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let t=true,e=this.state.currentPointer.copy();if(e.isNull)return;let n=(0, y.asOrNull)(e.Resolve(),U.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)e=jt.Pointer.StartOf(n),n=(0, y.asOrNull)(e.Resolve(),U.Container);this.state.currentPointer=e.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=e.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(t=false);let r=(0, y.asOrNull)(i,$d.ChoicePoint);if(r){let l=this.ProcessChoice(r);l&&this.state.generatedChoices.push(l),i=null,t=false;}if(i instanceof U.Container&&(t=false),t){let l=(0, y.asOrNull)(i,g.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);i=new g.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let s=(0, y.asOrNull)(i,S.ControlCommand);s&&s.commandType==S.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(t,e){(!t.countingAtStartOnly||e)&&(t.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(t),t.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(t));}VisitChangedContainersDueToDivert(){let t=this.state.previousPointer.copy(),e=this.state.currentPointer.copy();if(e.isNull||e.index==-1)return;if(this._prevContainers.length=0,!t.isNull){let r=t.Resolve(),s=(0, y.asOrNull)(r,U.Container)||(0, y.asOrNull)(t.container,U.Container);for(;s;)this._prevContainers.push(s),s=(0, y.asOrNull)(s.parent,U.Container);}let n=e.Resolve();if(n==null)return;let i=(0, y.asOrNull)(n.parent,U.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let r=i.content.length>0&&n==i.content[0]&&a;r||(a=false),this.VisitContainer(i,r),n=i,i=(0, y.asOrNull)(i.parent,U.Container);}}PopChoiceStringAndTags(t){let e=(0, y.asOrThrows)(this.state.PopEvaluationStack(),g.StringValue);for(;this.state.evaluationStack.length>0&&(0, y.asOrNull)(this.state.PeekEvaluationStack(),_r.Tag)!=null;){let n=(0, y.asOrNull)(this.state.PopEvaluationStack(),_r.Tag);n&&t.push(n.text);}return e.value}ProcessChoice(t){let e=true;if(t.hasCondition){let s=this.state.PopEvaluationStack();this.IsTruthy(s)||(e=false);}let n="",i="",a=[];if(t.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),t.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),t.onceOnly&&this.state.VisitCountForContainer(t.choiceTarget)>0&&(e=false),!e)return null;let r=new Ud.Choice;return r.targetPath=t.pathOnChoice,r.sourcePath=t.path.toString(),r.isInvisibleDefault=t.isInvisibleDefault,r.threadAtGeneration=this.state.callStack.ForkThread(),r.tags=a.reverse(),r.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),r}IsTruthy(t){let e=false;if(t instanceof g.Value){let n=t;if(n instanceof g.DivertTargetValue){let i=n;return this.Error("Shouldn't use a divert target (to "+i.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 e}PerformLogicAndFlowControl(t){if(t==null)return false;if(t instanceof Al.Divert){let e=t;if(e.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(e.hasVariableTarget){let n=e.variableDivertName,i=this.state.variablesState.GetVariableWithName(n);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(i instanceof g.DivertTargetValue)){let r=(0, y.asOrNull)(i,g.IntValue),s="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";r instanceof g.IntValue&&r.value==0?s+="was empty/null (the value 0).":s+="contained '"+i+"'.",this.Error(s);}let a=(0, y.asOrThrows)(i,g.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(e.isExternal)return this.CallExternalFunction(e.targetPathString,e.externalArgs),true;this.state.divertedPointer=e.targetPointer.copy();}return e.pushesToStack&&this.state.callStack.Push(e.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!e.isExternal&&(e&&e.debugMetadata&&e.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+e.debugMetadata.sourceName):this.Error("Divert resolution failed: "+e)),true}else if(t instanceof S.ControlCommand){let e=t;switch(e.commandType){case S.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case S.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case S.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let C=this.state.PopEvaluationStack();if(!(C instanceof nn.Void)){let O=new g.StringValue(C.toString());this.state.PushToOutputStream(O);}}break;case S.ControlCommand.CommandType.NoOp:break;case S.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case S.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case S.ControlCommand.CommandType.PopFunction:case S.ControlCommand.CommandType.PopTunnel:let n=e.commandType==S.ControlCommand.CommandType.PopFunction?dt.PushPopType.Function:dt.PushPopType.Tunnel,i=null;if(n==dt.PushPopType.Tunnel){let C=this.state.PopEvaluationStack();i=(0, y.asOrNull)(C,g.DivertTargetValue),i===null&&this.Assert(C instanceof nn.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 C=new Map;C.set(dt.PushPopType.Function,"function return statement (~ return)"),C.set(dt.PushPopType.Tunnel,"tunnel onwards statement (->->)");let O=C.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(O="end of flow (-> END or choice)");let W="Found "+C.get(n)+", when expected "+O;this.Error(W);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case S.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(e),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case S.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(e);break;case S.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let C=[],O=0;for(let J=this.state.outputStream.length-1;J>=0;--J){let z=this.state.outputStream[J];O++;let Ot=(0, y.asOrNull)(z,S.ControlCommand);if(Ot!=null){if(Ot.commandType==S.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}z instanceof g.StringValue&&C.push(z);}this.state.PopFromOutputStream(O);let W=new Yt.StringBuilder;for(let J of C.reverse())W.Append(J.toString());let At=new _r.Tag(this.state.CleanOutputWhitespace(W.toString()));this.state.PushEvaluationStack(At);}else this.state.PushToOutputStream(e);break}case S.ControlCommand.CommandType.EndString:{let C=[],O=[],W=0;for(let J=this.state.outputStream.length-1;J>=0;--J){let z=this.state.outputStream[J];W++;let Ot=(0, y.asOrNull)(z,S.ControlCommand);if(Ot&&Ot.commandType==S.ControlCommand.CommandType.BeginString)break;z instanceof _r.Tag&&O.push(z),z instanceof g.StringValue&&C.push(z);}this.state.PopFromOutputStream(W);for(let J of O)this.state.PushToOutputStream(J);C=C.reverse();let At=new Yt.StringBuilder;for(let J of C)At.Append(J.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new g.StringValue(At.toString()));break}case S.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new g.IntValue(a));break;case S.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new g.IntValue(this.state.currentTurnIndex+1));break;case S.ControlCommand.CommandType.TurnsSince:case S.ControlCommand.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof g.DivertTargetValue)){let C="";r instanceof g.IntValue&&(C=". 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 "+r+C);break}let s=(0, y.asOrThrows)(r,g.DivertTargetValue),l=(0, y.asOrNull)(this.ContentAtPath(s.targetPath).correctObj,U.Container),u;l!=null?e.commandType==S.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(e.commandType==S.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+e.toString()+" lookup at "+s.targetPath.toString())),this.state.PushEvaluationStack(new g.IntValue(u));break;case S.ControlCommand.CommandType.Random:{let C=(0, y.asOrNull)(this.state.PopEvaluationStack(),g.IntValue),O=(0, y.asOrNull)(this.state.PopEvaluationStack(),g.IntValue);if(O==null||!(O instanceof g.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(C==null||!(C instanceof g.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(C.value===null)return (0, E.throwNullException)("maxInt.value");if(O.value===null)return (0, E.throwNullException)("minInt.value");let W=C.value-O.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 "+O.value+" and maximum as "+C.value+". The maximum must be larger");let At=this.state.storySeed+this.state.previousRandom,z=new $a.PRNG(At).next(),Ot=z%W+O.value;this.state.PushEvaluationStack(new g.IntValue(Ot)),this.state.previousRandom=z;break}case S.ControlCommand.CommandType.SeedRandom:let h=(0, y.asOrNull)(this.state.PopEvaluationStack(),g.IntValue);if(h==null||!(h instanceof g.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, E.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new nn.Void);break;case S.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new g.IntValue(c));break;case S.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new g.IntValue(f));break;case S.ControlCommand.CommandType.StartThread:break;case S.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=jt.Pointer.Null);break;case S.ControlCommand.CommandType.End:this.state.ForceEnd();break;case S.ControlCommand.CommandType.ListFromInt:let p=(0, y.asOrNull)(this.state.PopEvaluationStack(),g.IntValue),v=(0, y.asOrThrows)(this.state.PopEvaluationStack(),g.StringValue);if(p===null)throw new Xt.StoryException("Passed non-integer when creating a list element from a numerical value.");let w=null;if(this.listDefinitions===null)return (0, E.throwNullException)("this.listDefinitions");let H=this.listDefinitions.TryListGetDefinition(v.value,null);if(H.exists){if(p.value===null)return (0, E.throwNullException)("minInt.value");let C=H.result.TryGetItemWithValue(p.value,rn.InkListItem.Null);C.exists&&(w=new g.ListValue(C.result,p.value));}else throw new Xt.StoryException("Failed to find LIST called "+v.value);w==null&&(w=new g.ListValue),this.state.PushEvaluationStack(w);break;case S.ControlCommand.CommandType.ListRange:let R=(0, y.asOrNull)(this.state.PopEvaluationStack(),g.Value),Pt=(0, y.asOrNull)(this.state.PopEvaluationStack(),g.Value),st=(0, y.asOrNull)(this.state.PopEvaluationStack(),g.ListValue);if(st===null||Pt===null||R===null)throw new Xt.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(st.value===null)return (0, E.throwNullException)("targetList.value");let hn=st.value.ListWithSubRange(Pt.valueObject,R.valueObject);this.state.PushEvaluationStack(new g.ListValue(hn));break;case S.ControlCommand.CommandType.ListRandom:{let C=this.state.PopEvaluationStack();if(C===null)throw new Xt.StoryException("Expected list for LIST_RANDOM");let O=C.value,W=null;if(O===null)throw (0, E.throwNullException)("list");if(O.Count==0)W=new rn.InkList;else {let At=this.state.storySeed+this.state.previousRandom,z=new $a.PRNG(At).next(),Ot=z%O.Count,no=O.entries();for(let ro=0;ro<=Ot-1;ro++)no.next();let io=no.next().value,cn={Key:rn.InkListItem.fromSerializedKey(io[0]),Value:io[1]};if(cn.Key.originName===null)return (0, E.throwNullException)("randomItem.Key.originName");W=new rn.InkList(cn.Key.originName,this),W.Add(cn.Key,cn.Value),this.state.previousRandom=z;}this.state.PushEvaluationStack(new g.ListValue(W));break}default:this.Error("unhandled ControlCommand: "+e);break}return true}else if(t instanceof Kd.VariableAssignment){let e=t,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(e,n),true}else if(t instanceof Hd.VariableReference){let e=t,n=null;if(e.pathForCount!=null){let i=e.containerForCount,a=this.state.VisitCountForContainer(i);n=new g.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(e.name),n==null&&(this.Warning("Variable not found: '"+e.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 g.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(t instanceof Jd.NativeFunctionCall){let e=t,n=this.state.PopEvaluationStack(e.numberOfParameters),i=e.Call(n);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(t,e=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(t,n),e)this.ResetCallstack();else if(this.state.callStack.currentElement.type==dt.PushPopType.Function){let i="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(i="("+a.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+t+`) - this is almost certainly not not what you want! Full stack trace:
28
+ `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new Ga.Path(t));}IfAsyncWeCant(t){if(this._asyncContinueActive)throw new Error("Can't "+t+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(t,e=true){this.state.SetChosenPath(t,e),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(t){t=t;let e=this.currentChoices;this.Assert(t>=0&&t<e.length,"choice out of range");let n=e[t];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, E.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, E.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(t){try{return this.KnotContainerWithName(t)!=null}catch{return false}}EvaluateFunction(t,e=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(t,e),this.IfAsyncWeCant("evaluate a function"),t==null)throw new Error("Function is null");if(t==""||t.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(t);if(i==null)throw new Error("Function doesn't exist: '"+t+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,e);let r=new Yt.StringBuilder;for(;this.canContinue;)r.Append(this.Continue());let s=r.toString();this._state.ResetOutput(a);let l=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(t,e,s,l),n?{returned:l,output:s}:l}EvaluateExpression(t){let e=this.state.callStack.elements.length;this.state.callStack.Push(dt.PushPopType.Tunnel),this._temporaryEvaluationContainer=t,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>e&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(t,e){if(t===null)return (0, E.throwNullException)("funcName");let n=this._externals.get(t),i=null,a=typeof n<"u";if(a&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+t+` 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 = `+t+"()"),a&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(t),this.Assert(i!==null,"Trying to call EXTERNAL function '"+t+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(dt.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=jt.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+t+"' which has not been bound (and ink fallbacks disabled).");let r=[];for(let u=0;u<e;++u){let c=(0, y.asOrThrows)(this.state.PopEvaluationStack(),g.Value).valueObject;r.push(c);}r.reverse();let s=n.function(r),l=null;s!=null?(l=g.Value.Create(s),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof s)):l=new nn.Void,this.state.PushEvaluationStack(l);}BindExternalFunctionGeneral(t,e,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(t),"Function '"+t+"' has already been bound."),this._externals.set(t,{function:e,lookAheadSafe:n});}TryCoerce(t){return t}BindExternalFunction(t,e,n=false){this.Assert(e!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(t,i=>{this.Assert(i.length>=e.length,"External function expected "+e.length+" arguments");let a=[];for(let r=0,s=i.length;r<s;r++)a[r]=this.TryCoerce(i[r]);return e.apply(null,a)},n);}UnbindExternalFunction(t){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(t),"Function '"+t+"' has not been bound."),this._externals.delete(t);}ValidateExternalBindings(){let t=null,e=null,n=arguments[1]||new Set;if(arguments[0]instanceof U.Container&&(t=arguments[0]),arguments[0]instanceof Ma.InkObject&&(e=arguments[0]),t===null&&e===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=n.size>1?"s":"",i+=": '",i+=Array.from(n).join("', '"),i+="' ",i+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(i);}else if(t!=null){for(let i of t.content){let a=i;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(i,n);}for(let[,i]of t.namedContent)this.ValidateExternalBindings((0, y.asOrNull)(i,Ma.InkObject),n);}else if(e!=null){let i=(0, y.asOrNull)(e,Al.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, E.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.add(a);}}}ObserveVariable(t,e){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(t))throw new Error("Cannot observe variable '"+t+"' because it wasn't declared in the ink story.");this._variableObservers.has(t)?this._variableObservers.get(t).push(e):this._variableObservers.set(t,[e]);}ObserveVariables(t,e){for(let n=0,i=t.length;n<i;n++)this.ObserveVariable(t[n],e[n]);}RemoveVariableObserver(t,e){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(e!=null){if(this._variableObservers.has(e))if(t!=null){let n=this._variableObservers.get(e);n!=null&&(n.splice(n.indexOf(t),1),n.length===0&&this._variableObservers.delete(e));}else this._variableObservers.delete(e);}else if(t!=null){let n=this._variableObservers.keys();for(let i of n){let a=this._variableObservers.get(i);a!=null&&(a.splice(a.indexOf(t),1),a.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(t,e){if(this._variableObservers===null)return;let n=this._variableObservers.get(t);if(typeof n<"u"){if(!(e instanceof g.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, y.asOrThrows)(e,g.Value);for(let a of n)a(t,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(t){return this.TagsAtStartOfFlowContainerWithPathString(t)}TagsAtStartOfFlowContainerWithPathString(t){let e=new Ga.Path(t),n=this.ContentAtPath(e).container;if(n===null)return (0, E.throwNullException)("flowContainer");for(;;){let r=n.content[0];if(r instanceof U.Container)n=r;else break}let i=false,a=null;for(let r of n.content){let s=(0, y.asOrNull)(r,S.ControlCommand);if(s!=null)s.commandType==S.ControlCommand.CommandType.BeginTag?i=true:s.commandType==S.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let l=(0, y.asOrNull)(r,g.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 t=new Yt.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}BuildStringOfContainer(t){let e=new Yt.StringBuilder;return t.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=jt.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let e=false;this.state.callStack.CanPop(dt.PushPopType.Function)?(this.state.PopCallStack(dt.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new nn.Void),e=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),e=true):this.state.TryExitFunctionEvaluationFromGame(),e&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let t=true,e=this.state.callStack.currentElement.currentPointer.copy();if(e.index++,e.container===null)return (0, E.throwNullException)("pointer.container");for(;e.index>=e.container.content.length;){t=false;let n=(0, y.asOrNull)(e.container.parent,U.Container);if(!(n instanceof U.Container))break;let i=n.content.indexOf(e.container);if(i==-1)break;if(e=new jt.Pointer(n,i),e.index++,t=true,e.container===null)return (0, E.throwNullException)("pointer.container")}return t||(e=jt.Pointer.Null),this.state.callStack.currentElement.currentPointer=e.copy(),t}TryFollowDefaultInvisibleChoice(){let t=this._state.currentChoices,e=t.filter(i=>i.isInvisibleDefault);if(e.length==0||t.length>e.length)return false;let n=e[0];return n.targetPath===null?(0, E.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, E.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 t=(0, y.asOrNull)(this.state.PopEvaluationStack(),g.IntValue);if(!(t instanceof g.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let e=this.state.currentPointer.container;if(e===null)return (0, E.throwNullException)("seqContainer");if(t.value===null)return (0, E.throwNullException)("numElementsIntVal.value");let n=t.value,a=(0, y.asOrThrows)(this.state.PopEvaluationStack(),g.IntValue).value;if(a===null)return (0, E.throwNullException)("seqCount");let r=a/n,s=a%n,l=e.path.toString(),u=0;for(let p=0,v=l.length;p<v;p++)u+=l.charCodeAt(p)||0;let h=u+r+this.state.storySeed,c=new $a.PRNG(Math.floor(h)),f=[];for(let p=0;p<n;++p)f.push(p);for(let p=0;p<=s;++p){let v=c.next()%f.length,w=f[v];if(f.splice(v,1),p==s)return w}throw new Error("Should never reach here")}Error(t,e=false){let n=new Xt.StoryException(t);throw n.useEndLineNumber=e,n}Warning(t){this.AddError(t,true);}AddError(t,e=false,n=false){let i=this.currentDebugMetadata,a=e?"WARNING":"ERROR";if(i!=null){let r=n?i.endLineNumber:i.startLineNumber;t="RUNTIME "+a+": '"+i.fileName+"' line "+r+": "+t;}else this.state.currentPointer.isNull?t="RUNTIME "+a+": "+t:t="RUNTIME "+a+": ("+this.state.currentPointer+"): "+t;this.state.AddError(t,e),e||this.state.ForceEnd();}Assert(t,e=null){if(t==false)throw e==null&&(e="Story assert"),new Error(e+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let t,e=this.state.currentPointer;if(!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(e=this.state.callStack.elements[n].currentPointer,!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.outputStream.length-1;n>=0;--n)if(t=this.state.outputStream[n].debugMetadata,t!==null)return t;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};Zt.Story=Se;Se.inkVersionCurrent=21;(function(o){(function(e){e[e.NoChange=0]="NoChange",e[e.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",e[e.NewlineRemoved=2]="NewlineRemoved";})(o.OutputStateChange||(o.OutputStateChange={}));})(Se||(Zt.Story=Se={}));});var Vl=d(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.Story=void 0;var Zd=Sn(),Qd=ri(),br=F(),Er=G(),sn=we(),wr=_t(),Rl=he(),tf=da(),ef=Ri(),nf=va(),rf=Ye(),ye=Tt(),sf=Wt(),af=Rt(),an=P(),of=Be(),lf=Ge(),uf=Ht(),Pr=class o extends wr.FlowBase{get flowLevel(){return Rl.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(t,e=false){super(null,t,null,false,e),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 i,a;this._errorHandler=n,this.constants=new Map;for(let h of this.FindAll(Qd.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let f=`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(f,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(ef.ListDefinition)())!((i=h.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=h.identifier)===null||a===void 0?void 0:a.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let r=this.runtimeObject,s=new br.Container;s.AddContent(Er.ControlCommand.EvalStart());let l=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),s.AddContent(c.listDefinition.runtimeObject),l.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(s);}let f=new af.VariableAssignment(h,true);f.isGlobal=true,s.AddContent(f);}s.AddContent(Er.ControlCommand.EvalEnd()),s.AddContent(Er.ControlCommand.End()),this.variableDeclarations.size>0&&(s.name="global decl",r.AddToNamedContentOnly(s)),r.AddContent(Er.ControlCommand.Done());let u=new rf.Story(r,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(r),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,a=null)=>{let r=null;if(n)return (r=this._listDefs.get(n))?r.ItemNamed(i):null;{let s=null,l=null;for(let[,u]of this._listDefs.entries()){let h=u.ItemNamed(i);h&&(s?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,false):(s=h,l=u));}return s}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let a of n.content){let r=(0, an.asOrNull)(a,br.Container);r&&i.add(r);}if(n.namedContent)for(let[,a]of n.namedContent){let r=(0, an.asOrNull)(a,br.Container);r&&i.add(r);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let i=(0, an.asOrNull)(n.parent,br.Container);if(i){let a=i.content.indexOf(n);i.content.splice(a,1);let r=n.ownDebugMetadata;if(n.content)for(let s of n.content)s.parent=null,r!==null&&s.ownDebugMetadata===null&&(s.debugMetadata=r),i.InsertContent(s,a),a+=1;}},this.Error=(n,i,a)=>{let r=a?sn.ErrorType.Warning:sn.ErrorType.Error,s="";if(i instanceof Zd.AuthorWarning?(s+="TODO: ",r=sn.ErrorType.Author):a?s+="WARNING: ":s+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(s+=`'${i.debugMetadata.fileName}' `),s+=`line ${i.debugMetadata.startLineNumber}: `),s+=n,n=s,this._errorHandler!==null)this._errorHandler(n,r);else throw new Error(n);this._hadError=r===sn.ErrorType.Error,this._hadWarning=r===sn.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,i,a,r)=>{n.Error(`${r} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,i,a,r="")=>{var s;let l=r||n.typeName;if(o.IsReservedKeyword(i?.name)){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(lf.FunctionCall.IsBuiltIn(i?.name||"")){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(i?.name||"",Rl.FlowLevel.Knot),h=(0, an.asOrNull)(u,wr.FlowBase);if(h&&(h!==n||a===ye.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,l);return}if(a<ye.SymbolType.List)return;for(let[v,w]of this._listDefs)if(i?.name===v&&n!==w&&w.variableAssignment!==n&&this.NameConflictError(n,i?.name,w,l),!(n instanceof nf.ListElementDefinition))for(let H of w.itemDefinitions)i?.name===H.name&&this.NameConflictError(n,i?.name||"",H,l);if(a<=ye.SymbolType.Var)return;let c=i?.name&&this.variableDeclarations.get(i?.name)||null;if(c&&c!==n&&c.isGlobalDeclaration&&c.listDefinition==null&&this.NameConflictError(n,i?.name||"",c,l),a<ye.SymbolType.SubFlowAndWeave)return;let p=new uf.Path(i).ResolveFromContext(n);if(p&&p!==n){this.NameConflictError(n,i?.name||"",p,l);return}if(!(a<ye.SymbolType.Arg)&&a!==ye.SymbolType.Arg){let v=(0, an.asOrNull)(n,wr.FlowBase);if(v||(v=(0, of.ClosestFlowBase)(n)),v&&v.hasParameters&&v.args){for(let w of v.args)if(((s=w.identifier)===null||s===void 0?void 0:s.name)===i?.name){n.Error(`${l} '${i}': name has already been used for a argument to ${v.identifier} on ${v.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(t){super.PreProcessTopLevelObjects(t);let e=[];for(let n of t)if(n instanceof tf.IncludedFile){let i=n,a=t.indexOf(n);if(t.splice(a,1),i.includedStory){let r=[],s=i.includedStory;if(s.content!=null){for(let l of s.content)l instanceof wr.FlowBase?e.push(l):r.push(l);r.push(new sf.Text(`
29
+ `)),t.splice(a,0,...r);}}continue}t.splice(0,0,...e);}};Or.Story=Pr;Pr.IsReservedKeyword=o=>{switch(o){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 Dl=d(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.StringExpression=void 0;var Wl=G(),hf=ot(),cf=Wt(),df=P(),Ua=class o extends hf.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof cf.Text))}constructor(t){super(),this.GenerateIntoContainer=e=>{e.AddContent(Wl.ControlCommand.BeginString());for(let n of this.content)e.AddContent(n.runtimeObject);e.AddContent(Wl.ControlCommand.EndString());},this.toString=()=>{let e="";for(let n of this.content)e+=n;return e},this.AddContent(t);}get typeName(){return "String"}Equals(t){let e=(0, df.asOrNull)(t,o);if(e===null||!this.isSingleString||!e.isSingleString)return false;let n=this.toString(),i=e.toString();return n===i}};xr.StringExpression=Ua;});var ql=d(_e=>{Object.defineProperty(_e,"__esModule",{value:true});_e.LegacyTag=_e.Tag=void 0;var ff=N(),Ll=G(),Ka=class extends ff.ParsedObject{constructor(t,e=false){super(),this.GenerateRuntimeObject=()=>this.isStart?Ll.ControlCommand.BeginTag():Ll.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=t,this.inChoice=e;}get typeName(){return "Tag"}};_e.Tag=Ka;var pf=oa(),Ha=class extends pf.Wrap{constructor(t){super(t);}get typeName(){return "Tag"}};_e.LegacyTag=Ha;});var jl=d(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.DefaultFileHandler=void 0;var Ja=class{constructor(t){this.rootPath=t,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.")};}};Tr.DefaultFileHandler=Ja;});var Za=d(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.InkParser=void 0;var mf=lo(),gf=Sn(),Cf=ns(),pt=bo(),j=De(),vf=ue(),Sf=Ao(),yf=ei(),on=Ws(),rt=mi(),_f=ri(),Nr=Qo(),bf=tl(),Qt=fe(),za=de(),Ef=ot(),wf=el(),Ml=nl(),Ir=Ge(),Pf=Me(),Of=il(),xf=Ji(),Ar=sl(),Bl=da(),Tf=al(),Nf=ma(),Gl=ll(),If=Ri(),Af=va(),Ff=Fs(),$l=N(),kf=Ht(),Ul=Es(),Kl=Us(),q=Bs(),Y=Sa(),Rf=_a(),Hl=Vl(),ln=Dl(),Nt=fs(),be=ql(),It=Wt(),Jl=Hs(),Xa=Qs(),Ya=me(),Vf=ts(),Mt=P(),un=di(),Ee=Vn(),zl=we(),Wf=jl(),x=class o extends Nt.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(t){this._fileHandler=t;}constructor(t,e=null,n=null,i=null,a=null){if(super(t),this.ParseStory=()=>{let r=this.StatementsAtLevel(Y.StatementLevel.Top);return new Hl.Story(r,this._rootParser!==this)},this.SeparatedList=(r,s)=>{let l=this.Parse(r);if(l===null)return null;let u=[];u.push(l);do{let h=this.BeginRule();if(s()===null){this.FailRule(h);break}let f=this.Parse(r);if(f===null){this.FailRule(h);break}this.SucceedRule(h),u.push(f);}while(true);return u},this.CreateDebugMetadata=(r,s)=>{let l=new bf.DebugMetadata;return l.startLineNumber=(r?.lineIndex||0)+1,l.endLineNumber=s.lineIndex+1,l.startCharacterNumber=(r?.characterInLineIndex||0)+1,l.endCharacterNumber=s.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(r,s,l)=>{let u=(0, Mt.asOrNull)(r,$l.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(s,l));let h=Array.isArray(r)?r:null;if(h!==null)for(let f of h)(0, Mt.asOrNull)(f,$l.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(s,l)));let c=(0, Mt.asOrNull)(r,un.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(s,l));},this.OnStringParserError=(r,s,l=0,u=false)=>{let c=u?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${l+1}: ${r}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,u?zl.ErrorType.Warning:zl.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let s=this.ParseUntilCharactersFromString(`
30
+ \r`);return s?new gf.AuthorWarning(s):null},this.ExtendIdentifierCharacterRanges=r=>{let s=o.ListAllCharacterRanges();for(let l of s)r.AddCharacters(l.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let r=true,s=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!s){if(s=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),s===null)return null;r=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 rt.ContentList(c));let f=null,p=null,v=this.ParseString("[")!==null;if(v){this.EndTagIfNecessary(h);let Pt=this.Parse(this.MixedTextAndLogic);Pt!==null&&(f=new rt.ContentList(Pt)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let st=this.Parse(this.MixedTextAndLogic);st!==null&&(p=new rt.ContentList(st));}this.Whitespace(),this.EndTagIfNecessary(p??h);let w=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let H=!h&&!p&&!f;if(H&&w===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&v&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),p||(p=new rt.ContentList),this.EndTagIfNecessary(p),w!==null)for(let Pt of w){let st=(0, Mt.asOrNull)(Pt,Qt.Divert);st&&st.isEmpty||p.AddContent(Pt);}p.AddContent(new It.Text(`
31
+ `));let R=new vf.Choice(h,f,p);return l&&(R.identifier=l),R.indentationDepth=s.length,R.hasWeaveStyleInlineBrackets=v,R.condition=u,R.onceOnly=r,R.isInvisibleDefault=H,R},this.ChoiceCondition=()=>{let r=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return r===null?null:r.length===1?r[0]:new Ff.MultipleConditionExpression(r)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Nt.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let r=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(r),this.Expect(this.String("}"),"closing '}' for choice condition"),r},this.Gather=()=>{let r=this.Parse(this.GatherDashes);if(r===null)return null;let s=Number(r),l=this.Parse(this.BracketedName),u=new Pf.Gather(l,s);return this.Newline(),u},this.GatherDashes=()=>{this.Whitespace();let r=0;for(;this.ParseDashNotArrow()!==null;)r+=1,this.Whitespace();return r===0?null:r},this.ParseDashNotArrow=()=>{let r=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(r):this.FailRule(r)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),r)},this.InnerConditionalContent=r=>{if(r===void 0){let c=this.Parse(this.ConditionExpression),f=this.Parse(()=>this.InnerConditionalContent(c));return f===null?null:f}let s,l=r!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)s=this.InlineConditionalBranches();else {if(s=this.MultilineConditionalBranches(),s===null){if(r){let c=this.StatementsAtLevel(Y.StatementLevel.InnerBlock);if(c!==null){s=[new on.ConditionalSingleBranch(c)];let p=this.Parse(this.SingleMultilineCondition);p&&(p.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",p),p.isElse=true),s.push(p));}}if(s===null)return null}else if(s.length===1&&s[0].isElse&&r){let c=new on.ConditionalSingleBranch(null);c.isTrueBranch=true,s.unshift(c);}if(r){let c=false;for(let f=0;f<s.length;++f){let p=s[f],v=f===s.length-1;p.ownExpression?(p.matchingEquality=true,c=true):c&&v?(p.matchingEquality=true,p.isElse=true):!v&&s.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",p):f===0?p.isTrueBranch=true:p.isElse=true;}}else {for(let c=0;c<s.length;++c){let f=s[c],p=c===s.length-1;if(f.ownExpression===null)if(p)f.isElse=true;else if(f.isElse){let v=s[s.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",f);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",f);}s.length===1&&s[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",s[0]);}}if(s===null)return null;for(let c of s)c.isInline=u;return new yf.Conditional(r,s)},this.InlineConditionalBranches=()=>{let r=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(r===null||r.length===0)return null;let s=[];if(r.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let l=new on.ConditionalSingleBranch(r[0]);if(l.isTrueBranch=true,s.push(l),r.length>1){let u=new on.ConditionalSingleBranch(r[1]);u.isElse=true,s.push(u);}}return s},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineCondition);return r===null?null:(this.MultilineWhitespace(),r)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=null,s=this.Parse(this.ElseExpression)!==null;s||(r=this.Parse(this.ConditionExpression));let l=this.StatementsAtLevel(Y.StatementLevel.InnerBlock);r===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new It.Text("")]),this.MultilineWhitespace();let u=new on.ConditionalSingleBranch(l);return u.ownExpression=r,u.isElse=s,u},this.ConditionExpression=()=>{let r=this.Parse(this.Expression);return r===null||(this.DisallowIncrement(r),this.Whitespace(),this.ParseString(":")===null)?null:r},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:Nt.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(r,s)=>{if(r.length>0){let l=r.length-1,u=r[l];if(u instanceof It.Text){let h=u;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),s?h.text+=" ":h.text.length===0&&(r.splice(l,1),this.TrimEndWhitespace(r,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let r=this.Parse(this.MixedTextAndLogic);if(!r||!r.length)return null;let s=r[0];return s&&s.text&&s.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),r.length===0?null:(r[r.length-1]instanceof Qt.Divert||this.TrimEndWhitespace(r,false),this.EndTagIfNecessary(r),r.length>0&&r[0]instanceof be.Tag&&r[0].isStart||r.push(new It.Text(`
32
+ `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),r)},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 s=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let l=this.Parse(this.MultiDivert);l!==null&&(s===null&&(s=[]),this.EndTagIfNecessary(s),this.TrimEndWhitespace(s,true),s.push(...l));}return s||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let r=null;do{let s=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||s!==null){if(r===null&&(r=""),s!==null&&(r+=String(s)),l){let u=this.ParseSingleCharacter();r+=u;}}else break}while(true);return r!==null?new It.Text(r):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new j.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new j.CharacterSet(`{}|
33
+ \r\\#`),this._notTextEndCharactersChoice=new j.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new j.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let r=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),s=null;this.parsingStringExpression?s=this._notTextEndCharactersString:this._parsingChoice?s=this._notTextEndCharactersChoice:s=this._nonTextEndCharacters;let l=this.ParseUntil(r,this._nonTextPauseCharacters,s);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let r=[],s=this.Parse(this.StartThread);if(s)return r=[s],r;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;r=[],this.EndTagIfNecessary(r);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 f=new Jl.TunnelOnwards;if(u<l.length-1){let p=(0, Mt.asOrNull)(l[u+1],Qt.Divert);f.divertAfter=p;}r.push(f);break}}else {let c=l[u];u<l.length-1&&(c.isTunnel=true),r.push(c);}if(r.length===0&&l.length===1){let u=new Qt.Divert(null);u.isEmpty=true,r.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return r},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let r=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new Qt.Divert(null));return r.isThread=true,r},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let r=this.Parse(this.DotSeparatedDivertPathComponents);if(!r)return null;this.Whitespace();let s=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new kf.Path(r);return new Qt.Divert(l,s)},this.SingleDivert=()=>{let r=this.Parse(this.MultiDivert);if(!r||r.length!==1||r[0]instanceof Jl.TunnelOnwards)return null;let l=r[0];return l.isTunnel?null:l},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let r=0;for(;this.ParseString("->")!==null;)r+=1;return r===0?null:r===1?"->":(r===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 r=this.ParseTempKeyword();this.Whitespace();let s=null;if(r?s=this.Expect(this.IdentifierWithMetadata,"variable name"):s=this.Parse(this.IdentifierWithMetadata),s===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 r&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return l||u?new Ar.IncDecExpression(s,h,l):new Xa.VariableAssignment({variableIdentifier:s,assignedExpression:h,isTemporaryNewDeclaration:r})},this.DisallowIncrement=r=>{r instanceof Ar.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let r=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(r),true):(this.FailRule(r),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let s=this.Parse(this.Expression);return new Ul.ReturnType(s)},this.Expression=(r=0)=>{this.Whitespace();let s=this.ExpressionUnary();if(s===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>r){let h=`right side of '${u.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(s,u),h);if(c===null)return this.FailRule(l),null;s=this.SucceedRule(l,c);continue}this.FailRule(l);break}return this.Whitespace(),s},this.ExpressionUnary=()=>{let r=this.Parse(this.ExpressionDivertTarget);if(r!==null)return r;let s=this.OneOf([this.String("-"),this.String("!")]);s===null&&(s=this.Parse(this.ExpressionNot)),this.Whitespace();let l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&s!==null&&(l=this.ExpressionUnary()),l===null)return null;s!==null&&(l=Vf.UnaryExpression.WithInner(l,s)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof Ya.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new Ar.IncDecExpression(c.identifier,h);}}return l},this.ExpressionNot=()=>{let r=this.Identifier();return r==="not"?r:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let r=this.Parse(this.SingleDivert);return !r||r&&r.isThread?null:(this.Whitespace(),new za.DivertTarget(r))},this.ExpressionInt=()=>{let r=this.ParseInt();return r===null?null:new Ee.NumberExpression(r,"int")},this.ExpressionFloat=()=>{let r=this.ParseFloat();return r===null?null:new Ee.NumberExpression(r,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let s=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,s===null?s=[new It.Text("")]:s.find(l=>l instanceof Qt.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new ln.StringExpression(s)},this.ExpressionBool=()=>{let r=this.Parse(this.Identifier);return r==="true"?new Ee.NumberExpression(true,"bool"):r==="false"?new Ee.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;this.Whitespace();let s=this.Parse(this.ExpressionFunctionCallArguments);return s===null?null:new Ir.FunctionCall(r,s)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Exclude(this.String(",")),s=this.Interleave(this.Expression,r);return s===null&&(s=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),s},this.ExpressionVariableName=()=>{let r=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return r===null||Hl.Story.IsReservedKeyword(r[0].name)?null:new Ya.VariableReference(r)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let r=this.Parse(this.Expression);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),r)},this.ExpressionInfixRight=(r,s)=>{if(!r)return null;this.Whitespace();let l=this.Parse(()=>this.Expression(s.precedence));return l?new Cf.BinaryExpression(r,l,s.type):null},this.ParseInfixOperator=()=>{for(let r of this._binaryOperators){let s=this.BeginRule();if(this.ParseString(r.type)!==null){if(r.requireWhitespace&&this.Whitespace()===null){this.FailRule(s);continue}return this.SucceedRule(s,r)}this.FailRule(s);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let r=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new Gl.List(r)},this.ListMember=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${r}`);r.name+=`.${l?.name}`;}return this.Whitespace(),r},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=(r,s,l=false)=>{let u=new Tf.InfixOperator(r,s,l);this._binaryOperators.push(u),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,r.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let r=this.Expect(()=>this.ParseUntilCharactersFromString(`
34
+ \r`),"filename for include statement");r=r.replace(new RegExp(/[ \t]+$/g),"");let s=this.fileHandler.ResolveInkFilename(r);if(this.FilenameIsAlreadyOpen(s))return this.Error(`Recursive INCLUDE detected: '${s}' is already open.`),this.ParseUntilCharactersFromString(`\r
35
+ `),new Bl.IncludedFile(null);this.AddOpenFilename(s);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(s);}catch(h){this.Error(`Failed to load: '${r}'.
36
+ Error:${h}`);}return u!=null&&(l=new o(u,r,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(s),new Bl.IncludedFile(l)},this.FilenameIsAlreadyOpen=r=>this._rootParser._openFilenames.includes(r),this.AddOpenFilename=r=>{this._rootParser._openFilenames.push(r);},this.RemoveOpenFilename=r=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(r),1);},this.KnotDefinition=()=>{let r=this.Parse(this.KnotDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let s=()=>this.StatementsAtLevel(Y.StatementLevel.Knot),l=this.Expect(s,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new Nf.Knot(r.name,l,r.args,r.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata),s,l=r?.name==="function";l?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),s=this.Parse(this.IdentifierWithMetadata)):s=r,s===null&&(this.Error(`Expected the name of the ${l?"function":"knot"}`),s=new un.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new Ml.FlowDecl(s,u,l)},this.KnotTitleEquals=()=>{let r=this.ParseCharactersFromString("=");return r===null||r.length<=1?null:r},this.StitchDefinition=()=>{let r=this.Parse(this.StitchDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let s=()=>this.StatementsAtLevel(Y.StatementLevel.Stitch),l=this.Expect(s,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new Rf.Stitch(r.name,l,r.args,r.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let r=this.ParseString("function")!==null;r&&this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new Ml.FlowDecl(s,l,r)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new j.CharacterSet("="),null),[new It.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),r===null&&(r=[]),r},this.FlowDeclArgument=()=>{let r=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let s=this.ParseDivertArrow();this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(r==null&&l===null)return null;let u=new mf.Argument;return s!==null&&(u.isDivertTarget=true),r!==null&&r.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=r,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},this.ExternalDeclaration=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!="EXTERNAL")return null;this.Whitespace();let s=this.Expect(this.IdentifierWithMetadata,"name of external function")||new un.Identifier("");this.Whitespace();let l=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${s}()'`);l===null&&(l=[]);let u=l.map(h=>{var c;return (c=h.identifier)===null||c===void 0?void 0:c.name}).filter(Mt.filterUndef);return new wf.ExternalDeclaration(s,u)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let r=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),s=this.Expect(r,"expression after '~'",this.SkipToNextLine);if(s===null)return new rt.ContentList;s instanceof Ef.Expression&&!(s instanceof Ir.FunctionCall||s instanceof Ar.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
37
+ ~ return
38
+ ~ var x = blah
39
+ ~ x++
40
+ ~ myFunction()`);let l=(0, Mt.asOrNull)(s,Ir.FunctionCall);return l&&(l.shouldPopReturnedValue=true),s.Find(Ir.FunctionCall)()!==null&&(s=new rt.ContentList(s,new It.Text(`
41
+ `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),s},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let s=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 Ee.NumberExpression||u instanceof ln.StringExpression||u instanceof za.DivertTarget||u instanceof Ya.VariableReference||u instanceof Gl.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 ln.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new Xa.VariableAssignment({assignedExpression:u,isGlobalDeclaration:true,variableIdentifier:s})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let s=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 un.Identifier(s.name),new Xa.VariableAssignment({variableIdentifier:s,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let r=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return r===null?null:new If.ListDefinition(r)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let r=this.ParseString("(")!==null,s=r;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),r&&this.ParseString(")")!=null&&(s=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),s&&(this.Whitespace(),this.ParseString(")")!==null&&(s=false));}return s&&this.Error("Expected closing ')'"),new Af.ListElementDefinition(l,r,u)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let s=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 Ee.NumberExpression||l instanceof za.DivertTarget||l instanceof ln.StringExpression?l instanceof ln.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 _f.ConstantDeclaration(s,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new Of.Glue(new xf.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let r=this.parsingStringExpression,s=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=r,null;this.DisallowIncrement(l);let u=(0, Mt.asOrNull)(l,rt.ContentList);return u||(u=new rt.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=r,s||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let r=this.ParseObject(this.SequenceTypeAnnotation);if(r!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new Kl.Sequence(u,r)}let s=this.Parse(this.ConditionExpression);if(s)return this.Expect(()=>this.InnerConditionalContent(s),"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 r=this.Parse(this.Expression);return r&&(r.outputWhenComplete=true),r},this.IdentifierWithMetadata=()=>{let r=this.Identifier();return r===null?null:new un.Identifier(r)},this.Identifier=()=>{let r=this.ParseCharactersFromCharSet(this.identifierCharSet);if(r===null)return null;let s=true;for(let l of r)if(!(l>="0"&&l<="9")){s=false;break}return s?null:r},this._sequenceTypeSymbols=new j.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let r=q.SequenceType.Stopping,s=this.Parse(this.SequenceTypeAnnotation);s!==null&&(r=s);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new Kl.Sequence(l,r)},this.SequenceTypeAnnotation=()=>{let r=this.Parse(this.SequenceTypeSymbolAnnotation);if(r===null&&(r=this.Parse(this.SequenceTypeWordAnnotation)),r===null)return null;switch(r){case q.SequenceType.Once:case q.SequenceType.Cycle:case q.SequenceType.Stopping:case q.SequenceType.Shuffle:case q.SequenceType.Shuffle|q.SequenceType.Stopping:case q.SequenceType.Shuffle|q.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${r}`),q.SequenceType.Stopping}return r},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new j.CharacterSet("!&~$ "));let r=0,s=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(s===null)return null;for(let l of s)switch(l){case "!":r|=q.SequenceType.Once;break;case "&":r|=q.SequenceType.Cycle;break;case "~":r|=q.SequenceType.Shuffle;break;case "$":r|=q.SequenceType.Stopping;break}return r===0?null:r},this.SequenceTypeWordAnnotation=()=>{let r=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(r===null||r.length===0||this.ParseString(":")===null)return null;let s=0;for(let l of r)s|=l;return s},this.SequenceTypeSingleWord=()=>{let r=null,s=this.Parse(this.IdentifierWithMetadata);if(s!==null)switch(s.name){case "once":r=q.SequenceType.Once;break;case "cycle":r=q.SequenceType.Cycle;break;case "shuffle":r=q.SequenceType.Shuffle;break;case "stopping":r=q.SequenceType.Stopping;break}return r===null?null:r},this.InnerSequenceObjects=()=>{let r=this.Parse(this.Newline)!==null,s=null;return r?s=this.Parse(this.InnerMultilineSequenceObjects):s=this.Parse(this.InnerInlineSequenceObjects),s},this.InnerInlineSequenceObjects=()=>{let r=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(r===null)return null;let s=[],l=false;for(let u of r)if(u==="|")l||s.push(new rt.ContentList),l=false;else {let h=u;h===null?this.Error(`Expected content, but got ${u} (this is an ink compiler bug!)`):s.push(new rt.ContentList(h)),l=true;}return l||s.push(new rt.ContentList),s},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineSequenceElement);return r===null?null:r},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=this.StatementsAtLevel(Y.StatementLevel.InnerBlock);return r===null?this.MultilineWhitespace():r.unshift(new It.Text(`
42
+ `)),new rt.ContentList(r)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=r=>(r===Y.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(r),()=>this.StatementsBreakForLevel(r))),this.StatementAtLevel=r=>{let s=this._statementRulesAtLevel[r],l=this.OneOf(s);return r===Y.StatementLevel.Top&&l instanceof Ul.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=r=>{this.Whitespace();let s=this._statementBreakRulesAtLevel[r],l=this.OneOf(s);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let r=Object.values(Y.StatementLevel);this._statementRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]);for(let s of r){let l=[],u=[];l.push(this.Line(this.MultiDivert)),s>=Y.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),s>Y.StatementLevel.InnerBlock&&l.push(this.Gather),s>=Y.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),s<=Y.StatementLevel.Knot&&u.push(this.KnotDeclaration),s<=Y.StatementLevel.Stitch&&u.push(this.StitchDeclaration),s<=Y.StatementLevel.InnerBlock&&(u.push(this.ParseDashNotArrow),u.push(this.String("}"))),this._statementRulesAtLevel[s]=l,this._statementBreakRulesAtLevel[s]=u;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
43
+ \r`),this.ParseNewline(),Nt.ParseSuccess),this.Line=r=>()=>{let s=this.ParseObject(r);return s===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),s)},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 r=null;if(this.tagActive){let s=new rt.ContentList;s.AddContent(new be.Tag(false)),s.AddContent(new be.Tag(true)),r=s;}else r=new be.Tag(true);return this.tagActive=true,this.Whitespace(),r},this._inlineWhitespaceChars=new j.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Nt.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Nt.ParseSuccess:null),this.MultilineWhitespace=()=>{let r=this.OneOrMore(this.Newline);return r===null?null:r.length>=1?Nt.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Nt.ParseSuccess:null,this.Spaced=r=>()=>{this.Whitespace();let s=this.ParseObject(r);return s===null?null:(this.Whitespace(),s)},this.AnyWhitespace=()=>{let r=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)r=true;return r?Nt.ParseSuccess:null},this.MultiSpaced=r=>()=>{this.AnyWhitespace();let s=this.ParseObject(r);return s===null?null:(this.AnyWhitespace(),s)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=e,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new Wf.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let r=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(r);}}else this._rootParser=i;}PreProcessInputString(t){return new Sf.CommentEliminator(t).Process()}get parsingStringExpression(){return this.GetFlag(Number(Nr.CustomFlags.ParsingString))}set parsingStringExpression(t){this.SetFlag(Number(Nr.CustomFlags.ParsingString),t);}get tagActive(){return this.GetFlag(Number(Nr.CustomFlags.TagActive))}set tagActive(t){this.SetFlag(Number(Nr.CustomFlags.TagActive),t);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new j.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(t){this.tagActive&&(t!=null&&(t instanceof rt.ContentList?t.AddContent(new be.Tag(false)):t.push(new be.Tag(false))),this.tagActive=false);}};Fr.InkParser=x;x.LatinBasic=pt.CharacterRange.Define("A","z",new j.CharacterSet().AddRange("[","`"));x.LatinExtendedA=pt.CharacterRange.Define("\u0100","\u017F");x.LatinExtendedB=pt.CharacterRange.Define("\u0180","\u024F");x.Greek=pt.CharacterRange.Define("\u0370","\u03FF",new j.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));x.Cyrillic=pt.CharacterRange.Define("\u0400","\u04FF",new j.CharacterSet().AddRange("\u0482","\u0489"));x.Armenian=pt.CharacterRange.Define("\u0530","\u058F",new j.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));x.Hebrew=pt.CharacterRange.Define("\u0590","\u05FF",new j.CharacterSet);x.Arabic=pt.CharacterRange.Define("\u0600","\u06FF",new j.CharacterSet);x.Korean=pt.CharacterRange.Define("\uAC00","\uD7AF",new j.CharacterSet);x.Latin1Supplement=pt.CharacterRange.Define("\x80","\xFF",new j.CharacterSet);x.Chinese=pt.CharacterRange.Define("\u4E00","\u9FFF",new j.CharacterSet);x.ListAllCharacterRanges=()=>[x.LatinBasic,x.LatinExtendedA,x.LatinExtendedB,x.Arabic,x.Armenian,x.Cyrillic,x.Greek,x.Hebrew,x.Korean,x.Latin1Supplement,x.Chinese];});var Xl=d(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.GenerateStoryStats=void 0;var Df=ue(),Lf=fe(),qf=Me(),jf=ma(),Mf=_a(),Bf=Wt();function Gf(o){let t=o.FindAll(Bf.Text)(),e=0;for(let l of t){let u=0,h=true;for(let c of l.text)c==" "||c==" "||c==`
44
+ `||c=="\r"?h=true:h&&(u++,h=false);e+=u;}let n=o.FindAll(jf.Knot)(),i=o.FindAll(Mf.Stitch)(),a=o.FindAll(Df.Choice)(),r=o.FindAll(qf.Gather)(l=>l.debugMetadata!=null),s=o.FindAll(Lf.Divert)();return {words:e,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:i.length,gathers:r.length,diverts:s.length-1,choices:a.length}}kr.GenerateStoryStats=Gf;});var Yl=d(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.JsonFileHandler=void 0;var Qa=class{constructor(t){this.fileHierarchy=t,this.ResolveInkFilename=e=>{if(Object.keys(this.fileHierarchy).includes(e))return e;throw new Error(`Cannot locate ${e}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=e=>{if(Object.keys(this.fileHierarchy).includes(e))return this.fileHierarchy[e];throw new Error(`Cannot open ${e}.`)};}};Rr.JsonFileHandler=Qa;});var Ql=d(K=>{Object.defineProperty(K,"__esModule",{value:true});K.Compiler=K.Story=K.InkList=K.JsonFileHandler=K.StatementLevel=K.InkParser=K.CompilerOptions=void 0;var $f=Dr(),Uf=oo(),to=we(),Kf=Za(),Hf=I(),Jf=P(),zf=Xl(),Xf=Dr();Object.defineProperty(K,"CompilerOptions",{enumerable:true,get:function(){return Xf.CompilerOptions}});var Yf=Za();Object.defineProperty(K,"InkParser",{enumerable:true,get:function(){return Yf.InkParser}});var Zf=Sa();Object.defineProperty(K,"StatementLevel",{enumerable:true,get:function(){return Zf.StatementLevel}});var Qf=Yl();Object.defineProperty(K,"JsonFileHandler",{enumerable:true,get:function(){return Qf.JsonFileHandler}});var Zl=Ye();Object.defineProperty(K,"InkList",{enumerable:true,get:function(){return Zl.InkList}});Object.defineProperty(K,"Story",{enumerable:true,get:function(){return Zl.Story}});var eo=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(t,e=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new Kf.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 i of this.runtimeStory.state.outputStream){let a=(0, Jf.asOrNull)(i,Hf.StringValue);if(a!==null){let r=new Uf.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(r);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, zf.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let i=0,a=null;for(let r of this.debugSourceRanges){if(r.debugMetadata!==null&&(a=r.debugMetadata),n>=i&&n<i+r.length)return a;i+=r.length;}return null},this.OnError=(n,i)=>{switch(i){case to.ErrorType.Author:this._authorMessages.push(n);break;case to.ErrorType.Warning:this._warnings.push(n);break;case to.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=t,this._options=e||new $f.CompilerOptions;}};K.Compiler=eo;});var dn;(i=>(i.log=(a,...r)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...r),i.warn=(a,...r)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...r),i.error=(a,...r)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...r),i.info=(a,...r)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...r)))(dn||(dn={}));var eu=so(Ql(),1),nu=so(we(),1);function tu(o,t=[],e=[]){let n=[];try{return {json:new eu.Compiler(o,{errorHandler:(s,l)=>{n.push({message:s,type:l});},countAllVisits:!0,fileHandler:null,pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:n,labelToRemove:t,initialVarsToRemove:e}}catch(i){let a=n.find(r=>r.type===nu.ErrorType.Error);if(a){if(a.message.includes("Divert target not found")){let r=a.message.match(/Divert target not found: '-> (\w+)'/);if(r&&r[1]){let s=r[1],l=`
45
+
46
+ === ${s} ===
47
+
48
+ -> DONE`;return o=o.concat(l),tu(o,[...t,s],e)}}if(a.message.includes("Unresolved variable")){let r=a.message.match(/Unresolved variable: (\w+)/);if(r&&r[1]){let s=r[1];return o=`VAR ${s} = ""
49
+
50
+ `.concat(o),tu(o,t,[...e,s])}}return {issues:n,labelToRemove:t,initialVarsToRemove:e}}throw dn.error("Error compiling ink file"),i}}export{tp as a,so as b,ep as c,dn as d,we as e,tu as f};