Files
ai.interactive.fiction/prototype/ink-full.js
T

3 lines
240 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).inkjs={})}(this,(function(t){"use strict";class e{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;this.sourceFilename=t,this.pluginNames=e,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=r}}class n{constructor(t,e,n){this.length=t,this.debugMetadata=e,this.text=n}}var i;!function(t){t[t.Author=0]="Author",t[t.Warning=1]="Warning",t[t.Error=2]="Error"}(i||(i={}));class r{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.identifier=t,this.isByReference=e,this.isDivertTarget=n}get typeName(){return"Argument"}}function s(t,e){return t instanceof e?u(t):null}function a(t,e){if(t instanceof e)return u(t);throw new Error(`${t} is not of type ${e}`)}function o(t){return t.hasValidName&&t.name?t:null}function l(t){return void 0===t?null:t}function h(t){return"object"==typeof t&&"function"==typeof t.Equals}function u(t,e){return t}function c(t){return null!=t}class d{constructor(){var t=this;this._alreadyHadError=!1,this._alreadyHadWarning=!1,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=t=>{null===this.content&&(this.content=[]);const e=Array.isArray(t)?t:[t];for(const t of e)t.hasOwnProperty("parent")&&(t.parent=this),this.content.push(t);return Array.isArray(t)?void 0:t},this.InsertContent=(t,e)=>(null===this.content&&(this.content=[]),e.parent=this,this.content.splice(t,0,e),e),this.Find=e=>function(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=s(t,e);if(null!==i&&(null===n||!0===n(i)))return i;if(null===t.content)return null;for(const i of t.content){let t=i.Find&&i.Find(e)(n);if(t)return t}return null},this.FindAll=t=>(e,n)=>{const i=Array.isArray(n)?n:[],r=s(this,t);if(null===r||e&&!0!==e(r)||i.push(r),null===this.content)return[];for(const n of this.content)n.FindAll&&n.FindAll(t)(e,i);return i},this.Warning=function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;t.Error(e,n,!0)}}get debugMetadata(){return null===this._debugMetadata&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t}get hasOwnDebugMetadata(){return Boolean(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(null!==this.content)for(const e of this.content)e.ResolveReferences(t)}Error(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(null===e&&(e=this),!(e._alreadyHadError&&!n||e._alreadyHadWarning&&n)){if(!this.parent)throw new Error(`No parent object to send error to: ${t}`);this.parent.Error(t,e,n),n?e._alreadyHadWarning=!0:e._alreadyHadError=!0}}}class p extends d{constructor(t){super(),this.warningMessage=t,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null)}get typeName(){return"AuthorWarning"}}let m=class t{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=!1,"string"==typeof arguments[0]){let t=arguments[0];this.componentsString=t}else if(arguments[0]instanceof t.Component&&arguments[1]instanceof t){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 e=this._components.slice(1,this._components.length);return new t(e)}return t.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!0;return!1}static get self(){let e=new t;return e._isRelative=!0,e}GetComponent(t){return this._components[t]}PathByAppendingPath(e){let n=new t,i=0;for(let t=0;t<e._components.length&&e._components[t].isParent;++t)i++;for(let t=0;t<this._components.length-i;++t)n._components.push(this._components[t]);for(let t=i;t<e._components.length;++t)n._components.push(e._components[t]);return n}get componentsString(){return null==this._componentsString&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,null==this._componentsString||""==this._componentsString)return;"."==this._componentsString[0]&&(this._isRelative=!0,this._componentsString=this._componentsString.substring(1));let n=this._componentsString.split(".");for(let e of n)/^(\-|\+)?([0-9]+|Infinity)$/.test(e)?this._components.push(new t.Component(parseInt(e))):this._components.push(new t.Component(e))}toString(){return this.componentsString}Equals(t){if(null==t)return!1;if(t._components.length!=this._components.length)return!1;if(t.isRelative!=this.isRelative)return!1;for(let e=0,n=t._components.length;e<n;e++)if(!t._components[e].Equals(this._components[e]))return!1;return!0}PathByAppendingComponent(e){let n=new t;return n._components.push(...this._components),n._components.push(e),n}};var f,g,v;m.parentId="^",function(t){class e{constructor(t){this.index=-1,this.name=null,"string"==typeof t?this.name=t:this.index=t}get isIndex(){return this.index>=0}get isParent(){return this.name==t.parentId}static ToParent(){return new e(t.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(t){return null!=t&&t.isIndex==this.isIndex&&(this.isIndex?this.index==t.index:this.name==t.name)}}t.Component=e}(m||(m={})),function(t){function e(t,e){if(!t)throw void 0!==e&&console.warn(e),console.trace&&console.trace(),new Error("")}t.AssertType=function(t,n,i){e(t instanceof n,i)},t.Assert=e}(f||(f={}));class C extends Error{}function S(t){throw new C(`${t} is null or undefined`)}class y{constructor(){this.parent=null,this._debugMetadata=null,this._path=null}get debugMetadata(){return null===this._debugMetadata&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(t){if(null===t)return null;let e=this.rootContentContainer;if(e){let n=e.ContentAtPath(t).obj;if(n){let t=n.debugMetadata;if(null!==t)return t.startLineNumber}}return null}get path(){if(null==this._path)if(null==this.parent)this._path=new m;else{let t=[],e=this,n=s(e.parent,L);for(;null!==n;){let i=o(e);if(null!=i&&i.hasValidName){if(null===i.name)return S("namedChild.name");t.unshift(new m.Component(i.name))}else t.unshift(new m.Component(n.content.indexOf(e)));e=n,n=s(n.parent,L)}this._path=new m(t)}return this._path}ResolvePath(t){if(null===t)return S("path");if(t.isRelative){let e=s(this,L);return null===e&&(f.Assert(null!==this.parent,"Can't resolve relative path because we don't have a parent"),e=s(this.parent,L),f.Assert(null!==e,"Expected parent to be a container"),f.Assert(t.GetComponent(0).isParent),t=t.tail),null===e?S("nearestContainer"):e.ContentAtPath(t)}{let e=this.rootContentContainer;return null===e?S("contentContainer"):e.ContentAtPath(t)}}ConvertPathToRelative(t){let e=this.path,n=Math.min(t.length,e.length),i=-1;for(let r=0;r<n;++r){let n=e.GetComponent(r),s=t.GetComponent(r);if(!n.Equals(s))break;i=r}if(-1==i)return t;let r=e.componentCount-1-i,s=[];for(let t=0;t<r;++t)s.push(m.Component.ToParent());for(let e=i+1;e<t.componentCount;++e)s.push(t.GetComponent(e));return new m(s,!0)}CompactPathString(t){let e=null,n=null;if(t.isRelative)n=t.componentsString,e=this.path.PathByAppendingPath(t).componentsString;else{n=this.ConvertPathToRelative(t).componentsString,e=t.componentsString}return n.length<e.length?n:e}get rootContentContainer(){let t=this;for(;t.parent;)t=t.parent;return s(t,L)}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}}class b{constructor(t){t=void 0!==t?t.toString():"",this.string=t}get Length(){return this.string.length}Append(t){null!==t&&(this.string+=t)}AppendLine(t){void 0!==t&&this.Append(t),this.string+="\n"}AppendFormat(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];this.string+=t.replace(/{(\d+)}/g,((t,e)=>void 0!==n[e]?n[e]:t))}toString(){return this.string}Clear(){this.string=""}}class w{constructor(){if(this.originName=null,this.itemName=null,void 0!==arguments[1]){let t=arguments[0],e=arguments[1];this.originName=t,this.itemName=e}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1]}}static get Null(){return new w(null,null)}get isNull(){return null==this.originName&&null==this.itemName}get fullName(){return(null!==this.originName?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(t){if(t instanceof w){let e=t;return e.itemName==this.itemName&&e.originName==this.originName}return!1}copy(){return new w(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let e=JSON.parse(t);if(!w.isLikeInkListItem(e))return w.Null;let n=e;return new w(n.originName,n.itemName)}static isLikeInkListItem(t){return"object"==typeof t&&(!(!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName"))&&(("string"==typeof t.originName||null===typeof t.originName)&&("string"==typeof t.itemName||null===typeof t.itemName)))}}class E extends Map{constructor(){if(super(arguments[0]instanceof E?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof E){let t=arguments[0],e=t.originNames;null!==e&&(this._originNames=e.slice()),null!==t.origins&&(this.origins=t.origins.slice())}else if("string"==typeof arguments[0]){let t=arguments[0],e=arguments[1];if(this.SetInitialOriginName(t),null===e.listDefinitions)return S("originStory.listDefinitions");let n=e.listDefinitions.TryListGetDefinition(t,null);if(!n.exists)throw new Error("InkList origin could not be found in story when constructing new list: "+t);if(null===n.result)return S("def.result");this.origins=[n.result]}else if("object"==typeof arguments[0]&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let t=arguments[0];this.Add(t.Key,t.Value)}}static FromString(t,e){var n;let i=null===(n=e.listDefinitions)||void 0===n?void 0:n.FindSingleItemListWithName(t);if(i)return null===i.value?S("listValue.value"):new E(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){if(t instanceof w){let e=t;if(null==e.originName)return void this.AddItem(e.itemName);if(null===this.origins)return S("this.origins");for(let t of this.origins)if(t.name==e.originName){let n=t.TryGetValueForItem(e,0);if(n.exists)return void this.Add(e,n.result);throw new Error("Could not add the item "+e+" 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.")}{let e=t,n=null;if(null===this.origins)return S("this.origins");for(let t of this.origins){if(null===e)return S("itemName");if(t.ContainsItemWithName(e)){if(null!=n)throw new Error("Could not add the item "+e+" to this list because it could come from either "+t.name+" or "+n.name);n=t}}if(null==n)throw new Error("Could not add the item "+e+" to this list because it isn't known to any list definitions previously associated with this list.");let i=new w(n.name,e),r=n.ValueForItem(i);this.Add(i,r)}}ContainsItemNamed(t){for(let[e]of this){if(w.fromSerializedKey(e).itemName==t)return!0}return!1}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(null==this.origins)return null;let t=this.maxItem.Key.originName,e=null;return this.origins.every((n=>n.name!=t||(e=n,!1))),e}get originNames(){if(this.Count>0){null==this._originNames&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let e=w.fromSerializedKey(t);if(null===e.originName)return S("item.originName");this._originNames.push(e.originName)}}return this._originNames}SetInitialOriginName(t){this._originNames=[t]}SetInitialOriginNames(t){this._originNames=null==t?null:t.slice()}get maxItem(){let t={Key:w.Null,Value:0};for(let[e,n]of this){let i=w.fromSerializedKey(e);(t.Key.isNull||n>t.Value)&&(t={Key:i,Value:n})}return t}get minItem(){let t={Key:w.Null,Value:0};for(let[e,n]of this){let i=w.fromSerializedKey(e);(t.Key.isNull||n<t.Value)&&(t={Key:i,Value:n})}return t}get inverse(){let t=new E;if(null!=this.origins)for(let e of this.origins)for(let[n,i]of e.items){let e=w.fromSerializedKey(n);this.ContainsKey(e)||t.Add(e,i)}return t}get all(){let t=new E;if(null!=this.origins)for(let e of this.origins)for(let[n,i]of e.items){let e=w.fromSerializedKey(n);t.set(e.serialized(),i)}return t}Union(t){let e=new E(this);for(let[n,i]of t)e.set(n,i);return e}Intersect(t){let e=new E;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!0;return!1}Without(t){let e=new E(this);for(let[n]of t)e.delete(n);return e}Contains(t){if("string"==typeof t)return this.ContainsItemNamed(t);const e=t;if(0==e.size||0==this.size)return!1;for(let[t]of e)if(!this.has(t))return!1;return!0}GreaterThan(t){return 0!=this.Count&&(0==t.Count||this.minItem.Value>t.maxItem.Value)}GreaterThanOrEquals(t){return 0!=this.Count&&(0==t.Count||this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value)}LessThan(t){return 0!=t.Count&&(0==this.Count||this.maxItem.Value<t.minItem.Value)}LessThanOrEquals(t){return 0!=t.Count&&(0==this.Count||this.maxItem.Value<=t.maxItem.Value&&this.minItem.Value<=t.minItem.Value)}MaxAsList(){return this.Count>0?new E(this.maxItem):new E}MinAsList(){return this.Count>0?new E(this.minItem):new E}ListWithSubRange(t,e){if(0==this.Count)return new E;let n=this.orderedItems,i=0,r=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?i=t:t instanceof E&&t.Count>0&&(i=t.minItem.Value),Number.isInteger(e)?r=e:e instanceof E&&e.Count>0&&(r=e.maxItem.Value);let s=new E;s.SetInitialOriginNames(this.originNames);for(let t of n)t.Value>=i&&t.Value<=r&&s.Add(t.Key,t.Value);return s}Equals(t){if(t instanceof E==!1)return!1;if(t.Count!=this.Count)return!1;for(let[e]of this)if(!t.has(e))return!1;return!0}get orderedItems(){let t=new Array;for(let[e,n]of this){let i=w.fromSerializedKey(e);t.push({Key:i,Value:n})}return t.sort(((t,e)=>null===t.Key.originName?S("x.Key.originName"):null===e.Key.originName?S("y.Key.originName"):t.Value==e.Value?t.Key.originName.localeCompare(e.Key.originName):t.Value<e.Value?-1:t.Value>e.Value?1:0)),t}toString(){let t=this.orderedItems,e=new b;for(let n=0;n<t.length;n++){n>0&&e.Append(", ");let i=t[n].Key;if(null===i.itemName)return S("item.itemName");e.Append(i.itemName)}return e.toString()}valueOf(){return NaN}}class _ extends Error{constructor(t){super(t),this.useEndLineNumber=!1,this.message=t,this.name="StoryException"}}function T(t,e,n){if(null===t)return{result:n,exists:!1};let i=t.get(e);return void 0===i?{result:n,exists:!1}:{result:i,exists:!0}}class x extends y{static Create(t,e){if(e){if(e===g.Int&&Number.isInteger(Number(t)))return new N(Number(t));if(e===g.Float&&!isNaN(t))return new O(Number(t))}return"boolean"==typeof t?new P(Boolean(t)):"string"==typeof t?new I(String(t)):Number.isInteger(Number(t))?new N(Number(t)):isNaN(t)?t instanceof m?new F(a(t,m)):t instanceof E?new R(a(t,E)):null:new O(Number(t))}Copy(){return a(x.Create(this.valueObject),y)}BadCastException(t){return new _("Can't cast "+this.valueObject+" from "+this.valueType+" to "+t)}}class A extends x{constructor(t){super(),this.value=t}get valueObject(){return this.value}toString(){return null===this.value?S("Value.value"):this.value.toString()}}class P extends A{constructor(t){super(t||!1)}get isTruthy(){return Boolean(this.value)}get valueType(){return g.Bool}Cast(t){if(null===this.value)return S("Value.value");if(t==this.valueType)return this;if(t==g.Int)return new N(this.value?1:0);if(t==g.Float)return new O(this.value?1:0);if(t==g.String)return new I(this.value?"true":"false");throw this.BadCastException(t)}toString(){return this.value?"true":"false"}}class N extends A{constructor(t){super(t||0)}get isTruthy(){return 0!=this.value}get valueType(){return g.Int}Cast(t){if(null===this.value)return S("Value.value");if(t==this.valueType)return this;if(t==g.Bool)return new P(0!==this.value);if(t==g.Float)return new O(this.value);if(t==g.String)return new I(""+this.value);throw this.BadCastException(t)}}class O extends A{constructor(t){super(t||0)}get isTruthy(){return 0!=this.value}get valueType(){return g.Float}Cast(t){if(null===this.value)return S("Value.value");if(t==this.valueType)return this;if(t==g.Bool)return new P(0!==this.value);if(t==g.Int)return new N(this.value);if(t==g.String)return new I(""+this.value);throw this.BadCastException(t)}}class I extends A{constructor(t){if(super(t||""),this._isNewline="\n"==this.value,this._isInlineWhitespace=!0,null===this.value)return S("Value.value");this.value.length>0&&this.value.split("").every((t=>" "==t||"\t"==t||(this._isInlineWhitespace=!1,!1)))}get valueType(){return g.String}get isTruthy(){return null===this.value?S("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==g.Int){let e=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=parseInt(t);return Number.isNaN(n)?{result:e,exists:!1}:{result:n,exists:!0}}(this.value);if(e.exists)return new N(e.result);throw this.BadCastException(t)}if(t==g.Float){let e=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=parseFloat(t);return Number.isNaN(n)?{result:e,exists:!1}:{result:n,exists:!0}}(this.value);if(e.exists)return new O(e.result);throw this.BadCastException(t)}throw this.BadCastException(t)}}class F extends A{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:null)}get valueType(){return g.DivertTarget}get targetPath(){return null===this.value?S("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+")"}}class W extends A{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;super(t),this._contextIndex=e}get contextIndex(){return this._contextIndex}set contextIndex(t){this._contextIndex=t}get variableName(){return null===this.value?S("Value.value"):this.value}set variableName(t){this.value=t}get valueType(){return g.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 W(this.variableName,this.contextIndex)}}class R extends A{get isTruthy(){return null===this.value?S("this.value"):this.value.Count>0}get valueType(){return g.List}Cast(t){if(null===this.value)return S("Value.value");if(t==g.Int){let t=this.value.maxItem;return t.Key.isNull?new N(0):new N(t.Value)}if(t==g.Float){let t=this.value.maxItem;return t.Key.isNull?new O(0):new O(t.Value)}if(t==g.String){let t=this.value.maxItem;return t.Key.isNull?new I(""):new I(t.Key.toString())}if(t==this.valueType)return this;throw this.BadCastException(t)}constructor(t,e){super(null),t||e?t instanceof E?this.value=new E(t):t instanceof w&&"number"==typeof e&&(this.value=new E({Key:t,Value:e})):this.value=new E}static RetainListOriginsForAssignment(t,e){let n=s(t,R),i=s(e,R);return i&&null===i.value?S("newList.value"):n&&null===n.value?S("oldList.value"):void(n&&i&&0==i.value.Count&&i.value.SetInitialOriginNames(n.value.originNames))}}!function(t){t[t.Bool=-1]="Bool",t[t.Int=0]="Int",t[t.Float=1]="Float",t[t.List=2]="List",t[t.String=3]="String",t[t.DivertTarget=4]="DivertTarget",t[t.VariablePointer=5]="VariablePointer"}(g||(g={}));class k{constructor(){this.obj=null,this.approximate=!1}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof L?this.obj:null}copy(){let t=new k;return t.obj=this.obj,t.approximate=this.approximate,t}}class L extends y{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=!1,this.turnIndexShouldBeCounted=!1,this.countingAtStartOnly=!1,this._pathToFirstLeafContent=null}get hasValidName(){return null!=this.name&&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=a(n,y);t.set(e,i)}for(let e of this.content){let n=o(e);null!=n&&n.hasValidName&&t.delete(n.name)}return 0==t.size&&(t=null),t}set namedOnlyContent(t){let e=this.namedOnlyContent;if(null!=e)for(let[t]of e)this.namedContent.delete(t);if(null!=t)for(let[,e]of t){let t=o(e);null!=t&&this.AddToNamedContentOnly(t)}}get countFlags(){let t=0;return this.visitsShouldBeCounted&&(t|=L.CountFlags.Visits),this.turnIndexShouldBeCounted&&(t|=L.CountFlags.Turns),this.countingAtStartOnly&&(t|=L.CountFlags.CountStartOnly),t==L.CountFlags.CountStartOnly&&(t=0),t}set countFlags(t){let e=t;(e&L.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=!0),(e&L.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=!0),(e&L.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=!0)}get pathToFirstLeafContent(){return null==this._pathToFirstLeafContent&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let t=[],e=this;for(;e instanceof L;)e.content.length>0&&(t.push(new m.Component(0)),e=e.content[0]);return new m(t)}AddContent(t){if(t instanceof Array){let e=t;for(let t of e)this.AddContent(t)}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=o(t);null!=e&&e.hasValidName&&this.AddToNamedContentOnly(e)}AddToNamedContentOnly(t){if(f.AssertType(t,y,"Can only add Runtime.Objects to a Runtime.Container"),a(t,y).parent=this,null===t.name)return S("namedContentObj.name");this.namedContent.set(t.name,t)}ContentAtPath(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;-1==n&&(n=t.length);let i=new k;i.approximate=!1;let r=this,a=this;for(let o=e;o<n;++o){let e=t.GetComponent(o);if(null==r){i.approximate=!0;break}let n=r.ContentWithPathComponent(e);if(null==n){i.approximate=!0;break}a=n,r=s(n,L)}return i.obj=a,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(null===t.name)return S("component.name");let e=T(this.namedContent,t.name,null);return e.exists?a(e.result,y):null}}BuildStringOfHierarchy(){let t;if(0==arguments.length)return t=new b,this.BuildStringOfHierarchy(t,0,null),t.toString();t=arguments[0];let e=arguments[1],n=arguments[2];function i(){for(let n=0;n<4*e;++n)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];if(s instanceof L){s.BuildStringOfHierarchy(t,e,n)}else i(),s instanceof I?(t.Append('"'),t.Append(s.toString().replace("\n","\\n")),t.Append('"')):t.Append(s.toString());r!=this.content.length-1&&t.Append(","),s instanceof L||s!=n||t.Append(" <---"),t.AppendLine()}let r=new Map;for(let[t,e]of this.namedContent)this.content.indexOf(a(e,y))>=0||r.set(t,e);if(r.size>0){i(),t.AppendLine("-- named: --");for(let[,i]of r){f.AssertType(i,L,"Can only print out named Containers"),i.BuildStringOfHierarchy(t,e,n),t.AppendLine()}}e--,i(),t.Append("]")}}!function(t){var e;(e=t.CountFlags||(t.CountFlags={}))[e.Start=0]="Start",e[e.Visits=1]="Visits",e[e.Turns=2]="Turns",e[e.CountStartOnly=4]="CountStartOnly"}(L||(L={}));class D extends y{get commandType(){return this._commandType}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:D.CommandType.NotSet;super(),this._commandType=t}Copy(){return new D(this.commandType)}static EvalStart(){return new D(D.CommandType.EvalStart)}static EvalOutput(){return new D(D.CommandType.EvalOutput)}static EvalEnd(){return new D(D.CommandType.EvalEnd)}static Duplicate(){return new D(D.CommandType.Duplicate)}static PopEvaluatedValue(){return new D(D.CommandType.PopEvaluatedValue)}static PopFunction(){return new D(D.CommandType.PopFunction)}static PopTunnel(){return new D(D.CommandType.PopTunnel)}static BeginString(){return new D(D.CommandType.BeginString)}static EndString(){return new D(D.CommandType.EndString)}static NoOp(){return new D(D.CommandType.NoOp)}static ChoiceCount(){return new D(D.CommandType.ChoiceCount)}static Turns(){return new D(D.CommandType.Turns)}static TurnsSince(){return new D(D.CommandType.TurnsSince)}static ReadCount(){return new D(D.CommandType.ReadCount)}static Random(){return new D(D.CommandType.Random)}static SeedRandom(){return new D(D.CommandType.SeedRandom)}static VisitIndex(){return new D(D.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new D(D.CommandType.SequenceShuffleIndex)}static StartThread(){return new D(D.CommandType.StartThread)}static Done(){return new D(D.CommandType.Done)}static End(){return new D(D.CommandType.End)}static ListFromInt(){return new D(D.CommandType.ListFromInt)}static ListRange(){return new D(D.CommandType.ListRange)}static ListRandom(){return new D(D.CommandType.ListRandom)}static BeginTag(){return new D(D.CommandType.BeginTag)}static EndTag(){return new D(D.CommandType.EndTag)}toString(){return"ControlCommand "+this.commandType.toString()}}!function(t){var e;(e=t.CommandType||(t.CommandType={}))[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"}(D||(D={}));class V extends d{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=!1,this.GenerateRuntimeObject=()=>{const t=new L;return t.AddContent(D.EvalStart()),this.GenerateIntoContainer(t),this.outputWhenComplete&&t.AddContent(D.EvalOutput()),t.AddContent(D.EvalEnd()),t},this.GenerateConstantIntoContainer=t=>{null===this._prototypeRuntimeConstantExpression&&(this._prototypeRuntimeConstantExpression=new L,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(const e of this._prototypeRuntimeConstantExpression.content){const n=e.Copy();n&&t.AddContent(n)}},this.toString=()=>"No string value in JavaScript."}get typeName(){return"Expression"}Equals(t){return!1}}class j extends y{toString(){return"Void"}}class B extends y{static CallWithName(t){return new B(t)}static CallExistsWithName(t){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(t)}get name(){return null===this._name?S("NativeFunctionCall._name"):this._name}set name(t){this._name=t,this._isPrototype||(null===B._nativeFunctions?S("NativeFunctionCall._nativeFunctions"):this._prototype=B._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=!1;for(let n of t){if(n instanceof j)throw new _('Attempting to perform operation on a void value. Did you forget to "return" a value from a function you called here?');n instanceof R&&(e=!0)}if(2==t.length&&e)return this.CallBinaryListOperation(t);let n=this.CoerceValuesToSingleType(t),i=n[0].valueType;return i==g.Int||i==g.Float||i==g.String||i==g.DivertTarget||i==g.List?this.CallType(n):null}CallType(t){let e=a(t[0],A),n=e.valueType,i=e,r=t.length;if(2==r||1==r){if(null===this._operationFuncs)return S("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){const t=g[n];throw new _("Cannot perform operation "+this.name+" on "+t)}if(2==r){let e=a(t[1],A),n=s;if(null===i.value||null===e.value)return S("NativeFunctionCall.Call BinaryOp values");let r=n(i.value,e.value);return A.Create(r)}{let t=s;if(null===i.value)return S("NativeFunctionCall.Call UnaryOp value");let n=t(i.value);return this.name===B.Int?A.Create(n,g.Int):this.name===B.Float?A.Create(n,g.Float):A.Create(n,e.valueType)}}throw new Error("Unexpected number of parameters to NativeFunctionCall: "+t.length)}CallBinaryListOperation(t){if(("+"==this.name||"-"==this.name)&&t[0]instanceof R&&t[1]instanceof N)return this.CallListIncrementOperation(t);let e=a(t[0],A),n=a(t[1],A);if(!("&&"!=this.name&&"||"!=this.name||e.valueType==g.List&&n.valueType==g.List)){if(null===this._operationFuncs)return S("NativeFunctionCall._operationFuncs");let t=this._operationFuncs.get(g.Int);if(null===t)return S("NativeFunctionCall.CallBinaryListOperation op");let i=function(t){if("boolean"==typeof t)return t;throw new Error(`${t} is not a boolean`)}(t(e.isTruthy?1:0,n.isTruthy?1:0));return new P(i)}if(e.valueType==g.List&&n.valueType==g.List)return this.CallType([e,n]);throw new _("Can not call use "+this.name+" operation on "+g[e.valueType]+" and "+g[n.valueType])}CallListIncrementOperation(t){let e=a(t[0],R),n=a(t[1],N),i=new E;if(null===e.value)return S("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[t,r]of e.value){let s=w.fromSerializedKey(t);if(null===this._operationFuncs)return S("NativeFunctionCall._operationFuncs");let a=this._operationFuncs.get(g.Int);if(null===n.value)return S("NativeFunctionCall.CallListIncrementOperation intVal.value");let o=a(r,n.value),l=null;if(null===e.value.origins)return S("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let t of e.value.origins)if(t.name==s.originName){l=t;break}if(null!=l){let t=l.TryGetItemWithValue(o,w.Null);t.exists&&i.Add(t.result,o)}}return new R(i)}CoerceValuesToSingleType(t){let e=g.Int,n=null;for(let i of t){let t=a(i,A);t.valueType>e&&(e=t.valueType),t.valueType==g.List&&(n=s(t,R))}let i=[];if(g[e]==g[g.List])for(let e of t){let t=a(e,A);if(t.valueType==g.List)i.push(t);else{if(t.valueType!=g.Int){const e=g[t.valueType];throw new _("Cannot mix Lists and "+e+" values in this operation")}{let e=parseInt(t.valueObject);if(n=a(n,R),null===n.value)return S("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let r=n.value.originOfMaxItem;if(null===r)return S("NativeFunctionCall.CoerceValuesToSingleType list");let s=r.TryGetItemWithValue(e,w.Null);if(!s.exists)throw new _("Could not find List item with the value "+e+" in "+r.name);{let t=new R(s.result,e);i.push(t)}}}}else for(let n of t){let t=a(n,A).Cast(e);i.push(t)}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=!1,this._operationFuncs=null,0===arguments.length)B.GenerateNativeFunctionsIfNecessary();else if(1===arguments.length){let t=arguments[0];B.GenerateNativeFunctionsIfNecessary(),this.name=t}else if(2===arguments.length){let t=arguments[0],e=arguments[1];this._isPrototype=!0,this.name=t,this.numberOfParameters=e}}static Identity(t){return t}static GenerateNativeFunctionsIfNecessary(){if(null==this._nativeFunctions){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,((t,e)=>t+e)),this.AddIntBinaryOp(this.Subtract,((t,e)=>t-e)),this.AddIntBinaryOp(this.Multiply,((t,e)=>t*e)),this.AddIntBinaryOp(this.Divide,((t,e)=>Math.floor(t/e))),this.AddIntBinaryOp(this.Mod,((t,e)=>t%e)),this.AddIntUnaryOp(this.Negate,(t=>-t)),this.AddIntBinaryOp(this.Equal,((t,e)=>t==e)),this.AddIntBinaryOp(this.Greater,((t,e)=>t>e)),this.AddIntBinaryOp(this.Less,((t,e)=>t<e)),this.AddIntBinaryOp(this.GreaterThanOrEquals,((t,e)=>t>=e)),this.AddIntBinaryOp(this.LessThanOrEquals,((t,e)=>t<=e)),this.AddIntBinaryOp(this.NotEquals,((t,e)=>t!=e)),this.AddIntUnaryOp(this.Not,(t=>0==t)),this.AddIntBinaryOp(this.And,((t,e)=>0!=t&&0!=e)),this.AddIntBinaryOp(this.Or,((t,e)=>0!=t||0!=e)),this.AddIntBinaryOp(this.Max,((t,e)=>Math.max(t,e))),this.AddIntBinaryOp(this.Min,((t,e)=>Math.min(t,e))),this.AddIntBinaryOp(this.Pow,((t,e)=>Math.pow(t,e))),this.AddIntUnaryOp(this.Floor,B.Identity),this.AddIntUnaryOp(this.Ceiling,B.Identity),this.AddIntUnaryOp(this.Int,B.Identity),this.AddIntUnaryOp(this.Float,(t=>t)),this.AddFloatBinaryOp(this.Add,((t,e)=>t+e)),this.AddFloatBinaryOp(this.Subtract,((t,e)=>t-e)),this.AddFloatBinaryOp(this.Multiply,((t,e)=>t*e)),this.AddFloatBinaryOp(this.Divide,((t,e)=>t/e)),this.AddFloatBinaryOp(this.Mod,((t,e)=>t%e)),this.AddFloatUnaryOp(this.Negate,(t=>-t)),this.AddFloatBinaryOp(this.Equal,((t,e)=>t==e)),this.AddFloatBinaryOp(this.Greater,((t,e)=>t>e)),this.AddFloatBinaryOp(this.Less,((t,e)=>t<e)),this.AddFloatBinaryOp(this.GreaterThanOrEquals,((t,e)=>t>=e)),this.AddFloatBinaryOp(this.LessThanOrEquals,((t,e)=>t<=e)),this.AddFloatBinaryOp(this.NotEquals,((t,e)=>t!=e)),this.AddFloatUnaryOp(this.Not,(t=>0==t)),this.AddFloatBinaryOp(this.And,((t,e)=>0!=t&&0!=e)),this.AddFloatBinaryOp(this.Or,((t,e)=>0!=t||0!=e)),this.AddFloatBinaryOp(this.Max,((t,e)=>Math.max(t,e))),this.AddFloatBinaryOp(this.Min,((t,e)=>Math.min(t,e))),this.AddFloatBinaryOp(this.Pow,((t,e)=>Math.pow(t,e))),this.AddFloatUnaryOp(this.Floor,(t=>Math.floor(t))),this.AddFloatUnaryOp(this.Ceiling,(t=>Math.ceil(t))),this.AddFloatUnaryOp(this.Int,(t=>Math.floor(t))),this.AddFloatUnaryOp(this.Float,B.Identity),this.AddStringBinaryOp(this.Add,((t,e)=>t+e)),this.AddStringBinaryOp(this.Equal,((t,e)=>t===e)),this.AddStringBinaryOp(this.NotEquals,((t,e)=>!(t===e))),this.AddStringBinaryOp(this.Has,((t,e)=>t.includes(e))),this.AddStringBinaryOp(this.Hasnt,((t,e)=>!t.includes(e))),this.AddListBinaryOp(this.Add,((t,e)=>t.Union(e))),this.AddListBinaryOp(this.Subtract,((t,e)=>t.Without(e))),this.AddListBinaryOp(this.Has,((t,e)=>t.Contains(e))),this.AddListBinaryOp(this.Hasnt,((t,e)=>!t.Contains(e))),this.AddListBinaryOp(this.Intersect,((t,e)=>t.Intersect(e))),this.AddListBinaryOp(this.Equal,((t,e)=>t.Equals(e))),this.AddListBinaryOp(this.Greater,((t,e)=>t.GreaterThan(e))),this.AddListBinaryOp(this.Less,((t,e)=>t.LessThan(e))),this.AddListBinaryOp(this.GreaterThanOrEquals,((t,e)=>t.GreaterThanOrEquals(e))),this.AddListBinaryOp(this.LessThanOrEquals,((t,e)=>t.LessThanOrEquals(e))),this.AddListBinaryOp(this.NotEquals,((t,e)=>!t.Equals(e))),this.AddListBinaryOp(this.And,((t,e)=>t.Count>0&&e.Count>0)),this.AddListBinaryOp(this.Or,((t,e)=>t.Count>0||e.Count>0)),this.AddListUnaryOp(this.Not,(t=>0==t.Count?1:0)),this.AddListUnaryOp(this.Invert,(t=>t.inverse)),this.AddListUnaryOp(this.All,(t=>t.all)),this.AddListUnaryOp(this.ListMin,(t=>t.MinAsList())),this.AddListUnaryOp(this.ListMax,(t=>t.MaxAsList())),this.AddListUnaryOp(this.Count,(t=>t.Count)),this.AddListUnaryOp(this.ValueOfList,(t=>t.maxItem.Value));let t=(t,e)=>t.Equals(e),e=(t,e)=>!t.Equals(e);this.AddOpToNativeFunc(this.Equal,2,g.DivertTarget,t),this.AddOpToNativeFunc(this.NotEquals,2,g.DivertTarget,e)}}AddOpFuncForType(t,e){null==this._operationFuncs&&(this._operationFuncs=new Map),this._operationFuncs.set(t,e)}static AddOpToNativeFunc(t,e,n,i){if(null===this._nativeFunctions)return S("NativeFunctionCall._nativeFunctions");let r=this._nativeFunctions.get(t);r||(r=new B(t,e),this._nativeFunctions.set(t,r)),r.AddOpFuncForType(n,i)}static AddIntBinaryOp(t,e){this.AddOpToNativeFunc(t,2,g.Int,e)}static AddIntUnaryOp(t,e){this.AddOpToNativeFunc(t,1,g.Int,e)}static AddFloatBinaryOp(t,e){this.AddOpToNativeFunc(t,2,g.Float,e)}static AddFloatUnaryOp(t,e){this.AddOpToNativeFunc(t,1,g.Float,e)}static AddStringBinaryOp(t,e){this.AddOpToNativeFunc(t,2,g.String,e)}static AddListBinaryOp(t,e){this.AddOpToNativeFunc(t,2,g.List,e)}static AddListUnaryOp(t,e){this.AddOpToNativeFunc(t,1,g.List,e)}toString(){return'Native "'+this.name+'"'}}B.Add="+",B.Subtract="-",B.Divide="/",B.Multiply="*",B.Mod="%",B.Negate="_",B.Equal="==",B.Greater=">",B.Less="<",B.GreaterThanOrEquals=">=",B.LessThanOrEquals="<=",B.NotEquals="!=",B.Not="!",B.And="&&",B.Or="||",B.Min="MIN",B.Max="MAX",B.Pow="POW",B.Floor="FLOOR",B.Ceiling="CEILING",B.Int="INT",B.Float="FLOAT",B.Has="?",B.Hasnt="!?",B.Intersect="^",B.ListMin="LIST_MIN",B.ListMax="LIST_MAX",B.All="LIST_ALL",B.Count="LIST_COUNT",B.ValueOfList="LIST_VALUE",B.Invert="LIST_INVERT",B._nativeFunctions=null;class M extends V{constructor(t,e){if(super(),this.isInt=()=>"int"==this.subtype,this.isFloat=()=>"float"==this.subtype,this.isBool=()=>"bool"==this.subtype,this.GenerateIntoContainer=t=>{this.isInt()?t.AddContent(new N(this.value)):this.isFloat()?t.AddContent(new O(this.value)):this.isBool()&&t.AddContent(new P(this.value))},this.toString=()=>String(this.value),("number"!=typeof t||Number.isNaN(t))&&"boolean"!=typeof t)throw new Error("Unexpected object type in NumberExpression.");this.value=t,this.subtype=e}get typeName(){return"Number"}Equals(t){const e=s(t,M);return!!e&&(e.subtype==this.subtype&&e.value==this.value)}}class G extends V{get nativeNameForOp(){return"-"===this.op?"_":"not"===this.op?"!":this.op}constructor(t,e){super(),this.op=e,this.GenerateIntoContainer=t=>{this.innerExpression.GenerateIntoContainer(t),t.AddContent(B.CallWithName(this.nativeNameForOp))},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(t)}get typeName(){return"UnaryExpression"}}G.WithInner=(t,e)=>{const n=s(t,M);if(n){if("-"===e){if(n.isInt())return new M(-n.value,"int");if(n.isFloat())return new M(-n.value,"float")}else if("!"==e||"not"==e){if(n.isInt())return new M(0==n.value,"bool");if(n.isFloat())return new M(0==n.value,"bool");if(n.isBool())return new M(!n.value,"bool")}throw new Error("Unexpected operation or number type")}return new G(t,e)};class $ extends V{constructor(t,e,n){super(),this.opName=n,this.GenerateIntoContainer=t=>{this.leftExpression.GenerateIntoContainer(t),this.rightExpression.GenerateIntoContainer(t),this.opName=this.NativeNameForOp(this.opName),t.AddContent(B.CallWithName(this.opName))},this.NativeNameForOp=t=>"and"===t?"&&":"or"===t?"||":"mod"===t?"%":"has"===t?"?":"hasnt"===t?"!?":t,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)){const t=s(this.leftExpression,G);null===t||"not"!==t.op&&"!"!==t.op||this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`)}}}class q{constructor(t){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,e)=>{for(let n=t.charCodeAt(0);n<=e.charCodeAt(0);++n)this.Add(String.fromCharCode(n));return this},this.AddCharacters=t=>{if("string"==typeof t||Array.isArray(t))for(const e of t)this.Add(e);else for(const e of t.set)this.Add(e);return this},t&&this.AddCharacters(t)}}q.FromRange=(t,e)=>(new q).AddRange(t,e);class U{constructor(t,e){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];if(this._start=t,this._end=e,this._correspondingCharSet=new q,this._excludes=new Set,this.ToCharacterSet=()=>{if(0===this._correspondingCharSet.set.size)for(let t,e=this.start.charCodeAt(0);e<=this.end.charCodeAt(0);e+=1)t=String.fromCharCode(e),this._excludes.has(t)||this._correspondingCharSet.AddCharacters(t);return this._correspondingCharSet},n instanceof q)this._excludes=n.set;else for(const t of n)this._excludes.add(t)}get start(){return this._start}get end(){return this._end}}U.Define=function(t,e){return new U(t,e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:[])};class K extends y{constructor(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];super(),this._pathOnChoice=null,this.hasCondition=!1,this.hasStartContent=!1,this.hasChoiceOnlyContent=!1,this.isInvisibleDefault=!1,this.onceOnly=!0,this.onceOnly=t}get pathOnChoice(){if(null!=this._pathOnChoice&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path)}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t}get choiceTarget(){return null===this._pathOnChoice?S("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return null===this.pathOnChoice?S("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new m(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=(1&t)>0,this.hasStartContent=(2&t)>0,this.hasChoiceOnlyContent=(4&t)>0,this.isInvisibleDefault=(8&t)>0,this.onceOnly=(16&t)>0}toString(){if(null===this.pathOnChoice)return S("ChoicePoint.pathOnChoice");return"Choice: -> "+this.pathOnChoice.toString()}}!function(t){t[t.Tunnel=0]="Tunnel",t[t.Function=1]="Function",t[t.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame"}(v||(v={}));class H{constructor(){this.container=null,this.index=-1,2===arguments.length&&(this.container=arguments[0],this.index=arguments[1])}Resolve(){return this.index<0?this.container:null==this.container?null:0==this.container.content.length?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return null==this.container}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new m.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 H(this.container,this.index)}static StartOf(t){return new H(t,0)}static get Null(){return new H(null,-1)}}let J=class t extends y{get targetPath(){if(null!=this._targetPath&&this._targetPath.isRelative){let t=this.targetPointer.Resolve();t&&(this._targetPath=t.path)}return this._targetPath}set targetPath(t){this._targetPath=t,this._targetPointer=H.Null}get targetPointer(){if(this._targetPointer.isNull){let t=this.ResolvePath(this._targetPath).obj;if(null===this._targetPath)return S("this._targetPath");if(null===this._targetPath.lastComponent)return S("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(null===t)return S("targetObj");this._targetPointer.container=t.parent instanceof L?t.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index}else this._targetPointer=H.StartOf(t instanceof L?t:null)}return this._targetPointer.copy()}get targetPathString(){return null==this.targetPath?null:this.CompactPathString(this.targetPath)}set targetPathString(t){this.targetPath=null==t?null:new m(t)}get hasVariableTarget(){return null!=this.variableDivertName}constructor(t){super(),this._targetPath=null,this._targetPointer=H.Null,this.variableDivertName=null,this.pushesToStack=!1,this.stackPushType=0,this.isExternal=!1,this.externalArgs=0,this.isConditional=!1,this.pushesToStack=!1,void 0!==t&&(this.pushesToStack=!0,this.stackPushType=t)}Equals(e){let n=e;return n instanceof t&&this.hasVariableTarget==n.hasVariableTarget&&(this.hasVariableTarget?this.variableDivertName==n.variableDivertName:null===this.targetPath?S("this.targetPath"):this.targetPath.Equals(n.targetPath))}toString(){if(this.hasVariableTarget)return"Divert(variable: "+this.variableDivertName+")";if(null==this.targetPath)return"Divert(null)";{let t=new b,e=this.targetPath.toString();return t.Append("Divert"),this.isConditional&&t.Append("?"),this.pushesToStack&&(this.stackPushType==v.Function?t.Append(" function"):t.Append(" tunnel")),t.Append(" -> "),t.Append(this.targetPathString),t.Append(" ("),t.Append(e),t.Append(")"),t.toString()}}};var z;!function(t){t[t.Knot=0]="Knot",t[t.List=1]="List",t[t.ListItem=2]="ListItem",t[t.Var=3]="Var",t[t.SubFlowAndWeave=4]="SubFlowAndWeave",t[t.Arg=5]="Arg",t[t.Temp=6]="Temp"}(z||(z={}));let X=class extends y{constructor(t,e){super(),this.variableName=t||null,this.isNewDeclaration=!!e,this.isGlobal=!1}toString(){return"VarAssign to "+this.variableName}},Y=class extends d{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var t;return(null===(t=this.identifier)||void 0===t?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=!1,this.hasWeaveStyleInlineBrackets=!1,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new L,this._runtimeChoice=new K(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(D.EvalStart()),this.startContent){this._returnToR1=new F,this._outerContainer.AddContent(this._returnToR1);const t=new X("$r",!0);this._outerContainer.AddContent(t),this._outerContainer.AddContent(D.BeginString()),this._divertToStartContentOuter=new J,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";const e=new J;e.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(e),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new L,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(D.EndString()),this._runtimeChoice.hasStartContent=!0}if(this.choiceOnlyContent){this._outerContainer.AddContent(D.BeginString());const t=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(t),this._outerContainer.AddContent(D.EndString()),this._runtimeChoice.hasChoiceOnlyContent=!0}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=!0),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(D.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new L,this.startContent){this._returnToR2=new F,this._innerContentContainer.AddContent(D.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(D.EvalEnd());const t=new X("$r",!0);this._innerContentContainer.AddContent(t),this._divertToStartContentInner=new J,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new L,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label)}if(this.innerContent){const t=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(t)}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=!0),this._innerContentContainer.countingAtStartOnly=!0,this._outerContainer},this.toString=()=>null!==this.choiceOnlyContent?`* ${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=!0}get typeName(){return"Choice"}ResolveReferences(t){var e;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=!0)),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&&((null===(e=this.identifier)||void 0===e?void 0:e.name)||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,z.SubFlowAndWeave)}};class Z{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=!1,this.uniqueId=0,this.customFlags=0,this.CopyFrom=t=>{Z._uniqueIdCounter++,this.uniqueId=Z._uniqueIdCounter,this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.customFlags=t.customFlags,this.reportedErrorInScope=!1},this.SquashFrom=t=>{this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.reportedErrorInScope=t.reportedErrorInScope,this.customFlags=t.customFlags}}}Z._uniqueIdCounter=1e3;class Q{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 t=0;t<200;++t)this._stack[t]=new Z;this._numElements=1},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");const t=this._stack[this._numElements-1],e=this._stack[this._numElements];return this._numElements++,e.CopyFrom(t),e.uniqueId},this.Pop=t=>{if(1==this._numElements)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");const t=this._stack[this._numElements-2],e=this._stack[this._numElements-1];t.SquashFrom(e),this._numElements-=1},this.NoteErrorReported=()=>{for(const t of this._stack)t.reportedErrorInScope=!0};for(let t=0;t<200;t++)this._stack[t]=new Z;this._numElements=1}}const tt=Symbol("ParseSuccessStruct");class et{constructor(t){var e=this;this.ParseRule=null,this.errorHandler=null,this.hadError=!1,this.BeginRule=()=>this.state.Push(),this.FailRule=t=>(this.state.Pop(t),null),this.CancelRule=t=>{this.state.Pop(t)},this.SucceedRule=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;const i=e.state.Peek(t),r=e.state.PeekPenultimate();e.RuleDidSucceed&&e.RuleDidSucceed(n,r,i),e.state.Squash();let s=n;return null===s&&(s=et.ParseSuccess),s},this.Expect=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=e.ParseObject(t);if(null===r){let s;null===n&&(n=t.name);const a=e.LineRemainder();s=null===a||0===a.length?"end of line":`'${a}'`,e.Error(`Expected ${n} but saw ${s}`),null!==i&&(r=i())}return r},this.Error=function(t){let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];e.ErrorOnLine(t,e.lineIndex+1,n)},this.ErrorWithParsedObject=function(t,n){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];e.ErrorOnLine(t,n.debugMetadata?n.debugMetadata.startLineNumber:-1,i)},this.ErrorOnLine=(t,e,n)=>{if(!this.state.errorReportedAlreadyInScope){const i=n?"Warning":"Error";if(!this.errorHandler)throw new Error(`${i} on line ${e}: ${t}`);this.errorHandler(t,this.index,e-1,n),this.state.NoteErrorReported()}n||(this.hadError=!0)},this.Warning=t=>this.Error(t,!0),this.LineRemainder=()=>this.Peek((()=>this.ParseUntilCharactersFromString("\n\r"))),this.SetFlag=(t,e)=>{e?this.state.customFlags|=t:this.state.customFlags&=~t},this.GetFlag=t=>Boolean(this.state.customFlags&t),this.ParseObject=t=>{const e=this.BeginRule(),n=this.state.stackHeight,i=t();if(n!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return null===i?this.FailRule(e):(this.SucceedRule(e,i),i)},this.Parse=t=>{const e=this.BeginRule(),n=t();return null===n?(this.FailRule(e),null):(this.SucceedRule(e,n),n)},this.OneOf=t=>{for(const e of t){const t=this.ParseObject(e);if(null!==t)return t}return null},this.OneOrMore=t=>{const e=[];let n=null;do{n=this.ParseObject(t),null!==n&&e.push(n)}while(null!==n);return e.length>0?e:null},this.Optional=t=>()=>{const e=this.ParseObject(t);return null===e?et.ParseSuccess:e},this.Exclude=t=>()=>this.ParseObject(t)&&et.ParseSuccess,this.OptionalExclude=t=>()=>(this.ParseObject(t),et.ParseSuccess),this.String=t=>()=>this.ParseString(t),this.TryAddResultToList=function(t,e){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(t!==et.ParseSuccess){if(n&&Array.isArray(t)){const n=t;if(null!==n){for(const t of n)e.push(t);return}}e.push(t)}},this.Interleave=function(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];const s=e.BeginRule(),a=[],o=e.ParseObject(t);if(null===o)return e.FailRule(s);e.TryAddResultToList(o,a,r);let l=null,h=null;do{if(null!==i&&null!==e.Peek(i))break;if(l=e.ParseObject(n),null===l)break;if(e.TryAddResultToList(l,a,r),h=null,null!==l){if(h=e.ParseObject(t),null===h)break;e.TryAddResultToList(h,a,r)}}while((null!==l||null!==h)&&(l!==et.ParseSuccess||h!=et.ParseSuccess)&&e.remainingLength>0);return 0===a.length?e.FailRule(s):e.SucceedRule(s,a)},this.ParseString=t=>{if(t.length>this.remainingLength)return null;const e=this.BeginRule();let n=this.index,i=this.characterInLineIndex,r=this.lineIndex,s=!0;for(let e=0;e<t.length;e+=1){const a=t[e];if(this._chars[n]!==a){s=!1;break}"\n"===a&&(r++,i=-1),n++,i++}return this.index=n,this.characterInLineIndex=i,this.lineIndex=r,s?this.SucceedRule(e,t):this.FailRule(e)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){const t=this._chars[this.index];return"\n"===t&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,t}return"0"},this.ParseUntilCharactersFromString=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return e.ParseCharactersFromString(t,!1,n)},this.ParseUntilCharactersFromCharSet=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return e.ParseCharactersFromCharSet(t,!1,n)},this.ParseCharactersFromString=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;const r=new q(t);return"number"==typeof n?e.ParseCharactersFromCharSet(r,!0,n):e.ParseCharactersFromCharSet(r,n,i)},this.ParseCharactersFromCharSet=function(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;-1===i&&(i=Number.MAX_SAFE_INTEGER);const r=e.index;let s=e.index,a=e.characterInLineIndex,o=e.lineIndex,l=0;for(;s<e._chars.length&&t.set.has(e._chars[s])===n&&l<i;)"\n"===e._chars[s]&&(o+=1,a=-1),s+=1,a+=1,l+=1;e.index=s,e.characterInLineIndex=a,e.lineIndex=o;return e.index>r?e._chars.slice(r,e.index).join(""):null},this.Peek=t=>{const e=this.BeginRule(),n=t();return this.CancelRule(e),n},this.ParseInt=()=>{const t=this.index,e=this.characterInLineIndex,n=null!==this.ParseString("-");this.ParseCharactersFromString(" \t");const i=this.ParseCharactersFromCharSet(et.numbersCharacterSet);if(null===i)return this.index=t,this.characterInLineIndex=e,null;let r;return Number.isNaN(Number(i))?(this.Error("Failed to read integer value: "+i+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(r=Number(i),n?-r:r)},this.ParseFloat=()=>{const t=this.index,e=this.characterInLineIndex,n=this.ParseInt();if(null!==n&&null!==this.ParseString(".")){const t=this.ParseCharactersFromCharSet(et.numbersCharacterSet);return Number(`${n}.${t}`)}return this.index=t,this.characterInLineIndex=e,null},this.ParseNewline=()=>{const t=this.BeginRule();return this.ParseString("\r"),null===this.ParseString("\n")?this.FailRule(t):this.SucceedRule(t,"\n")};const n=this.PreProcessInputString(t);this.state=new Q,this._chars=t?n.split(""):[],this.inputString=n}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){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;const i=this.BeginRule(),r=new q;null!==e&&(r.set=new Set([...r.set.values(),...e.set.values()])),null!==n&&(r.set=new Set([...r.set.values(),...n.set.values()]));let s="",a=null;for(;;){const n=this.ParseUntilCharactersFromCharSet(r);if(n&&(s+=n),a=this.Peek(t),null!==a)break;{if(this.endOfInput)break;const t=this.currentCharacter;if(null!==e&&e.set.has(t)){s+=t,"\n"===t&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}break}}return s.length>0?this.SucceedRule(i,String(s)):this.FailRule(i)}}et.ParseSuccess=tt,et.numbersCharacterSet=new q("0123456789");class nt extends et{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new q("/\r\n"),this._commentBlockEndCharacter=new q("*"),this._newlineCharacters=new q("\n\r"),this.Process=()=>{const t=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return null!==t?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 null!==t?t.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>null===this.ParseString("//")?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(null===this.ParseString("/*"))return null;const t=this.lineIndex,e=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),null!=e?"\n".repeat(this.lineIndex-t):null}}PreProcessInputString(t){return t}}class it extends d{constructor(t,e){super(),this.initialCondition=t,this.branches=e,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{const t=new L;this.initialCondition&&t.AddContent(this.initialCondition.runtimeObject);for(const e of this.branches){const n=e.runtimeObject;t.AddContent(n)}return null===this.initialCondition||null===this.branches[0].ownExpression||this.branches[this.branches.length-1].isElse||t.AddContent(D.PopEvaluatedValue()),this._reJoinTarget=D.NoOp(),t.AddContent(this._reJoinTarget),t},this.initialCondition&&this.AddContent(this.initialCondition),null!==this.branches&&this.AddContent(this.branches)}get typeName(){return"Conditional"}ResolveReferences(t){const e=this._reJoinTarget.path;for(const t of this.branches){if(!t.returnDivert)throw new Error;t.returnDivert.targetPath=e}super.ResolveReferences(t)}}class rt extends d{constructor(t){super(),this.text=t,this.GenerateRuntimeObject=()=>new I(this.text),this.toString=()=>this.text}get typeName(){return"Text"}}class st extends d{get constantName(){var t;return null===(t=this.constantIdentifier)||void 0===t?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,z.Var)}}var at;!function(t){t[t.Story=0]="Story",t[t.Knot=1]="Knot",t[t.Stitch=2]="Stitch",t[t.WeavePoint=3]="WeavePoint"}(at||(at={}));class ot extends d{get name(){var t;return(null===(t=this.identifier)||void 0===t?void 0:t.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(t,e){super(),this.indentationDepth=e,this.GenerateRuntimeObject=()=>{const t=new L;if(t.name=this.name,this.story.countAllVisits&&(t.visitsShouldBeCounted=!0),t.countingAtStartOnly=!0,this.content)for(const e of this.content)t.AddContent(e.runtimeObject);return t},this.toString=()=>{var t,e;return"- "+((null===(t=this.identifier)||void 0===t?void 0:t.name)?"("+(null===(e=this.identifier)||void 0===e?void 0:e.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,z.SubFlowAndWeave)}}class lt{get baseTargetLevel(){return this.baseLevelIsAmbiguous?at.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return!this._baseTargetLevel}get firstComponent(){return null!=this.components&&this.components.length?this.components[0].name:null}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return null==this._dotSeparatedComponents&&(this._dotSeparatedComponents=(this.components?this.components:[]).map((t=>t.name)).filter(c).join(".")),this._dotSeparatedComponents}constructor(t,e){this._dotSeparatedComponents=null,this.toString=()=>null===this.components||0===this.components.length?this.baseTargetLevel===at.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=t=>{if(null==this.components||0==this.components.length)return null;let e=this.ResolveBaseTarget(t);return null===e?null:this.components.length>1?this.ResolveTailComponents(e):e},this.ResolveBaseTarget=t=>{const e=this.firstComponent;let n=t;for(;n;){const i=n===t,r=this.GetChildFromContext(n,e,null,i);if(r)return r;n=n.parent}return null},this.ResolveTailComponents=t=>{let e=t;if(!this.components)return null;for(let t=1;t<this.components.length;++t){const n=this.components[t].name;let i,r=s(e,dt);if(i=null!==r?r.flowLevel+1:at.WeavePoint,e=this.GetChildFromContext(e,n,i),null===e)break}return e},this.GetChildFromContext=function(t,e,n){let i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const r=null===n,a=s(t,Pt);if(e&&null!==a&&(r||n===at.WeavePoint))return a.WeavePointNamed(e);let o=s(t,dt);if(e&&null!==o){const t=i||o.flowLevel===at.Knot;return o.ContentWithNameAtLevel(e,n,t)}return null},Object.values(at).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"}}class ht extends d{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{const t=new L;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(D.EvalStart()),t.AddContent(new j),t.AddContent(D.EvalEnd())),t.AddContent(D.PopFunction()),t},t&&(this.returnedExpression=this.AddContent(t))}get typeName(){return"ReturnType"}}function ut(t){let e=t.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent}return null}class ct{constructor(t){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=t}get typeName(){return"Identifier"}static Done(){return new ct("DONE")}}class dt extends d{get hasParameters(){return null!==this.args&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var t;return(null===(t=this.identifier)||void 0===t?void 0:t.name)||null}constructor(t){var e;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];super(),e=this,this.isFunction=r,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>!0,this.SplitWeaveAndSubFlowContent=(t,e)=>{var n,i;const r=[],a=[];this._subFlowsByName=new Map;for(const e of t){const t=s(e,dt);t?(null===this._firstChildFlow&&(this._firstChildFlow=t),a.push(e),(null===(n=t.identifier)||void 0===n?void 0:n.name)&&this._subFlowsByName.set(null===(i=t.identifier)||void 0===i?void 0:i.name,t)):r.push(e)}e&&r.push(new ot(null,1),new St(new lt(ct.Done())));const o=[];return r.length>0&&(this._rootWeave=new Pt(r,0),o.push(this._rootWeave)),a.length>0&&o.push(...a),o},this.ResolveVariableWithName=(t,e)=>{var n;const i={},r=null===e?this:ut(e);if(r){if(null!==r.args)for(const e of r.args)if((null===(n=e.identifier)||void 0===n?void 0:n.name)===t)return i.found=!0,i.isArgument=!0,i.ownerFlow=r,i;if(r!==this.story&&r.variableDeclarations.has(t))return i.found=!0,i.ownerFlow=r,i.isTemporary=!0,i}return this.story.variableDeclarations.has(t)?(i.found=!0,i.ownerFlow=this.story,i.isGlobal=!0,i):(i.found=!1,i)},this.AddNewVariableDeclaration=t=>{const e=t.variableName;if(this.variableDeclarations.has(e)){const n=this.variableDeclarations.get(e);let i="";return n.debugMetadata&&(i=` (${n.debugMetadata})`),void this.Error(`found declaration variable '${e}' that was already declared${i}`,t,!1)}this.variableDeclarations.set(t.variableName,t)},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(const[,t]of this._subFlowsByName)t.hasOwnProperty("ResolveWeavePointNaming")&&t.ResolveWeavePointNaming()},this.GenerateRuntimeObject=()=>{var t;let e=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():this.flowLevel!==at.Knot&&this.flowLevel!==at.Stitch||(e=this.Find(ht)(),null!==e&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,e));const n=new L;n.name=null===(t=this.identifier)||void 0===t?void 0:t.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=!0),this.GenerateArgumentVariableAssignments(n);let i=0;for(;null!==this.content&&i<this.content.length;){const t=this.content[i];if(t instanceof dt){const e=t,r=e.runtimeObject;0!==i||e.hasParameters||this.flowLevel!==at.Knot||(this._startingSubFlowDivert=new J,n.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=r);const s=r,a=n.namedContent.get(s.name)||null;if(a){const t=`${this.GetType()} already contains flow named '${s.name}' (at ${a.debugMetadata})`;this.Error(t,e)}n.AddToNamedContentOnly(s)}else t&&n.AddContent(t.runtimeObject);i+=1}return this.flowLevel===at.Story||this.isFunction||null===this._rootWeave||null!==e||this._rootWeave.ValidateTermination(this.WarningInTermination),n},this.GenerateArgumentVariableAssignments=t=>{var e;if(null!==this.args&&0!==this.args.length)for(let n=this.args.length-1;n>=0;--n){const i=(null===(e=this.args[n].identifier)||void 0===e?void 0:e.name)||null,r=new X(i,!0);t.AddContent(r)}},this.ContentWithNameAtLevel=function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];var r;if((n===e.flowLevel||null===n)&&t===(null===(r=e.identifier)||void 0===r?void 0:r.name))return e;if(n===at.WeavePoint||null===n){let r=null;if(e._rootWeave&&(r=e._rootWeave.WeavePointNamed(t),r))return r;if(n===at.WeavePoint)return i?e.DeepSearchForAnyLevelContent(t):null}if(null!==n&&n<e.flowLevel)return null;let s=e._subFlowsByName.get(t)||null;return!s||null!==n&&n!==s.flowLevel?i?e.DeepSearchForAnyLevelContent(t):null:s},this.DeepSearchForAnyLevelContent=t=>{const e=this.ContentWithNameAtLevel(t,at.WeavePoint,!1);if(e)return e;for(const[,e]of this._subFlowsByName){const n=e.ContentWithNameAtLevel(t,null,!0);if(n)return n}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==at.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(const[t,e]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${t}' within the function '${this.identifier}'`,e);if(!this._rootWeave)throw new Error;const t=this._rootWeave.FindAll(St)();for(const e of t)e.isFunctionCall||e.parent instanceof Ct||this.Error(`Functions may not contain diverts, but saw '${e}'`,e);const e=this._rootWeave.FindAll(Y)();for(const t of e)this.Error(`Functions may not contain choices, but saw '${t}'`,t)},this.WarningInTermination=t=>{let e="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";t.parent===this._rootWeave&&this._firstChildFlow&&(e=`${e} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);const n=s(t,St);n&&n.isTunnel&&(e+=` When final tunnel to '${n.target} ->' returns it won't have anywhere to go.`),this.Warning(e,t)},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=t,this.args=i,null===n&&(n=[]),this.PreProcessTopLevelObjects(n),n=this.SplitWeaveAndSubFlowContent(n,"Story"==this.GetType()&&!a),this.AddContent(n)}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),null!==this.args){for(const e of this.args)t.CheckForNamingCollisions(this,e.identifier,z.Arg,"argument");for(let t=0;t<this.args.length;t+=1)for(let i=t+1;i<this.args.length;i+=1)(null===(e=this.args[t].identifier)||void 0===e?void 0:e.name)==(null===(n=this.args[i].identifier)||void 0===n?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[t].identifier}'`)}if(this.flowLevel!==at.Story){const e=this.flowLevel===at.Knot?z.Knot:z.SubFlowAndWeave;t.CheckForNamingCollisions(this,this.identifier,e)}}}class pt extends d{get runtimeContainer(){return this.runtimeObject}constructor(t){super(),this.dontFlatten=!1,this.TrimTrailingWhitespace=()=>{for(let t=this.content.length-1;t>=0;--t){const e=s(this.content[t],rt);if(null===e)break;if(e.text=e.text.replace(new RegExp(/[ \t]/g),""),0!==e.text.length)break;this.content.splice(t,1)}},this.GenerateRuntimeObject=()=>{const t=new L;if(null!==this.content)for(const e of this.content){const n=e.runtimeObject;n&&t.AddContent(n)}return this.dontFlatten&&this.story.DontFlattenContainer(t),t},this.toString=()=>`ContentList(${this.content.join(", ")})`,t&&this.AddContent(t);for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];n&&this.AddContent(n)}get typeName(){return"ContentList"}}let mt=class extends y{get containerForCount(){return null===this.pathForCount?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return null===this.pathForCount?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(t){this.pathForCount=null===t?null:new m(t)}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;super(),this.pathForCount=null,this.name=t}toString(){if(null!=this.name)return"var("+this.name+")";return"read_count("+this.pathStringForCount+")"}};class ft extends V{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map((t=>t.name)).filter(c)}get identifier(){if(!this.pathIdentifiers||0==this.pathIdentifiers.length)return null;const t=this.path.join(".");return new ct(t)}get runtimeVarRef(){return this._runtimeVarRef}constructor(t){super(),this.pathIdentifiers=t,this._runtimeVarRef=null,this.isConstantReference=!1,this.isListItemReference=!1,this.GenerateIntoContainer=t=>{let e=this.story.constants.get(this.name);if(e)return e.GenerateConstantIntoContainer(t),void(this.isConstantReference=!0);if(this._runtimeVarRef=new mt(this.name),1===this.path.length||2===this.path.length){let t="",e="";1===this.path.length?t=this.path[0]:(e=this.path[0],t=this.path[1]);this.story.ResolveListItem(e,t,this)&&(this.isListItemReference=!0)}t.AddContent(this._runtimeVarRef)},this.toString=()=>`{${this.path.join(".")}}`}get typeName(){return"ref"}ResolveReferences(t){if(super.ResolveReferences(t),this.isConstantReference||this.isListItemReference)return;const e=new lt(this.pathIdentifiers),n=e.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=!0,null===this._runtimeVarRef)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let t=s(n,dt);t&&t.isFunction&&(this.parent instanceof Pt||this.parent instanceof pt||this.parent instanceof dt)&&this.Warning(`'${t.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${t.identifier}()`)}else{if(this.path.length>1){let t=`Could not find target for read count: ${e}`;return this.path.length<=2&&(t+=`, or couldn't find list item with the name ${this.path.join(",")}`),void this.Error(t)}t.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this)}}}class gt extends V{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"CHOICE_COUNT"===this.name}get isTurns(){return"TURNS"===this.name}get isTurnsSince(){return"TURNS_SINCE"===this.name}get isRandom(){return"RANDOM"===this.name}get isSeedRandom(){return"SEED_RANDOM"===this.name}get isListRange(){return"LIST_RANGE"===this.name}get isListRandom(){return"LIST_RANDOM"===this.name}get isReadCount(){return"READ_COUNT"===this.name}constructor(t,e){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=!1,this.GenerateIntoContainer=t=>{const e=this.story.ResolveList(this.name);let n=!1;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),t.AddContent(D.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),t.AddContent(D.Turns());else if(this.isTurnsSince||this.isReadCount){const e=s(this.args[0],Ct),n=s(this.args[0],ft);if(1!==this.args.length||null===e&&null===n)return void 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)`);e?(this._divertTargetToCount=e,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(t)):n&&(this._variableReferenceToCount=n,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(t)),this.isTurnsSince?t.AddContent(D.TurnsSince()):t.AddContent(D.ReadCount())}else if(this.isRandom){2!==this.args.length&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let e=0;e<this.args.length;e+=1){const n=s(this.args[e],M);if(n&&!n.isInt()){const t=0===e?"minimum":"maximum";this.Error(`RANDOM's ${t} parameter should be an integer`)}this.args[e].GenerateIntoContainer(t)}t.AddContent(D.Random())}else if(this.isSeedRandom){1!==this.args.length&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");const e=s(this.args[0],M);e&&!e.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(t),t.AddContent(D.SeedRandom())}else if(this.isListRange){3!==this.args.length&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let e=0;e<this.args.length;e+=1)this.args[e].GenerateIntoContainer(t);t.AddContent(D.ListRange())}else if(this.isListRandom)1!==this.args.length&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(t),t.AddContent(D.ListRandom());else if(B.CallExistsWithName(this.name)){const e=B.CallWithName(this.name);if(e.numberOfParameters!==this.args.length){let t=`${gt.name} should take ${e.numberOfParameters} parameter`;e.numberOfParameters>1&&(t+="s"),this.Error(t)}for(let e=0;e<this.args.length;e+=1)this.args[e].GenerateIntoContainer(t);t.AddContent(B.CallWithName(this.name))}else if(null!==e)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)"),1===this.args.length)t.AddContent(new I(this.name)),this.args[0].GenerateIntoContainer(t),t.AddContent(D.ListFromInt());else{const e=new E;e.SetInitialOriginName(this.name),t.AddContent(new R(e))}else t.AddContent(this._proxyDivert.runtimeObject),n=!0;n||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&t.AddContent(D.PopEvaluatedValue())},this.toString=()=>{const t=this.args.join(", ");return`${this.name}(${t})`},this._proxyDivert=new St(new lt(t),e),this._proxyDivert.isFunctionCall=!0,this.AddContent(this._proxyDivert)}get typeName(){return"FunctionCall"}ResolveReferences(t){if(super.ResolveReferences(t),!this.content.includes(this._proxyDivert)&&null!==this.args)for(const e of this.args)e.ResolveReferences(t);if(this._divertTargetToCount){const t=this._divertTargetToCount.divert,e=null!=t.runtimeDivert.variableDivertName;if(e)return void this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);const n=t.targetContent;if(null===n)e||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else{if(!n.containerForCounting)throw new Error;n.containerForCounting.turnIndexShouldBeCounted=!0}}else if(this._variableReferenceToCount){const t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;null!==t.pathForCount&&this.Error(`Should be '${gt.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`)}}}gt.IsBuiltIn=t=>!!B.CallExistsWithName(t)||("CHOICE_COUNT"===t||"TURNS_SINCE"===t||"TURNS"===t||"RANDOM"===t||"SEED_RANDOM"===t||"LIST_VALUE"===t||"LIST_RANDOM"===t||"READ_COUNT"===t);class vt extends V{get subExpressions(){return this.content}constructor(t){super(),this.GenerateIntoContainer=t=>{let e=!0;for(const n of this.subExpressions)n.GenerateIntoContainer(t),e||t.AddContent(B.CallWithName("&&")),e=!1},this.AddContent(t)}get typeName(){return"MultipleConditionExpression"}}class Ct extends V{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=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new F,t.AddContent(this.runtimeDivertTargetValue)},this.Equals=t=>{const e=s(t,Ct);if(!e||!this.divert.target||!e.divert.target)return!1;return this.divert.target.dotSeparatedComponents===e.divert.target.dotSeparatedComponents},this.divert=this.AddContent(t)}get typeName(){return"DivertTarget"}ResolveReferences(t){if(super.ResolveReferences(t),this.divert.isDone||this.divert.isEnd)return void this.Error("Can't use -> DONE or -> END as variable divert targets",this);let e=this;for(;e&&e instanceof V;){let t=!1,n=!1;const i=e.parent;if(i instanceof $){const e=i;"=="!==e.opName&&"!="!==e.opName?t=!0:(e.leftExpression instanceof Ct||e.leftExpression instanceof ft)&&(e.rightExpression instanceof Ct||e.rightExpression instanceof ft)||(t=!0),n=!0}else if(i instanceof gt){const e=i;e.isTurnsSince||e.isReadCount||(t=!0),n=!0}else(i instanceof V||i instanceof vt||i instanceof Y&&i.condition===e||i instanceof it||i instanceof Nt)&&(t=!0,n=!0);if(t&&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),n)break;e=i}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(null!==n){let t=n.containerForCounting;if(null!==t){const e=s(this.parent,gt);e&&e.isTurnsSince||(t.visitsShouldBeCounted=!0),t.turnIndexShouldBeCounted=!0}let e=s(n,dt);if(null!=e&&null!==e.args)for(const t of e.args)t.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${e.identifier}' has 'ref ${t.identifier}').`)}}}class St extends d{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(t){this._runtimeDivert=t}get isEnd(){return Boolean(this.target&&"END"===this.target.dotSeparatedComponents)}get isDone(){return Boolean(this.target&&"DONE"===this.target.dotSeparatedComponents)}constructor(t,e){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=!1,this.isEmpty=!1,this.isTunnel=!1,this.isThread=!1,this.GenerateRuntimeObject=()=>{if(this.isEnd)return D.End();if(this.isDone)return D.Done();this.runtimeDivert=new J,this.ResolveTargetContent(),this.CheckArgumentValidity();const t=null!==this.args&&this.args.length>0;if(t||this.isFunctionCall||this.isTunnel||this.isThread){const e=new L;if(t){this.isFunctionCall||e.AddContent(D.EvalStart());let t=null;this.targetContent&&(t=this.targetContent.args);for(let n=0;n<this.args.length;++n){const i=this.args[n];let r=null;if(t&&n<t.length&&(r=t[n]),r&&r.isByReference){const t=s(i,ft);if(!t){this.Error(`Expected variable name to pass by reference to 'ref ${r.identifier}' but saw ${i}`);break}const n=new lt(t.pathIdentifiers);if(n.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${n.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}const a=new W(t.name);e.AddContent(a)}else i.GenerateIntoContainer(e)}this.isFunctionCall||e.AddContent(D.EvalEnd())}return this.isThread?e.AddContent(D.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=!0,this.runtimeDivert.stackPushType=this.isFunctionCall?v.Function:v.Tunnel),e.AddContent(this.runtimeDivert),e}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!this.isEmpty&&!this.isEnd&&null===this.targetContent){let t=this.PathAsVariableName();if(null!==t){const e=s(ut(this),dt);if(e){const n=e.ResolveVariableWithName(t,this);if(n.found){if(n.isArgument&&n.ownerFlow&&n.ownerFlow.args){let e=n.ownerFlow.args.find((e=>{var n;return(null===(n=e.identifier)||void 0===n?void 0:n.name)==t}));e&&!e.isDivertTarget&&this.Error(`Since '${e.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${e.identifier}`,n.ownerFlow)}return void(this.runtimeDivert.variableDivertName=t)}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this)}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let t=0;if(null!==this.args&&this.args.length>0&&(t=this.args.length),null===this.targetContent)return;const e=s(this.targetContent,dt);if(!(0!==t||null!==e&&e.hasParameters))return;if(null===e&&t>0)return void this.Error("target needs to be a knot or stitch in order to pass arguments");if(null!==e&&(null===e.args||!e.args&&t>0))return void this.Error(`target (${e.name}) doesn't take parameters`);if(this.parent instanceof Ct)return void(t>0&&this.Error("can't store arguments in a divert target variable"));const n=e.args.length;if(n!==t){let i;return i=0===t?"but there weren't any passed to it":t<n?`but only got ${t}`:`but got ${t}`,void this.Error(`to '${e.identifier}' requires ${n} arguments, ${i}`)}for(let t=0;t<n;++t){const n=e.args[t],i=this.args[t];if(n.isDivertTarget){let t=s(i,ft);if(i instanceof Ct||null!==t){if(t){const e=new lt(t.pathIdentifiers);e.ResolveFromContext(t)&&this.Error(`Passing read count of '${e.dotSeparatedComponents}' instead of a divert target. You probably meant '${e}'`)}}else this.Error(`Target '${e.identifier}' expects a divert target for the parameter named -> ${n.identifier} but saw ${i}`,i)}}null!==e||this.Error("Can't call as a function or with arguments unless it's a knot or stitch")},this.CheckExternalArgumentValidity=t=>{const e=this.target?this.target.firstComponent:null,n=t.externals.get(e);if(!n)throw new Error("external not found");const i=n.argumentNames.length;let r=0;this.args&&(r=this.args.length),r!==i&&this.Error(`incorrect number of arguments sent to external function '${e}'. Expected ${i} but got ${r}`)},this.toString=()=>{let t="";return null===this.target?"-> <empty divert>":(t+=this.target.toString(),this.isTunnel&&(t+=" ->"),this.isFunctionCall&&(t+=" ()"),t)},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=s(this.targetContent,dt);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 Ct||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+"(...)'"));const n=null!==this.targetContent;let i=!1,r=!1;if(!this.target)throw new Error;if(1===this.target.numberOfComponents){if(!this.target.firstComponent)throw new Error;if(i=gt.IsBuiltIn(this.target.firstComponent),r=t.IsExternal(this.target.firstComponent),i||r)return this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),void(r&&(this.runtimeDivert.isExternal=!0,null!==this.args&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=!1,this.runtimeDivert.targetPath=new m(this.target.firstComponent),this.CheckExternalArgumentValidity(t)))}null==this.runtimeDivert.variableDivertName&&(n||i||r||this.Error(`target not found: '${this.target}'`))}Error(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];e!==this&&e?super.Error(t,e):this.isFunctionCall?super.Error(`Function call ${t}`,e,n):super.Error(`Divert ${t}`,e,n)}}class yt{constructor(t,e){this.divert=t,this.targetRuntimeObj=e}}class bt{constructor(t,e){this.divert=t,this.targetContent=e}}var wt;!function(t){t[t.Stopping=1]="Stopping",t[t.Cycle=2]="Cycle",t[t.Shuffle=4]="Shuffle",t[t.Once=8]="Once"}(wt||(wt={}));class Et extends d{constructor(t,e){super(),this.sequenceType=e,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{const t=new L;t.visitsShouldBeCounted=!0,t.countingAtStartOnly=!0,this._sequenceDivertsToResolve=[],t.AddContent(D.EvalStart()),t.AddContent(D.VisitIndex());const e=(this.sequenceType&wt.Once)>0,n=(this.sequenceType&wt.Cycle)>0,i=(this.sequenceType&wt.Stopping)>0,r=(this.sequenceType&wt.Shuffle)>0;let s=this.sequenceElements.length;if(e&&(s+=1),i||e?(t.AddContent(new N(s-1)),t.AddContent(B.CallWithName("MIN"))):n&&(t.AddContent(new N(this.sequenceElements.length)),t.AddContent(B.CallWithName("%"))),r){const n=D.NoOp();if(e||i){const e=i?this.sequenceElements.length-1:this.sequenceElements.length;t.AddContent(D.Duplicate()),t.AddContent(new N(e)),t.AddContent(B.CallWithName("=="));const r=new J;r.isConditional=!0,t.AddContent(r),this.AddDivertToResolve(r,n)}let r=this.sequenceElements.length;i&&(r-=1),t.AddContent(new N(r)),t.AddContent(D.SequenceShuffleIndex()),(e||i)&&t.AddContent(n)}t.AddContent(D.EvalEnd());const a=D.NoOp();for(let e=0;e<s;e+=1){t.AddContent(D.EvalStart()),t.AddContent(D.Duplicate()),t.AddContent(new N(e)),t.AddContent(B.CallWithName("==")),t.AddContent(D.EvalEnd());const n=new J;let i;if(n.isConditional=!0,t.AddContent(n),e<this.sequenceElements.length){i=this.sequenceElements[e].runtimeObject}else i=new L;i.name=`s${e}`,i.InsertContent(D.PopEvaluatedValue(),0);const r=new J;i.AddContent(r),t.AddToNamedContentOnly(i),this.AddDivertToResolve(n,i),this.AddDivertToResolve(r,a)}return t.AddContent(a),t},this.AddDivertToResolve=(t,e)=>{this._sequenceDivertsToResolve.push(new bt(t,e))},this.sequenceType=e,this.sequenceElements=[];for(const e of t){const t=e.content;let n=null;n=null===t||0===t.length?e:new Pt(t),this.sequenceElements.push(n),this.AddContent(n)}}get typeName(){return"Sequence"}ResolveReferences(t){super.ResolveReferences(t);for(const t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path}}class _t extends d{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{const t=new L;if(t.AddContent(D.EvalStart()),this.divertAfter){const e=this.divertAfter.GenerateRuntimeObject(),n=e;if(n){const e=this.divertAfter.args;if(null!==e&&e.length>0){let e=-1,i=-1;for(let t=0;t<n.content.length;t+=1){const r=n.content[t];r&&(-1==e&&r.commandType===D.CommandType.EvalStart?e=t:r.commandType===D.CommandType.EvalEnd&&(i=t))}for(let r=e+1;r<i;r+=1){n.content[r].parent=null,t.AddContent(n.content[r])}}}let i=s(e,J);if(null!=i&&i.hasVariableTarget){let e=new mt(i.variableDivertName);t.AddContent(e)}else this._overrideDivertTarget=new F,t.AddContent(this._overrideDivertTarget)}else t.AddContent(new j);return t.AddContent(D.EvalEnd()),t.AddContent(D.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)}}let Tt=class{constructor(t,e){this._name=t||"",this._items=null,this._itemNameToValues=e||new Map}get name(){return this._name}get items(){if(null==this._items){this._items=new Map;for(let[t,e]of this._itemNameToValues){let n=new w(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 void 0!==e?e:0}ContainsItem(t){return!!t.itemName&&(t.originName==this.name&&this._itemNameToValues.has(t.itemName))}ContainsItemWithName(t){return this._itemNameToValues.has(t)}TryGetItemWithValue(t,e){for(let[e,n]of this._itemNameToValues)if(n==t)return{result:new w(this.name,e),exists:!0};return{result:w.Null,exists:!1}}TryGetValueForItem(t,e){if(!t.itemName)return{result:0,exists:!1};let n=this._itemNameToValues.get(t.itemName);return n?{result:n,exists:!0}:{result:0,exists:!1}}};class xt extends d{get typeName(){return"ListDefinition"}get runtimeListDefinition(){var t;const e=new Map;for(const t of this.itemDefinitions)e.has(t.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${t.name}'`):e.set(t.name,t.seriesValue);return new Tt((null===(t=this.identifier)||void 0===t?void 0:t.name)||"",e)}constructor(t){super(),this.itemDefinitions=t,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=t=>{if(null===this._elementsByName){this._elementsByName=new Map;for(const t of this.itemDefinitions)this._elementsByName.set(t.name,t)}return this._elementsByName.get(t)||null},this.GenerateRuntimeObject=()=>{var t,e;const n=new E;for(const e of this.itemDefinitions)if(e.inInitialList){const i=new w((null===(t=this.identifier)||void 0===t?void 0:t.name)||null,e.name||null);n.Add(i,e.seriesValue)}return n.SetInitialOriginName((null===(e=this.identifier)||void 0===e?void 0:e.name)||""),new R(n)};let e=1;for(const t of this.itemDefinitions)null!==t.explicitValue&&(e=t.explicitValue),t.seriesValue=e,e+=1;this.AddContent(t)}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.identifier,z.List)}}class At extends d{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?null!==this.listDefinition?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor(t){let{assignedExpression:e,isGlobalDeclaration:n,isTemporaryNewDeclaration:i,listDef:r,variableIdentifier:s}=t;super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let t=null;if(this.isGlobalDeclaration?t=this.story:this.isNewTemporaryDeclaration&&(t=ut(this)),t&&t.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;const e=new L;return this.expression?e.AddContent(this.expression.runtimeObject):this.listDefinition&&e.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new X(this.variableName,this.isNewTemporaryDeclaration),e.AddContent(this._runtimeAssignment),e},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=s,this.isGlobalDeclaration=Boolean(n),this.isNewTemporaryDeclaration=Boolean(i),r instanceof xt?(this.listDefinition=this.AddContent(r),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=!0):e&&(this.expression=this.AddContent(e))}ResolveReferences(t){if(super.ResolveReferences(t),this.isDeclaration&&null===this.listDefinition&&t.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?z.Var:z.Temp),this.isGlobalDeclaration){const t=s(this.expression,ft);!t||t.isConstantReference||t.isListItemReference||this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items")}if(!this.isNewTemporaryDeclaration){const 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)}}}class Pt extends d{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(0===this.content.length)return null;let t=null;for(let e=this.content.length-1;e>=0;--e){t=this.content[e];let n=s(t,rt);if((!n||"\n"!==n.text)&&!this.IsGlobalDeclaration(t))break}const e=s(t,Pt);return e&&(t=e.lastParsedSignificantObject),t}constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=!1,this.hasSeenChoiceInSection=!1,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var t,e,n;const i=[...this.FindAll(ot)((t=>!(null===t.name||void 0===t.name))),...this.FindAll(Y)((t=>!(null===t.name||void 0===t.name)))];this._namedWeavePoints=new Map;for(const r of i){const i=this.namedWeavePoints.get((null===(t=r.identifier)||void 0===t?void 0:t.name)||"");if(i){const t=i instanceof ot?"gather":"choice",e=i;this.Error(`A ${t} with the same label name '${r.name}' already exists in this context on line ${e.debugMetadata?e.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,r)}(null===(e=r.identifier)||void 0===e?void 0:e.name)&&this.namedWeavePoints.set(null===(n=r.identifier)||void 0===n?void 0:n.name,r)}},this.ConstructWeaveHierarchyFromIndentation=()=>{let t=0;for(;t<this.content.length;){const e=this.content[t];if(e instanceof Y||e instanceof ot){const n=e.indentationDepth-1;if(n>this.baseIndentIndex){let e=t;for(;t<this.content.length;){const e=s(this.content[t],Y)||s(this.content[t],ot);if(null!==e){if(e.indentationDepth-1<=this.baseIndentIndex)break}t+=1}const i=t-e,r=this.content.slice(e,e+i);this.content.splice(e,i);const a=new Pt(r,n);this.InsertContent(e,a),t=e}}t+=1}},this.DetermineBaseIndentationFromContent=t=>{for(const e of t)if(e instanceof Y||e instanceof ot)return e.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new L,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(const t of this.content)if(t instanceof Y||t instanceof ot)this.AddRuntimeForWeavePoint(t);else if(t instanceof Pt){const e=t;this.AddRuntimeForNestedWeave(e),this.gatherPointsToResolve.splice(0,0,...e.gatherPointsToResolve)}else this.AddGeneralRuntimeContent(t.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=t=>{const e=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=!1;const n=t.runtimeContainer;if(t.name||(n.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),e){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n)}else this.rootContainer.AddToNamedContentOnly(n);for(const e of this.looseEnds){const i=e;if(i instanceof ot){if(i.indentationDepth==t.indentationDepth)continue}let r=null;if(i instanceof St)r=i.runtimeObject;else{r=new J;const t=i;if(!t.runtimeContainer)throw new Error;t.runtimeContainer.AddContent(r)}this.gatherPointsToResolve.push(new yt(r,n))}this.looseEnds=[],this.currentContainer=n},this.AddRuntimeForWeavePoint=t=>{if(t instanceof ot)this.AddRuntimeForGather(t);else if(t instanceof Y){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof ot&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);const e=t;if(this.currentContainer.AddContent(e.runtimeObject),!e.innerContentContainer)throw new Error;e.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(e.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=!0}if(this.addContentToPreviousWeavePoint=!1,this.WeavePointHasLooseEnd(t)){this.looseEnds.push(t);s(t,Y)&&(this.addContentToPreviousWeavePoint=!0)}this.previousWeavePoint=t},this.AddRuntimeForNestedWeave=t=>{this.AddGeneralRuntimeContent(t.rootContainer),null!==this.previousWeavePoint&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=!1)},this.AddGeneralRuntimeContent=t=>{if(null!==t)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(t)}else{if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(t)}},this.PassLooseEndsToAncestors=()=>{if(0===this.looseEnds.length)return;let t=null,e=null,n=!1;for(let i=this.parent;null!==i;i=i.parent){const r=s(i,Pt);r&&(n||null!==t||(t=r),n&&null===e&&(e=r)),(i instanceof Et||i instanceof it)&&(n=!0)}if(null!==t||null!==e)for(let i=this.looseEnds.length-1;i>=0;i-=1){const r=this.looseEnds[i];let s=!1;if(n){if(r instanceof Y&&null!==t)t.ReceiveLooseEnd(r),s=!0;else if(!(r instanceof Y)){const n=t||e;null!==n&&(n.ReceiveLooseEnd(r),s=!0)}}else(null==t?void 0:t.hasOwnProperty("ReceiveLooseEnd"))&&t.ReceiveLooseEnd(r),s=!0;s&&this.looseEnds.splice(i,1)}},this.ReceiveLooseEnd=t=>{this.looseEnds.push(t)},this.WeavePointNamed=t=>{if(!this.namedWeavePoints)return null;let e=this.namedWeavePoints.get(t);return e||null},this.IsGlobalDeclaration=t=>{const e=s(t,At);if(e&&e.isGlobalDeclaration&&e.isDeclaration)return!0;return!!s(t,st)},this.ContentThatFollowsWeavePoint=t=>{const e=[],n=t;if(null!==n.content)for(const t of n.content)this.IsGlobalDeclaration(t)||e.push(t);const i=s(n.parent,Pt);if(null===i)throw new Error("Expected weave point parent to be weave?");for(let t=i.content.indexOf(n)+1;t<i.content.length;t+=1){const n=i.content[t];if(!this.IsGlobalDeclaration(n)){if(n instanceof Y||n instanceof ot)break;if(n instanceof Pt)break;e.push(n)}}return e},this.ValidateTermination=t=>{if(this.lastParsedSignificantObject instanceof p)return;if(null!==this.looseEnds&&this.looseEnds.length>0)for(const e of this.looseEnds){const n=this.ContentThatFollowsWeavePoint(e);this.ValidateFlowOfObjectsTerminates(n,e,t)}else{for(const t of this.content)if(t instanceof Y||t instanceof St)return;this.ValidateFlowOfObjectsTerminates(this.content,this,t)}},this.BadNestedTerminationHandler=t=>{let e=null;for(let n=t.parent;null!==n;n=n.parent)if(n instanceof Et||n instanceof it){e=s(n,it);break}let n="Choices nested in conditionals or sequences need to explicitly divert afterwards.";if(null!==e){1===e.FindAll(Y)().length&&(n=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${n.toLowerCase()}`)}this.Error(n,t)},this.ValidateFlowOfObjectsTerminates=(t,e,n)=>{let i=!1,r=e;for(const e of t){if(null!==e.Find(St)((t=>!(t.isThread||t.isTunnel||t.isFunctionCall||t.parent instanceof Ct)))&&(i=!0),null!=e.Find(_t)()){i=!0;break}r=e}if(!i){if(r instanceof p)return;n(r)}},this.WeavePointHasLooseEnd=t=>{if(null===t.content)return!0;for(let e=t.content.length-1;e>=0;--e){let n=s(t.content[e],St);if(n){if(!(n.isThread||n.isTunnel||n.isFunctionCall))return!1}}return!0},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;const t=[];for(const e of this.ancestry){const n=s(e,dt);if(!n)break;t.push(n)}for(const[e,n]of this.namedWeavePoints)for(const i of t){const t=i.ContentWithNameAtLevel(e);if(t&&t!==n){const i=`${n.GetType()} '${e}' has the same label name as a ${t.GetType()} (on ${t.debugMetadata})`;this.Error(i,n)}}},this.baseIndentIndex=-1==e?this.DetermineBaseIndentationFromContent(t):e,this.AddContent(t),this.ConstructWeaveHierarchyFromIndentation()}get typeName(){return"Weave"}ResolveReferences(t){if(super.ResolveReferences(t),null!==this.looseEnds&&this.looseEnds.length>0){let t=!1;for(let e=this.parent;null!==e;e=e.parent)if(e instanceof Et||e instanceof it){t=!0;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler)}for(const t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions()}}class Nt extends d{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=!1,this.matchingEquality=!1,this.isElse=!1,this.isInline=!1,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(const t of this._innerWeave.content){const e=s(t,rt);e&&e.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",e)}const t=new L,e=this.matchingEquality&&!this.isElse;if(e&&t.AddContent(D.Duplicate()),this._conditionalDivert=new J,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){const e=null!==this.ownExpression;e&&t.AddContent(D.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(B.CallWithName("==")),e&&t.AddContent(D.EvalEnd())}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new I("\n"),0),(e||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(D.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new J,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>null===this._innerWeave?new L:this._innerWeave.rootContainer,t&&(this._innerWeave=new Pt(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)}}var Ot;!function(t){t[t.ParsingString=1]="ParsingString",t[t.TagActive=2]="TagActive"}(Ot||(Ot={}));class It{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null}Merge(t){let e=new It;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 null!==this.fileName?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}}class Ft extends d{get name(){var t;return(null===(t=this.identifier)||void 0===t?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 ${null===(t=this.identifier)||void 0===t?void 0:t.name}`}}class Wt{constructor(t,e,n){this.name=t,this.args=e,this.isFunction=n}}class Rt extends d{constructor(t){super(),this._objToWrap=t,this.GenerateRuntimeObject=()=>this._objToWrap}}let kt=class extends Rt{constructor(t){super(t)}get typeName(){return"Glue"}};class Lt extends y{toString(){return"Glue"}}class Dt extends V{constructor(t,e,n){super(),this.varIdentifier=t,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=t=>{var e,n;t.AddContent(new mt((null===(e=this.varIdentifier)||void 0===e?void 0:e.name)||null)),this.expression?this.expression.GenerateIntoContainer(t):t.AddContent(new N(1)),t.AddContent(B.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new X((null===(n=this.varIdentifier)||void 0===n?void 0:n.name)||null,!1),t.AddContent(this._runtimeAssignment)},this.toString=()=>{var t,e;return this.expression?`${null===(t=this.varIdentifier)||void 0===t?void 0:t.name}${this.isInc?" += ":" -= "}${this.expression}`:`${null===(e=this.varIdentifier)||void 0===e?void 0:e.name}`+(this.isInc?"++":"--")},e instanceof V?(this.expression=e,this.AddContent(this.expression),this.isInc=Boolean(n)):this.isInc=e}get typeName(){return"IncDecExpression"}ResolveReferences(t){var e;super.ResolveReferences(t);const n=t.ResolveVariableWithName((null===(e=this.varIdentifier)||void 0===e?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 Pt||this.parent instanceof dt||this.parent instanceof pt||this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`)}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}}class Vt extends d{constructor(t){super(),this.includedStory=t,this.GenerateRuntimeObject=()=>null}get typeName(){return"IncludedFile"}}class jt{constructor(t,e,n){this.type=t,this.precedence=e,this.requireWhitespace=n,this.toString=()=>this.type}}class Bt extends dt{get flowLevel(){return at.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(const t in this.subFlowsByName){const n=e.ContentWithNameAtLevel(t,at.Knot,!1);if(n){const e=this.subFlowsByName.get(t),i=`Stitch '${e?e.name:"NO STITCH FOUND"}' has the same name as a knot (on ${n.debugMetadata})`;this.Error(i,e)}}}}class Mt extends V{constructor(t){super(),this.itemIdentifierList=t,this.GenerateIntoContainer=t=>{var e,n;const i=new E;if(null!=this.itemIdentifierList)for(const t of this.itemIdentifierList){const r=(null===(e=null==t?void 0:t.name)||void 0===e?void 0:e.split("."))||[];let s=null,a="";r.length>1?(s=r[0],a=r[1]):a=r[0];const o=this.story.ResolveListItem(s,a,this);if(null===o)null===s?this.Error(`Could not find list definition that contains item '${t}'`):this.Error(`Could not find list item ${t}`);else{if(null==o.parent)return void this.Error(`Could not find list definition for item ${t}`);s||(s=(null===(n=o.parent.identifier)||void 0===n?void 0:n.name)||null);const e=new w(s,o.name||null);i.has(e.serialized())?this.Warning(`Duplicate of item '${t}' in list.`):i.Add(e,o.seriesValue)}}t.AddContent(new R(i))}}get typeName(){return"List"}}class Gt extends d{get fullName(){var t;const e=this.parent;if(null===e)throw new Error("Can't get full name without a parent list.");return`${null===(t=e.identifier)||void 0===t?void 0:t.name}.${this.name}`}get typeName(){return"ListElement"}get name(){var t;return(null===(t=this.indentifier)||void 0===t?void 0:t.name)||null}constructor(t,e){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]: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,z.ListItem)}}var $t;t.StatementLevel=void 0,($t=t.StatementLevel||(t.StatementLevel={}))[$t.InnerBlock=0]="InnerBlock",$t[$t.Stitch=1]="Stitch",$t[$t.Knot=2]="Knot",$t[$t.Top=3]="Top";class qt extends dt{get flowLevel(){return at.Stitch}constructor(t,e,n,i){super(t,e,n,i),this.baseToString=this.toString,this.toString=()=>`${null!==this.parent?this.parent+" > ":""}${this.baseToString()}`}get typeName(){return"Stitch"}}let Ut=class extends y{constructor(t){super(),this.text=t.toString()||""}toString(){return"# "+this.text}};class Kt extends y{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=!1,this.tags=null,this.originalThreadIndex=0}get pathStringOnChoice(){return null===this.targetPath?S("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new m(t)}}class Ht{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let e of t){this._lists.set(e.name,e);for(let[t,n]of e.items){let e=w.fromSerializedKey(t),i=new R(e,n);if(!e.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(e.itemName,i),this._allUnambiguousListValueCache.set(e.fullName,i)}}}get lists(){let t=[];for(let[,e]of this._lists)t.push(e);return t}TryListGetDefinition(t,e){if(null===t)return{result:e,exists:!1};let n=this._lists.get(t);return n?{result:n,exists:!0}:{result:e,exists:!1}}FindSingleItemListWithName(t){if(null===t)return S("name");let e=this._allUnambiguousListValueCache.get(t);return void 0!==e?e:null}}class Jt{static JArrayToRuntimeObjList(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=t.length;e&&n--;let i=[];for(let e=0;e<n;e++){let n=t[e],r=this.JTokenToRuntimeObject(n);if(null===r)return S("runtimeObj");i.push(r)}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=s(e,L);if(n)return void this.WriteRuntimeContainer(t,n);let i=s(e,J);if(i){let e,n="->";return i.isExternal?n="x()":i.pushesToStack&&(i.stackPushType==v.Function?n="f()":i.stackPushType==v.Tunnel&&(n="->t->")),e=i.hasVariableTarget?i.variableDivertName:i.targetPathString,t.WriteObjectStart(),t.WriteProperty(n,e),i.hasVariableTarget&&t.WriteProperty("var",!0),i.isConditional&&t.WriteProperty("c",!0),i.externalArgs>0&&t.WriteIntProperty("exArgs",i.externalArgs),void t.WriteObjectEnd()}let r=s(e,K);if(r)return t.WriteObjectStart(),t.WriteProperty("*",r.pathStringOnChoice),t.WriteIntProperty("flg",r.flags),void t.WriteObjectEnd();let a=s(e,P);if(a)return void t.WriteBool(a.value);let o=s(e,N);if(o)return void t.WriteInt(o.value);let l=s(e,O);if(l)return void t.WriteFloat(l.value);let h=s(e,I);if(h)return void(h.isNewline?t.Write("\n",!1):(t.WriteStringStart(),t.WriteStringInner("^"),t.WriteStringInner(h.value),t.WriteStringEnd()));let u=s(e,R);if(u)return void this.WriteInkList(t,u);let c=s(e,F);if(c)return t.WriteObjectStart(),null===c.value?S("divTargetVal.value"):(t.WriteProperty("^->",c.value.componentsString),void t.WriteObjectEnd());let d=s(e,W);if(d)return t.WriteObjectStart(),t.WriteProperty("^var",d.value),t.WriteIntProperty("ci",d.contextIndex),void t.WriteObjectEnd();if(s(e,Lt))return void t.Write("<>");let p=s(e,D);if(p)return void t.Write(Jt._controlCommandNames[p.commandType]);let m=s(e,B);if(m){let e=m.name;return"^"==e&&(e="L^"),void t.Write(e)}let f=s(e,mt);if(f){t.WriteObjectStart();let e=f.pathStringForCount;return null!=e?t.WriteProperty("CNT?",e):t.WriteProperty("VAR?",f.name),void t.WriteObjectEnd()}let g=s(e,X);if(g){t.WriteObjectStart();let e=g.isGlobal?"VAR=":"temp=";return t.WriteProperty(e,g.variableName),g.isNewDeclaration||t.WriteProperty("re",!0),void t.WriteObjectEnd()}if(s(e,j))return void t.Write("void");let C=s(e,Ut);if(C)return t.WriteObjectStart(),t.WriteProperty("#",C.text),void t.WriteObjectEnd();let y=s(e,Kt);if(!y)throw new Error("Failed to convert runtime object to Json token: "+e);this.WriteChoice(t,y)}static JObjectToDictionaryRuntimeObjs(t){let e=new Map;for(let n in t)if(t.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(t[n]);if(null===i)return S("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("number"==typeof t&&!isNaN(t)||"boolean"==typeof t)return A.Create(t);if("string"==typeof t){let e=t.toString(),n=e[0];if("^"==n)return new I(e.substring(1));if("\n"==n&&1==e.length)return new I("\n");if("<>"==e)return new Lt;for(let t=0;t<Jt._controlCommandNames.length;++t){if(e==Jt._controlCommandNames[t])return new D(t)}if("L^"==e&&(e="^"),B.CallExistsWithName(e))return B.CallWithName(e);if("->->"==e)return D.PopTunnel();if("~ret"==e)return D.PopFunction();if("void"==e)return new j}if("object"==typeof t&&!Array.isArray(t)){let e,n=t;if(n["^->"])return e=n["^->"],new F(new m(e.toString()));if(n["^var"]){e=n["^var"];let t=new W(e.toString());return"ci"in n&&(e=n.ci,t.contextIndex=parseInt(e)),t}let i=!1,r=!1,s=v.Function,a=!1;if((e=n["->"])?i=!0:(e=n["f()"])?(i=!0,r=!0,s=v.Function):(e=n["->t->"])?(i=!0,r=!0,s=v.Tunnel):(e=n["x()"])&&(i=!0,a=!0,r=!1,s=v.Function),i){let t=new J;t.pushesToStack=r,t.stackPushType=s,t.isExternal=a;let i=e.toString();return(e=n.var)?t.variableDivertName=i:t.targetPathString=i,t.isConditional=!!n.c,a&&(e=n.exArgs)&&(t.externalArgs=parseInt(e)),t}if(e=n["*"]){let t=new K;return t.pathStringOnChoice=e.toString(),(e=n.flg)&&(t.flags=parseInt(e)),t}if(e=n["VAR?"])return new mt(e.toString());if(e=n["CNT?"]){let t=new mt;return t.pathStringForCount=e.toString(),t}let o=!1,l=!1;if((e=n["VAR="])?(o=!0,l=!0):(e=n["temp="])&&(o=!0,l=!1),o){let t=e.toString(),i=!n.re,r=new X(t,i);return r.isGlobal=l,r}if(void 0!==n["#"])return e=n["#"],new Ut(e.toString());if(e=n.list){let t=e,i=new E;if(e=n.origins){let t=e;i.SetInitialOriginNames(t)}for(let e in t)if(t.hasOwnProperty(e)){let n=t[e],r=new w(e),s=parseInt(n);i.Add(r,s)}return new R(i)}if(null!=n.originalChoicePath)return this.JObjectToChoice(n)}if(Array.isArray(t))return this.JArrayToContainer(t);if(null==t)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,((t,n)=>(null==e?void 0:e.some((e=>e===t)))?void 0:n),n)}static WriteRuntimeContainer(t,e){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(t.WriteArrayStart(),null===e)return S("container");for(let n of e.content)this.WriteRuntimeObject(t,n);let i=e.namedOnlyContent,r=e.countFlags,a=null!=e.name&&!n,o=null!=i||r>0||a;if(o&&t.WriteObjectStart(),null!=i)for(let[e,n]of i){let i=e,r=s(n,L);t.WritePropertyStart(i),this.WriteRuntimeContainer(t,r,!0),t.WritePropertyEnd()}r>0&&t.WriteIntProperty("#f",r),a&&t.WriteProperty("#n",e.name),o?t.WriteObjectEnd():t.WriteNull(),t.WriteArrayEnd()}static JArrayToContainer(t){let e=new L;e.content=this.JArrayToRuntimeObjList(t,!0);let n=t[t.length-1];if(null!=n){let t=new Map;for(let i in n)if("#f"==i)e.countFlags=parseInt(n[i]);else if("#n"==i)e.name=n[i].toString();else{let e=this.JTokenToRuntimeObject(n[i]),r=s(e,L);r&&(r.name=i),t.set(i,e)}e.namedOnlyContent=t}return e}static JObjectToChoice(t){let e=new Kt;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(),t.tags&&(e.tags=t.tags),e}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),e.tags&&t.WriteProperty("tags",(t=>{t.WriteArrayStart();for(const n of e.tags)t.WriteStringStart(),t.WriteStringInner(n),t.WriteStringEnd();t.WriteArrayEnd()})),t.WriteObjectEnd()}static WriteInkList(t,e){let n=e.value;if(null===n)return S("rawList");t.WriteObjectStart(),t.WritePropertyStart("list"),t.WriteObjectStart();for(let[e,i]of n){let n=w.fromSerializedKey(e),r=i;if(null===n.itemName)return S("item.itemName");t.WritePropertyNameStart(),t.WritePropertyNameInner(n.originName?n.originName:"?"),t.WritePropertyNameInner("."),t.WritePropertyNameInner(n.itemName),t.WritePropertyNameEnd(),t.Write(r),t.WritePropertyEnd()}if(t.WriteObjectEnd(),t.WritePropertyEnd(),0==n.Count&&null!=n.originNames&&n.originNames.length>0){t.WritePropertyStart("origins"),t.WriteArrayStart();for(let e of n.originNames)t.Write(e);t.WriteArrayEnd(),t.WritePropertyEnd()}t.WriteObjectEnd()}static ListDefinitionsToJToken(t){let e={};for(let n of t.lists){let t={};for(let[e,i]of n.items){let n=w.fromSerializedKey(e);if(null===n.itemName)return S("item.itemName");t[n.itemName]=i}e[n.name]=t}return e}static JTokenToListDefinitions(t){let e=t,n=[];for(let t in e)if(e.hasOwnProperty(t)){let i=t.toString(),r=e[t],s=new Map;for(let n in r)if(e.hasOwnProperty(t)){let t=r[n];s.set(n,parseInt(t))}let a=new Tt(i,s);n.push(a)}return new Ht(n)}}Jt._controlCommandNames=(()=>{let t=[];t[D.CommandType.EvalStart]="ev",t[D.CommandType.EvalOutput]="out",t[D.CommandType.EvalEnd]="/ev",t[D.CommandType.Duplicate]="du",t[D.CommandType.PopEvaluatedValue]="pop",t[D.CommandType.PopFunction]="~ret",t[D.CommandType.PopTunnel]="->->",t[D.CommandType.BeginString]="str",t[D.CommandType.EndString]="/str",t[D.CommandType.NoOp]="nop",t[D.CommandType.ChoiceCount]="choiceCnt",t[D.CommandType.Turns]="turn",t[D.CommandType.TurnsSince]="turns",t[D.CommandType.ReadCount]="readc",t[D.CommandType.Random]="rnd",t[D.CommandType.SeedRandom]="srnd",t[D.CommandType.VisitIndex]="visit",t[D.CommandType.SequenceShuffleIndex]="seq",t[D.CommandType.StartThread]="thread",t[D.CommandType.Done]="done",t[D.CommandType.End]="end",t[D.CommandType.ListFromInt]="listInt",t[D.CommandType.ListRange]="range",t[D.CommandType.ListRandom]="lrnd",t[D.CommandType.BeginTag]="#",t[D.CommandType.EndTag]="/#";for(let e=0;e<D.CommandType.TOTAL_VALUES;++e)if(null==t[e])throw new Error("Control command not accounted for in serialisation");return t})();class zt{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(t){f.Assert(1==this._threads.length,"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=H.Null,arguments[0]instanceof re){let t=arguments[0];this._startOfRoot=H.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 zt.Thread),this._threads[0].callstack.push(new zt.Element(v.Tunnel,this._startOfRoot))}SetJsonToken(t,e){this._threads.length=0;let n=t.threads;for(let t of n){let n=t,i=new zt.Thread(n,e);this._threads.push(i)}this._threadCounter=parseInt(t.threadCounter),this._startOfRoot=H.StartOf(e.rootContentContainer)}WriteJson(t){t.WriteObject((t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let e of this._threads)e.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.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)throw new Error("Can't pop thread");this._threads.splice(this._threads.indexOf(this.currentThread),1)}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==v.FunctionEvaluationFromGame}Push(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=new zt.Element(t,this.currentElement.currentPointer,!1);i.evaluationStackHeightWhenPushed=e,i.functionStartInOutputStream=n,this.callStack.push(i)}CanPop(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return!!this.canPop&&(null==t||this.currentElement.type==t)}Pop(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(!this.CanPop(t))throw new Error("Mismatched push/pop in Callstack");this.callStack.pop()}GetTemporaryVariableWithName(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;-1==e&&(e=this.currentElementIndex+1);let n=T(this.callStack[e-1].temporaryVariables,t,null);return n.exists?n.result:null}SetTemporaryVariable(t,e,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1;-1==i&&(i=this.currentElementIndex+1);let r=this.callStack[i-1];if(!n&&!r.temporaryVariables.get(t))throw new Error("Could not find temporary variable to set: "+t);let s=T(r.temporaryVariables,t,null);s.exists&&R.RetainListOriginsForAssignment(s.result,e),r.temporaryVariables.set(t,e)}ContextForVariableNamed(t){return this.currentElement.temporaryVariables.get(t)?this.currentElementIndex+1:0}ThreadWithIndex(t){let e=this._threads.filter((e=>{if(e.threadIndex==t)return e}));return e.length>0?e[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let t=new b;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}===\n",e+1,this._threads.length,i?"(current) ":"");for(let e=0;e<n.callstack.length;e++){n.callstack[e].type==v.Function?t.Append(" [FUNCTION] "):t.Append(" [TUNNEL] ");let i=n.callstack[e].currentPointer;if(!i.isNull){if(t.Append("<SOMEWHERE IN "),null===i.container)return S("pointer.container");t.Append(i.container.path.toString()),t.AppendLine(">")}}}return t.toString()}}!function(t){class e{constructor(t,e){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=e.copy(),this.inExpressionEvaluation=n,this.temporaryVariables=new Map,this.type=t}Copy(){let t=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return t.temporaryVariables=new Map(this.temporaryVariables),t.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,t.functionStartInOutputStream=this.functionStartInOutputStream,t}}t.Element=e;class n{constructor(){if(this.threadIndex=0,this.previousPointer=H.Null,this.callstack=[],arguments[0]&&arguments[1]){let t=arguments[0],n=arguments[1];this.threadIndex=parseInt(t.threadIndex);let i=t.callstack;for(let t of i){let i,r=t,s=parseInt(r.type),a=H.Null,o=r.cPath;if(void 0!==o){i=o.toString();let t=n.ContentAtPath(new m(i));if(a.container=t.container,a.index=parseInt(r.idx),null==t.obj)throw new Error("When loading state, internal story location couldn't be found: "+i+". Has the story changed since this save data was created?");if(t.approximate){if(null===a.container)return S("pointer.container");n.Warning("When loading state, exact internal story location couldn't be found: '"+i+"', so it was approximated to '"+a.container.path.toString()+"' to recover. Has the story changed since this save data was created?")}}let l=!!r.exp,h=new e(s,a,l),u=r.temp;void 0!==u?h.temporaryVariables=Jt.JObjectToDictionaryRuntimeObjs(u):h.temporaryVariables.clear(),this.callstack.push(h)}let r=t.previousContentObject;if(void 0!==r){let t=new m(r.toString());this.previousPointer=n.PointerAtPath(t)}}}Copy(){let t=new n;t.threadIndex=this.threadIndex;for(let e of this.callstack)t.callstack.push(e.Copy());return t.previousPointer=this.previousPointer.copy(),t}WriteJson(t){t.WriteObjectStart(),t.WritePropertyStart("callstack"),t.WriteArrayStart();for(let e of this.callstack){if(t.WriteObjectStart(),!e.currentPointer.isNull){if(null===e.currentPointer.container)return S("el.currentPointer.container");t.WriteProperty("cPath",e.currentPointer.container.path.componentsString),t.WriteIntProperty("idx",e.currentPointer.index)}t.WriteProperty("exp",e.inExpressionEvaluation),t.WriteIntProperty("type",e.type),e.temporaryVariables.size>0&&(t.WritePropertyStart("temp"),Jt.WriteDictionaryRuntimeObjs(t,e.temporaryVariables),t.WritePropertyEnd()),t.WriteObjectEnd()}if(t.WriteArrayEnd(),t.WritePropertyEnd(),t.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let e=this.previousPointer.Resolve();if(null===e)return S("this.previousPointer.Resolve()");t.WriteProperty("previousContentObject",e.path.toString())}t.WriteObjectEnd()}}t.Thread=n}(zt||(zt={}));class Xt extends class{}{variableChangedEvent(t,e){for(let n of this.variableChangedEventCallbacks)n(t,e)}get batchObservingVariableChanges(){return this._batchObservingVariableChanges}set batchObservingVariableChanges(t){if(this._batchObservingVariableChanges=t,t)this._changedVariablesForBatchObs=new Set;else if(null!=this._changedVariablesForBatchObs){for(let t of this._changedVariablesForBatchObs){let e=this._globalVariables.get(t);e?this.variableChangedEvent(t,e):S("currentValue")}this._changedVariablesForBatchObs=null}}get callStack(){return this._callStack}set callStack(t){this._callStack=t}$(t,e){if(void 0===e){let e=null;return null!==this.patch&&(e=this.patch.TryGetGlobal(t,null),e.exists)?e.result.valueObject:(e=this._globalVariables.get(t),void 0===e&&(e=this._defaultGlobalVariables.get(t)),void 0!==e?e.valueObject:null)}{if(void 0===this._defaultGlobalVariables.get(t))throw new _("Cannot assign to a variable ("+t+") that hasn't been declared in the story");let n=A.Create(e);if(null==n)throw null==e?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._batchObservingVariableChanges=!1,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._globalVariables=new Map,this._callStack=t,this._listDefsOrigin=e;try{return new Proxy(this,{get:(t,e)=>e in t?t[e]:t.$(e),set:(t,e,n)=>(e in t?t[e]=n:t.$(e,n),!0)})}catch(t){}}ApplyPatch(){if(null===this.patch)return S("this.patch");for(let[t,e]of this.patch.globals)this._globalVariables.set(t,e);if(null!==this._changedVariablesForBatchObs)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(void 0!==i){let t=Jt.JTokenToRuntimeObject(i);if(null===t)return S("tokenInkObject");this._globalVariables.set(e,t)}else this._globalVariables.set(e,n)}}WriteJson(t){t.WriteObjectStart();for(let[e,n]of this._globalVariables){let i=e,r=n;if(Xt.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let t=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(r,t))continue}t.WritePropertyStart(i),Jt.WriteRuntimeObject(t,r),t.WritePropertyEnd()}t.WriteObjectEnd()}RuntimeObjectsEqual(t,e){if(null===t)return S("obj1");if(null===e)return S("obj2");if(t.constructor!==e.constructor)return!1;let n=s(t,P);if(null!==n)return n.value===a(e,P).value;let i=s(t,N);if(null!==i)return i.value===a(e,N).value;let r=s(t,O);if(null!==r)return r.value===a(e,O).value;let o=s(t,A),l=s(e,A);if(null!==o&&null!==l)return h(o.valueObject)&&h(l.valueObject)?o.valueObject.Equals(l.valueObject):o.valueObject===l.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+t.constructor.name)}GetVariableWithName(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,n=this.GetRawVariableWithName(t,e),i=s(n,W);return null!==i&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(t){let e=T(this._defaultGlobalVariables,t,null);return e.exists?e.result:null}GlobalVariableExistsWithName(t){return this._globalVariables.has(t)||null!==this._defaultGlobalVariables&&this._defaultGlobalVariables.has(t)}GetRawVariableWithName(t,e){let n=null;if(0==e||-1==e){let e=null;if(null!==this.patch&&(e=this.patch.TryGetGlobal(t,null),e.exists))return e.result;if(e=T(this._globalVariables,t,null),e.exists)return e.result;if(null!==this._defaultGlobalVariables&&(e=T(this._defaultGlobalVariables,t,null),e.exists))return e.result;if(null===this._listDefsOrigin)return S("VariablesState._listDefsOrigin");let n=this._listDefsOrigin.FindSingleItemListWithName(t);if(n)return n}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(null===n)return S("name");let i=-1,r=!1;if(r=t.isNewDeclaration?t.isGlobal:this.GlobalVariableExistsWithName(n),t.isNewDeclaration){let t=s(e,W);if(null!==t){e=this.ResolveVariablePointer(t)}}else{let t=null;do{t=s(this.GetRawVariableWithName(n,i),W),null!=t&&(n=t.variableName,i=t.contextIndex,r=0==i)}while(null!=t)}r?this.SetGlobal(n,e):this._callStack.SetTemporaryVariable(n,e,t.isNewDeclaration,i)}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables)}RetainListOriginsForAssignment(t,e){let n=a(t,R),i=a(e,R);n.value&&i.value&&0==i.value.Count&&i.value.SetInitialOriginNames(n.value.originNames)}SetGlobal(t,e){let n=null;if(null===this.patch&&(n=T(this._globalVariables,t,null)),null!==this.patch&&(n=this.patch.TryGetGlobal(t,null),n.exists||(n=T(this._globalVariables,t,null))),R.RetainListOriginsForAssignment(n.result,e),null===t)return S("variableName");if(null!==this.patch?this.patch.SetGlobal(t,e):this._globalVariables.set(t,e),null!==this.variableChangedEvent&&null!==n&&e!==n.result)if(this.batchObservingVariableChanges){if(null===this._changedVariablesForBatchObs)return S("this._changedVariablesForBatchObs");null!==this.patch?this.patch.AddChangedVariable(t):null!==this._changedVariablesForBatchObs&&this._changedVariablesForBatchObs.add(t)}else this.variableChangedEvent(t,e)}ResolveVariablePointer(t){let e=t.contextIndex;-1==e&&(e=this.GetContextIndexOfVariableNamed(t.variableName));let n=s(this.GetRawVariableWithName(t.variableName,e),W);return null!=n?n:new W(t.variableName,e)}GetContextIndexOfVariableNamed(t){return this.GlobalVariableExistsWithName(t)?0:this._callStack.currentElementIndex}ObserveVariableChange(t){this.variableChangedEventCallbacks.push(t)}}Xt.dontSaveDefaultValues=!0;class Yt{constructor(t){this.seed=t%2147483647,this.seed<=0&&(this.seed+=2147483646)}next(){return this.seed=48271*this.seed%2147483647}nextFloat(){return(this.next()-1)/2147483646}}class Zt{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,1===arguments.length&&null!==arguments[0]){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 null!==t&&this._globals.has(t)?{result:this._globals.get(t),exists:!0}:{result:e,exists:!1}}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:!0}:{result:e,exists:!1}}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:!0}:{result:e,exists:!1}}}class Qt{static TextToDictionary(t){return new Qt.Reader(t).ToDictionary()}static TextToArray(t){return new Qt.Reader(t).ToArray()}}!function(t){t.Reader=class{constructor(t){this._rootObject=JSON.parse(t)}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}};class e{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null}WriteObject(t){this.WriteObjectStart(),t(this),this.WriteObjectEnd()}WriteObjectStart(){this.StartNewObject(!0);let e={};if(this.state===t.Writer.State.Property){this.Assert(null!==this.currentCollection),this.Assert(null!==this.currentPropertyName);let t=this._propertyNameStack.pop();this.currentCollection[t]=e,this._collectionStack.push(e)}else this.state===t.Writer.State.Array?(this.Assert(null!==this.currentCollection),this.currentCollection.push(e),this._collectionStack.push(e)):(this.Assert(this.state===t.Writer.State.None),this._jsonObject=e,this._collectionStack.push(e));this._stateStack.push(new t.Writer.StateElement(t.Writer.State.Object))}WriteObjectEnd(){this.Assert(this.state===t.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop()}WriteProperty(t,e){if(this.WritePropertyStart(t),arguments[1]instanceof Function){(0,arguments[1])(this)}else{let t=arguments[1];this.Write(t)}this.WritePropertyEnd()}WriteIntProperty(t,e){this.WritePropertyStart(t),this.WriteInt(e),this.WritePropertyEnd()}WriteFloatProperty(t,e){this.WritePropertyStart(t),this.WriteFloat(e),this.WritePropertyEnd()}WritePropertyStart(e){this.Assert(this.state===t.Writer.State.Object),this._propertyNameStack.push(e),this.IncrementChildCount(),this._stateStack.push(new t.Writer.StateElement(t.Writer.State.Property))}WritePropertyEnd(){this.Assert(this.state===t.Writer.State.Property),this.Assert(1===this.childCount),this._stateStack.pop()}WritePropertyNameStart(){this.Assert(this.state===t.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new t.Writer.StateElement(t.Writer.State.Property)),this._stateStack.push(new t.Writer.StateElement(t.Writer.State.PropertyName))}WritePropertyNameEnd(){this.Assert(this.state===t.Writer.State.PropertyName),this.Assert(null!==this._currentPropertyName),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop()}WritePropertyNameInner(e){this.Assert(this.state===t.Writer.State.PropertyName),this.Assert(null!==this._currentPropertyName),this._currentPropertyName+=e}WriteArrayStart(){this.StartNewObject(!0);let e=[];if(this.state===t.Writer.State.Property){this.Assert(null!==this.currentCollection),this.Assert(null!==this.currentPropertyName);let t=this._propertyNameStack.pop();this.currentCollection[t]=e,this._collectionStack.push(e)}else this.state===t.Writer.State.Array?(this.Assert(null!==this.currentCollection),this.currentCollection.push(e),this._collectionStack.push(e)):(this.Assert(this.state===t.Writer.State.None),this._jsonObject=e,this._collectionStack.push(e));this._stateStack.push(new t.Writer.StateElement(t.Writer.State.Array))}WriteArrayEnd(){this.Assert(this.state===t.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop()}Write(t){null!==t?(this.StartNewObject(!1),this._addToCurrentObject(t)):console.error("Warning: trying to write a null value")}WriteBool(t){null!==t&&(this.StartNewObject(!1),this._addToCurrentObject(t))}WriteInt(t){null!==t&&(this.StartNewObject(!1),this._addToCurrentObject(Math.floor(t)))}WriteFloat(t){null!==t&&(this.StartNewObject(!1),t==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):t==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(t)?this._addToCurrentObject(0):this._addToCurrentObject(t))}WriteNull(){this.StartNewObject(!1),this._addToCurrentObject(null)}WriteStringStart(){this.StartNewObject(!1),this._currentString="",this._stateStack.push(new t.Writer.StateElement(t.Writer.State.String))}WriteStringEnd(){this.Assert(this.state==t.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null}WriteStringInner(e){this.Assert(this.state===t.Writer.State.String),null!==e?this._currentString+=e:console.error("Warning: trying to write a null string")}toString(){return null===this._jsonObject?"":JSON.stringify(this._jsonObject)}StartNewObject(e){e?this.Assert(this.state===t.Writer.State.None||this.state===t.Writer.State.Property||this.state===t.Writer.State.Array):this.Assert(this.state===t.Writer.State.Property||this.state===t.Writer.State.Array),this.state===t.Writer.State.Property&&this.Assert(0===this.childCount),this.state!==t.Writer.State.Array&&this.state!==t.Writer.State.Property||this.IncrementChildCount()}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:t.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 t=this._stateStack.pop();t.childCount++,this._stateStack.push(t)}Assert(t){if(!t)throw Error("Assert failed while writing JSON")}_addToCurrentObject(e){this.Assert(null!==this.currentCollection),this.state===t.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(e)):this.state===t.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(null!==this.currentPropertyName),this.currentCollection[this.currentPropertyName]=e,this._propertyNameStack.pop())}}t.Writer=e,function(e){var n;(n=e.State||(e.State={}))[n.None=0]="None",n[n.Object=1]="Object",n[n.Array=2]="Array",n[n.Property=3]="Property",n[n.PropertyName=4]="PropertyName",n[n.String=5]="String";e.StateElement=class{constructor(e){this.type=t.Writer.State.None,this.childCount=0,this.type=e}}}(e=t.Writer||(t.Writer={}))}(Qt||(Qt={}));class te{constructor(){let t=arguments[0],e=arguments[1];if(this.name=t,this.callStack=new zt(e),arguments[2]){let t=arguments[2];this.callStack.SetJsonToken(t.callstack,e),this.outputStream=Jt.JArrayToRuntimeObjList(t.outputStream),this.currentChoices=Jt.JArrayToRuntimeObjList(t.currentChoices);let n=t.choiceThreads;void 0!==n&&this.LoadFlowChoiceThreads(n,e)}else this.outputStream=[],this.currentChoices=[]}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",(t=>this.callStack.WriteJson(t))),t.WriteProperty("outputStream",(t=>Jt.WriteListRuntimeObjs(t,this.outputStream)));let e=!1;for(let n of this.currentChoices){if(null===n.threadAtGeneration)return S("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,null===this.callStack.ThreadWithIndex(n.originalThreadIndex)&&(e||(e=!0,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(t),t.WritePropertyEnd())}e&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",(t=>{t.WriteArrayStart();for(let e of this.currentChoices)Jt.WriteChoice(t,e);t.WriteArrayEnd()})),t.WriteObjectEnd()}LoadFlowChoiceThreads(t,e){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(null!==i)n.threadAtGeneration=i.Copy();else{let i=t[`${n.originalThreadIndex}`];n.threadAtGeneration=new zt.Thread(i,e)}}}}class ee{ToJson(){let t=new Qt.Writer;return this.WriteJson(t),t.toString()}toJson(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.ToJson(t)}LoadJson(t){let e=Qt.TextToDictionary(t);this.LoadJsonObj(e),null!==this.onDidLoadState&&this.onDidLoadState()}VisitCountAtPathString(t){let e;if(null!==this._patch){let n=this.story.ContentAtPath(new m(t)).container;if(null===n)throw new Error("Content at path not found: "+t);if(e=this._patch.TryGetVisitCount(n,0),e.exists)return e.result}return e=T(this._visitCounts,t,null),e.exists?e.result:0}VisitCountForContainer(t){if(null===t)return S("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(null!==this._patch){let e=this._patch.TryGetVisitCount(t,0);if(e.exists)return e.result}let e=t.path.toString(),n=T(this._visitCounts,e,null);return n.exists?n.result:0}IncrementVisitCountForContainer(t){if(null!==this._patch){let e=this.VisitCountForContainer(t);return e++,void this._patch.SetVisitCount(t,e)}let e=t.path.toString(),n=T(this._visitCounts,e,null);n.exists?this._visitCounts.set(e,n.result+1):this._visitCounts.set(e,1)}RecordTurnIndexVisitToContainer(t){if(null!==this._patch)return void this._patch.SetTurnIndex(t,this.currentTurnIndex);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)."),null!==this._patch){let e=this._patch.TryGetTurnIndex(t,0);if(e.exists)return this.currentTurnIndex-e.result}let e=t.path.toString(),n=T(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:null===t.path?S("pointer.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 null!=this.currentErrors&&this.currentErrors.length>0}get hasWarning(){return null!=this.currentWarnings&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let t=new b,e=!1;for(let n of this.outputStream){let i=s(n,I);if(e||null===i){let t=s(n,D);null!==t&&(t.commandType==D.CommandType.BeginTag?e=!0:t.commandType==D.CommandType.EndTag&&(e=!1))}else t.Append(i.value)}this._currentText=this.CleanOutputWhitespace(t.toString()),this._outputStreamTextDirty=!1}return this._currentText}CleanOutputWhitespace(t){let e=new b,n=-1,i=0;for(let r=0;r<t.length;r++){let s=t.charAt(r),a=" "==s||"\t"==s;a&&-1==n&&(n=r),a||("\n"!=s&&n>0&&n!=i&&e.Append(" "),n=-1),"\n"==s&&(i=r+1),a||e.Append(s)}return e.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let t=!1,e=new b;for(let n of this.outputStream){let i=s(n,D);if(null!=i){if(i.commandType==D.CommandType.BeginTag){if(t&&e.Length>0){let t=this.CleanOutputWhitespace(e.toString());this._currentTags.push(t),e.Clear()}t=!0}else if(i.commandType==D.CommandType.EndTag){if(e.Length>0){let t=this.CleanOutputWhitespace(e.toString());this._currentTags.push(t),e.Clear()}t=!1}}else if(t){let t=s(n,I);null!==t&&e.Append(t.value)}else{let t=s(n,Ut);null!=t&&null!=t.text&&t.text.length>0&&this._currentTags.push(t.text)}}if(e.Length>0){let t=this.CleanOutputWhitespace(e.toString());this._currentTags.push(t),e.Clear()}this._outputStreamTagsDirty=!1}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=[],null!=this._namedFlows)for(let t of this._namedFlows.keys())t!=this.kDefaultFlowName&&this._aliveFlowNames.push(t);this._aliveFlowNamesDirty=!1}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=H.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=!1,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=!0,this.story=t,this._currentFlow=new te(this.kDefaultFlowName,t),this.OutputStreamDirty(),this._aliveFlowNamesDirty=!0,this._evaluationStack=[],this._variablesState=new Xt(this.callStack,t.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let e=(new Date).getTime();this.storySeed=new Yt(e).next()%100,this.previousRandom=0,this.GoToStart()}GoToStart(){this.callStack.currentElement.currentPointer=H.StartOf(this.story.mainContentContainer)}SwitchFlow_Internal(t){if(null===t)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(null===this._namedFlows&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),t===this._currentFlow.name)return;let e,n=T(this._namedFlows,t,null);n.exists?e=n.result:(e=new te(t,this.story),this._namedFlows.set(t,e),this._aliveFlowNamesDirty=!0),this._currentFlow=e,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty()}SwitchToDefaultFlow_Internal(){null!==this._namedFlows&&this.SwitchFlow_Internal(this.kDefaultFlowName)}RemoveFlow_Internal(t){if(null===t)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(),null===this._namedFlows)return S("this._namedFlows");this._namedFlows.delete(t),this._aliveFlowNamesDirty=!0}CopyAndStartPatching(){let t=new ee(this.story);if(t._patch=new Zt(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new zt(this._currentFlow.callStack),t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),null!==this._namedFlows){t._namedFlows=new Map;for(let[e,n]of this._namedFlows)t._namedFlows.set(e,n),t._aliveFlowNamesDirty=!0;t._namedFlows.set(this._currentFlow.name,t._currentFlow)}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch}ApplyAnyPatch(){if(null!==this._patch){this.variablesState.ApplyPatch();for(let[t,e]of this._patch.visitCounts)this.ApplyCountChanges(t,e,!0);for(let[t,e]of this._patch.turnIndices)this.ApplyCountChanges(t,e,!1);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(),null!==this._namedFlows)for(let[e,n]of this._namedFlows)t.WriteProperty(e,(t=>n.WriteJson(t)));else t.WriteProperty(this._currentFlow.name,(t=>this._currentFlow.WriteJson(t)));if(t.WriteObjectEnd(),t.WritePropertyEnd(),t.WriteProperty("currentFlowName",this._currentFlow.name),t.WriteProperty("variablesState",(t=>this.variablesState.WriteJson(t))),t.WriteProperty("evalStack",(t=>Jt.WriteListRuntimeObjs(t,this.evaluationStack))),!this.divertedPointer.isNull){if(null===this.divertedPointer.path)return S("divertedPointer");t.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString)}t.WriteProperty("visitCounts",(t=>Jt.WriteIntDictionary(t,this._visitCounts))),t.WriteProperty("turnIndices",(t=>Jt.WriteIntDictionary(t,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",re.inkVersionCurrent),t.WriteObjectEnd()}LoadJsonObj(t){let e=t,n=e.inkSaveVersion;if(null==n)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(null!=i){let t=i;1===Object.keys(t).length?this._namedFlows=null:null===this._namedFlows?this._namedFlows=new Map:this._namedFlows.clear();let n=Object.entries(t);for(let[e,i]of n){let n=e,r=i,s=new te(n,this.story,r);if(1===Object.keys(t).length)this._currentFlow=new te(n,this.story,r);else{if(null===this._namedFlows)return S("this._namedFlows");this._namedFlows.set(n,s)}}if(null!=this._namedFlows&&this._namedFlows.size>1){let t=e.currentFlowName;this._currentFlow=this._namedFlows.get(t)}}else{this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(e.callstackThreads,this.story),this._currentFlow.outputStream=Jt.JArrayToRuntimeObjList(e.outputStream),this._currentFlow.currentChoices=Jt.JArrayToRuntimeObjList(e.currentChoices);let t=e.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(t,this.story)}this.OutputStreamDirty(),this._aliveFlowNamesDirty=!0,this.variablesState.SetJsonToken(e.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Jt.JArrayToRuntimeObjList(e.evalStack);let r=e.currentDivertTarget;if(null!=r){let t=new m(r.toString());this.divertedPointer=this.story.PointerAtPath(t)}this._visitCounts=Jt.JObjectToIntDictionary(e.visitCounts),this._turnIndices=Jt.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(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;this.outputStream.length=0,null!==t&&this.outputStream.push(...t),this.OutputStreamDirty()}PushToOutputStream(t){let e=s(t,I);if(null!==e){let t=this.TrySplittingHeadTailWhitespace(e);if(null!==t){for(let e of t)this.PushToOutputStreamIndividual(e);return void this.OutputStreamDirty()}}this.PushToOutputStreamIndividual(t),this.OutputStreamDirty()}PopFromOutputStream(t){this.outputStream.splice(this.outputStream.length-t,t),this.OutputStreamDirty()}TrySplittingHeadTailWhitespace(t){let e=t.value;if(null===e)return S("single.value");let n=-1,i=-1;for(let t=0;t<e.length;t++){let r=e[t];if("\n"!=r){if(" "==r||"\t"==r)continue;break}-1==n&&(n=t),i=t}let r=-1,s=-1;for(let t=e.length-1;t>=0;t--){let n=e[t];if("\n"!=n){if(" "==n||"\t"==n)continue;break}-1==r&&(r=t),s=t}if(-1==n&&-1==r)return null;let a=[],o=0,l=e.length;if(-1!=n){if(n>0){let t=new I(e.substring(0,n));a.push(t)}a.push(new I("\n")),o=i+1}if(-1!=r&&(l=s),l>o){let t=e.substring(o,l);a.push(new I(t))}if(-1!=r&&s>i&&(a.push(new I("\n")),r<e.length-1)){let t=e.length-r-1,n=new I(e.substring(r+1,r+1+t));a.push(n)}return a}PushToOutputStreamIndividual(t){let e=s(t,Lt),n=s(t,I),i=!0;if(e)this.TrimNewlinesFromOutputStream(),i=!0;else if(n){let t=-1,e=this.callStack.currentElement;e.type==v.Function&&(t=e.functionStartInOutputStream);let r=-1;for(let e=this.outputStream.length-1;e>=0;e--){let n=this.outputStream[e],i=n instanceof D?n:null;if(null!=(n instanceof Lt?n:null)){r=e;break}if(null!=i&&i.commandType==D.CommandType.BeginString){e>=t&&(t=-1);break}}let s=-1;if(s=-1!=r&&-1!=t?Math.min(t,r):-1!=r?r:t,-1!=s){if(n.isNewline)i=!1;else if(n.isNonWhitespace&&(r>-1&&this.RemoveExistingGlue(),t>-1)){let t=this.callStack.elements;for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.type!=v.Function)break;n.functionStartInOutputStream=-1}}}else n.isNewline&&(!this.outputStreamEndsInNewline&&this.outputStreamContainsContent||(i=!1))}if(i){if(null===t)return S("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=s(n,D),r=s(n,I);if(null!=i||null!=r&&r.isNonWhitespace)break;null!=r&&r.isNewline&&(t=e),e--}if(t>=0)for(e=t;e<this.outputStream.length;){s(this.outputStream[e],I)?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 Lt)this.outputStream.splice(t,1);else if(e instanceof D)break}this.OutputStreamDirty()}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let t=this.outputStream.length-1;t>=0;t--){if(this.outputStream[t]instanceof D)break;let e=this.outputStream[t];if(e instanceof I){if(e.isNewline)return!0;if(e.isNonWhitespace)break}}return!1}get outputStreamContainsContent(){for(let t of this.outputStream)if(t instanceof I)return!0;return!1}get inStringEvaluation(){for(let t=this.outputStream.length-1;t>=0;t--){let e=s(this.outputStream[t],D);if(e instanceof D&&e.commandType==D.CommandType.BeginString)return!0}return!1}PushEvaluationStack(t){let e=s(t,R);if(e){let t=e.value;if(null===t)return S("rawList");if(null!=t.originNames){t.origins||(t.origins=[]),t.origins.length=0;for(let e of t.originNames){if(null===this.story.listDefinitions)return S("StoryState.story.listDefinitions");let n=this.story.listDefinitions.TryListGetDefinition(e,null);if(null===n.result)return S("StoryState def.result");t.origins.indexOf(n.result)<0&&t.origins.push(n.result)}}}if(null===t)return S("obj");this.evaluationStack.push(t)}PopEvaluationStack(t){if(void 0===t){return l(this.evaluationStack.pop())}if(t>this.evaluationStack.length)throw new Error("trying to pop too many objects");return l(this.evaluationStack.splice(this.evaluationStack.length-t,t))}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=H.Null,this.previousPointer=H.Null,this.didSafeExit=!0}TrimWhitespaceFromFunctionEnd(){f.Assert(this.callStack.currentElement.type==v.Function);let t=this.callStack.currentElement.functionStartInOutputStream;-1==t&&(t=0);for(let e=this.outputStream.length-1;e>=t;e--){let t=this.outputStream[e],n=s(t,I),i=s(t,D);if(null!=n){if(i)break;if(!n.isNewline&&!n.isInlineWhitespace)break;this.outputStream.splice(e,1),this.OutputStreamDirty()}}}PopCallStack(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;this.callStack.currentElement.type==v.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(t)}SetChosenPath(t,e){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(t);n.isNull||-1!=n.index||(n.index=0),this.currentPointer=n,e&&this.currentTurnIndex++}StartFunctionEvaluationFromGame(t,e){this.callStack.Push(v.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=H.StartOf(t),this.PassArgumentsToEvaluationStack(e)}PassArgumentsToEvaluationStack(t){if(null!==t)for(let e=0;e<t.length;e++){if(!("number"==typeof t[e]||"string"==typeof t[e]||"boolean"==typeof t[e]||t[e]instanceof E))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+(null===l(t[e])?"null":t[e].constructor.name));this.PushEvaluationStack(A.Create(t[e]))}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==v.FunctionEvaluationFromGame&&(this.currentPointer=H.Null,this.didSafeExit=!0,!0)}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=v.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 t=this.PopEvaluationStack();null===e&&(e=t)}if(this.PopCallStack(v.FunctionEvaluationFromGame),e){if(e instanceof j)return null;let t=a(e,A);return t.valueType==g.DivertTarget?t.valueObject.toString():t.valueObject}return null}AddError(t,e){e?(null==this._currentWarnings&&(this._currentWarnings=[]),this._currentWarnings.push(t)):(null==this._currentErrors&&(this._currentErrors=[]),this._currentErrors.push(t))}OutputStreamDirty(){this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0}}class ne{constructor(){this.startTime=void 0}get ElapsedMilliseconds(){return void 0===this.startTime?0:(new Date).getTime()-this.startTime}Start(){this.startTime=(new Date).getTime()}Stop(){this.startTime=void 0}}var ie;!function(t){t[t.Author=0]="Author",t[t.Warning=1]="Warning",t[t.Error=2]="Error"}(ie||(ie={})),Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&t>-9007199254740992&&t<9007199254740992&&Math.floor(t)===t});let re=class t extends y{get currentChoices(){let t=[];if(null===this._state)return S("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(){let e;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=!1,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=!1,this._temporaryEvaluationContainer=null,this._asyncContinueActive=!1,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=!1,this._recursiveContinueCount=0,this._asyncSaving=!1,this._profiler=null;let n=null,i=null;if(arguments[0]instanceof L)e=arguments[0],void 0!==arguments[1]&&(n=arguments[1]),this._mainContentContainer=e;else if("string"==typeof arguments[0]){let t=arguments[0];i=Qt.TextToDictionary(t)}else i=arguments[0];if(null!=n&&(this._listDefinitions=new Ht(n)),this._externals=new Map,null!==i){let e=i,n=e.inkVersion;if(null==n)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let r=parseInt(n);if(r>t.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!=t.inkVersionCurrent&&console.warn("WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising.");let s,o=e.root;if(null==o)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");(s=e.listDefs)&&(this._listDefinitions=Jt.JTokenToListDefinitions(s)),this._mainContentContainer=a(Jt.JTokenToRuntimeObject(o),L),this.ResetState()}}ToJson(e){let n=!1;if(e||(n=!0,e=new Qt.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",t.inkVersionCurrent),e.WriteProperty("root",(t=>Jt.WriteRuntimeContainer(t,this._mainContentContainer))),null!=this._listDefinitions){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let t of this._listDefinitions.lists){e.WritePropertyStart(t.name),e.WriteObjectStart();for(let[n,i]of t.items){let t=w.fromSerializedKey(n),r=i;e.WriteIntProperty(t.itemName,r)}e.WriteObjectEnd(),e.WritePropertyEnd()}e.WriteObjectEnd(),e.WritePropertyEnd()}if(e.WriteObjectEnd(),n)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new ee(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals()}ResetErrors(){if(null===this._state)return S("this._state");this._state.ResetErrors()}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),null===this._state)return S("this._state");this._state.ForceEnd()}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let t=this.state.currentPointer.copy();this.ChoosePath(new m("global decl"),!1),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(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;null!=this._profiler&&this._profiler.PreContinue();let e=t>0;if(this._recursiveContinueCount++,!this._asyncContinueActive){if(this._asyncContinueActive=e,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=!1,this._state.ResetOutput(),1==this._recursiveContinueCount&&(this._state.variablesState.batchObservingVariableChanges=!0)}let n=new ne;n.Start();let i=!1;this._sawLookaheadUnsafeFunctionAfterNewline=!1;do{try{i=this.ContinueSingleStep()}catch(t){if(!(t instanceof _))throw t;this.AddError(t.message,void 0,t.useEndLineNumber);break}if(i)break;if(this._asyncContinueActive&&n.ElapsedMilliseconds>t)break}while(this.canContinue);if(n.Stop(),!i&&this.canContinue||(null!==this._stateSnapshotAtLastNewline&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),0!=this.state.generatedChoices.length||this.state.didSafeExit||null!=this._temporaryEvaluationContainer||(this.state.callStack.CanPop(v.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(v.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=!1,this._sawLookaheadUnsafeFunctionAfterNewline=!1,1==this._recursiveContinueCount&&(this._state.variablesState.batchObservingVariableChanges=!1),this._asyncContinueActive=!1,null!==this.onDidContinue&&this.onDidContinue()),this._recursiveContinueCount--,null!=this._profiler&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning){if(null===this.onError){let t=new b;throw t.Append("Ink had "),this.state.hasError&&(t.Append(`${this.state.currentErrors.length}`),t.Append(1==this.state.currentErrors.length?" error":"errors"),this.state.hasWarning&&t.Append(" and ")),this.state.hasWarning&&(t.Append(`${this.state.currentWarnings.length}`),t.Append(1==this.state.currentWarnings.length?" warning":"warnings"),this.state.hasWarning&&t.Append(" and ")),t.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),t.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new _(t.toString())}if(this.state.hasError)for(let t of this.state.currentErrors)this.onError(t,ie.Error);if(this.state.hasWarning)for(let t of this.state.currentWarnings)this.onError(t,ie.Warning);this.ResetErrors()}}ContinueSingleStep(){if(null!=this._profiler&&this._profiler.PreStep(),this.Step(),null!=this._profiler&&this._profiler.PostStep(),this.canContinue||this.state.callStack.elementIsEvaluateFromGame||this.TryFollowDefaultInvisibleChoice(),null!=this._profiler&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(null!==this._stateSnapshotAtLastNewline){if(null===this._stateSnapshotAtLastNewline.currentTags)return S("this._stateAtLastNewline.currentTags");if(null===this.state.currentTags)return S("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==t.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),!0;e==t.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot()}this.state.outputStreamEndsInNewline&&(this.canContinue?null==this._stateSnapshotAtLastNewline&&this.StateSnapshot():this.DiscardSnapshot())}return null!=this._profiler&&this._profiler.PostSnapshot(),!1}CalculateNewlineOutputStateChange(e,n,i,r){if(null===e)return S("prevText");if(null===n)return S("currText");let s=n.length>=e.length&&e.length>0&&"\n"==n.charAt(e.length-1);if(i==r&&e.length==n.length&&s)return t.OutputStateChange.NoChange;if(!s)return t.OutputStateChange.NewlineRemoved;if(r>i)return t.OutputStateChange.ExtendedBeyondNewline;for(let i=e.length;i<n.length;i++){let e=n.charAt(i);if(" "!=e&&"\t"!=e)return t.OutputStateChange.ExtendedBeyondNewline}return t.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let t=new b;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 L?e:null}PointerAtPath(t){if(0==t.length)return H.Null;let e=new H,n=t.length,i=null;return null===t.lastComponent?S("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),null==i.obj||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()}RestoreStateSnapshot(){null===this._stateSnapshotAtLastNewline&&S("_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(),this._asyncSaving=!0,t}BackgroundSaveComplete(){null===this._stateSnapshotAtLastNewline&&this._state.ApplyAnyPatch(),this._asyncSaving=!1}Step(){let t=!0,e=this.state.currentPointer.copy();if(e.isNull)return;let n=s(e.Resolve(),L);for(;n&&(this.VisitContainer(n,!0),0!=n.content.length);)e=H.StartOf(n),n=s(e.Resolve(),L);this.state.currentPointer=e.copy(),null!=this._profiler&&this._profiler.Step(this.state.callStack);let i=e.Resolve(),r=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;r&&(t=!1);let a=s(i,K);if(a){let e=this.ProcessChoice(a);e&&this.state.generatedChoices.push(e),i=null,t=!1}if(i instanceof L&&(t=!1),t){let t=s(i,W);if(t&&-1==t.contextIndex){let e=this.state.callStack.ContextForVariableNamed(t.variableName);i=new W(t.variableName,e)}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i)}this.NextContent();let o=s(i,D);o&&o.commandType==D.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||-1==e.index)return;if(this._prevContainers.length=0,!t.isNull){let e=s(t.Resolve(),L)||s(t.container,L);for(;e;)this._prevContainers.push(e),e=s(e.parent,L)}let n=e.Resolve();if(null==n)return;let i=s(n.parent,L),r=!0;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let t=i.content.length>0&&n==i.content[0]&&r;t||(r=!1),this.VisitContainer(i,t),n=i,i=s(i.parent,L)}}PopChoiceStringAndTags(t){let e=a(this.state.PopEvaluationStack(),I);for(;this.state.evaluationStack.length>0&&null!=s(this.state.PeekEvaluationStack(),Ut);){let e=s(this.state.PopEvaluationStack(),Ut);e&&t.push(e.text)}return e.value}ProcessChoice(t){let e=!0;if(t.hasCondition){let t=this.state.PopEvaluationStack();this.IsTruthy(t)||(e=!1)}let n="",i="",r=[];if(t.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(r)||""),t.hasStartContent&&(n=this.PopChoiceStringAndTags(r)||""),t.onceOnly){this.state.VisitCountForContainer(t.choiceTarget)>0&&(e=!1)}if(!e)return null;let s=new Kt;return s.targetPath=t.pathOnChoice,s.sourcePath=t.path.toString(),s.isInvisibleDefault=t.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=r.reverse(),s.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(t){if(t instanceof A){let e=t;if(e instanceof F){let t=e;return this.Error("Shouldn't use a divert target (to "+t.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),!1}return e.isTruthy}return!1}PerformLogicAndFlowControl(t){if(null==t)return!1;if(t instanceof J){let e=t;if(e.isConditional){let t=this.state.PopEvaluationStack();if(!this.IsTruthy(t))return!0}if(e.hasVariableTarget){let t=e.variableDivertName,n=this.state.variablesState.GetVariableWithName(t);if(null==n)this.Error("Tried to divert using a target from a variable that could not be found ("+t+")");else if(!(n instanceof F)){let e=s(n,N),i="Tried to divert to a target from a variable, but the variable ("+t+") didn't contain a divert target, it ";e instanceof N&&0==e.value?i+="was empty/null (the value 0).":i+="contained '"+n+"'.",this.Error(i)}let i=a(n,F);this.state.divertedPointer=this.PointerAtPath(i.targetPath)}else{if(e.isExternal)return this.CallExternalFunction(e.targetPathString,e.externalArgs),!0;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&&null!=e.debugMetadata.sourceName?this.Error("Divert target doesn't exist: "+e.debugMetadata.sourceName):this.Error("Divert resolution failed: "+e)),!0}if(t instanceof D){let e=t;switch(e.commandType){case D.CommandType.EvalStart:this.Assert(!1===this.state.inExpressionEvaluation,"Already in expression evaluation?"),this.state.inExpressionEvaluation=!0;break;case D.CommandType.EvalEnd:this.Assert(!0===this.state.inExpressionEvaluation,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=!1;break;case D.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let t=this.state.PopEvaluationStack();if(!(t instanceof j)){let e=new I(t.toString());this.state.PushToOutputStream(e)}}break;case D.CommandType.NoOp:break;case D.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case D.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case D.CommandType.PopFunction:case D.CommandType.PopTunnel:let t=e.commandType==D.CommandType.PopFunction?v.Function:v.Tunnel,n=null;if(t==v.Tunnel){let t=this.state.PopEvaluationStack();n=s(t,F),null===n&&this.Assert(t instanceof j,"Expected void if ->-> doesn't override target")}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type==t&&this.state.callStack.canPop)this.state.PopCallStack(),n&&(this.state.divertedPointer=this.PointerAtPath(n.targetPath));else{let e=new Map;e.set(v.Function,"function return statement (~ return)"),e.set(v.Tunnel,"tunnel onwards statement (->->)");let n=e.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(n="end of flow (-> END or choice)");let i="Found "+e.get(t)+", when expected "+n;this.Error(i)}break;case D.CommandType.BeginString:this.state.PushToOutputStream(e),this.Assert(!0===this.state.inExpressionEvaluation,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=!1;break;case D.CommandType.BeginTag:this.state.PushToOutputStream(e);break;case D.CommandType.EndTag:if(this.state.inStringEvaluation){let t=[],e=0;for(let n=this.state.outputStream.length-1;n>=0;--n){let i=this.state.outputStream[n];e++;let r=s(i,D);if(null!=r){if(r.commandType==D.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}i instanceof I&&t.push(i)}this.state.PopFromOutputStream(e);let n=new b;for(let e of t.reverse())n.Append(e.toString());let i=new Ut(this.state.CleanOutputWhitespace(n.toString()));this.state.PushEvaluationStack(i)}else this.state.PushToOutputStream(e);break;case D.CommandType.EndString:{let t=[],e=[],n=0;for(let i=this.state.outputStream.length-1;i>=0;--i){let r=this.state.outputStream[i];n++;let a=s(r,D);if(a&&a.commandType==D.CommandType.BeginString)break;r instanceof Ut&&e.push(r),r instanceof I&&t.push(r)}this.state.PopFromOutputStream(n);for(let t of e)this.state.PushToOutputStream(t);t=t.reverse();let i=new b;for(let e of t)i.Append(e.toString());this.state.inExpressionEvaluation=!0,this.state.PushEvaluationStack(new I(i.toString()));break}case D.CommandType.ChoiceCount:let i=this.state.generatedChoices.length;this.state.PushEvaluationStack(new N(i));break;case D.CommandType.Turns:this.state.PushEvaluationStack(new N(this.state.currentTurnIndex+1));break;case D.CommandType.TurnsSince:case D.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof F)){let t="";r instanceof N&&(t=". 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+t);break}let o,l=a(r,F),h=s(this.ContentAtPath(l.targetPath).correctObj,L);null!=h?o=e.commandType==D.CommandType.TurnsSince?this.state.TurnsSinceForContainer(h):this.state.VisitCountForContainer(h):(o=e.commandType==D.CommandType.TurnsSince?-1:0,this.Warning("Failed to find container for "+e.toString()+" lookup at "+l.targetPath.toString())),this.state.PushEvaluationStack(new N(o));break;case D.CommandType.Random:{let t=s(this.state.PopEvaluationStack(),N),e=s(this.state.PopEvaluationStack(),N);if(null==e||e instanceof N==!1)return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(null==t||t instanceof N==!1)return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(null===t.value)return S("maxInt.value");if(null===e.value)return S("minInt.value");let n=t.value-e.value+1;(!isFinite(n)||n>Number.MAX_SAFE_INTEGER)&&(n=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),n<=0&&this.Error("RANDOM was called with minimum as "+e.value+" and maximum as "+t.value+". The maximum must be larger");let i=this.state.storySeed+this.state.previousRandom,r=new Yt(i).next(),a=r%n+e.value;this.state.PushEvaluationStack(new N(a)),this.state.previousRandom=r;break}case D.CommandType.SeedRandom:let u=s(this.state.PopEvaluationStack(),N);if(null==u||u instanceof N==!1)return this.Error("Invalid value passed to SEED_RANDOM");if(null===u.value)return S("minInt.value");this.state.storySeed=u.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new j);break;case D.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new N(c));break;case D.CommandType.SequenceShuffleIndex:let d=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new N(d));break;case D.CommandType.StartThread:break;case D.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=!0,this.state.currentPointer=H.Null);break;case D.CommandType.End:this.state.ForceEnd();break;case D.CommandType.ListFromInt:let p=s(this.state.PopEvaluationStack(),N),m=a(this.state.PopEvaluationStack(),I);if(null===p)throw new _("Passed non-integer when creating a list element from a numerical value.");let f=null;if(null===this.listDefinitions)return S("this.listDefinitions");let g=this.listDefinitions.TryListGetDefinition(m.value,null);if(!g.exists)throw new _("Failed to find LIST called "+m.value);{if(null===p.value)return S("minInt.value");let t=g.result.TryGetItemWithValue(p.value,w.Null);t.exists&&(f=new R(t.result,p.value))}null==f&&(f=new R),this.state.PushEvaluationStack(f);break;case D.CommandType.ListRange:let C=s(this.state.PopEvaluationStack(),A),y=s(this.state.PopEvaluationStack(),A),T=s(this.state.PopEvaluationStack(),R);if(null===T||null===y||null===C)throw new _("Expected list, minimum and maximum for LIST_RANGE");if(null===T.value)return S("targetList.value");let x=T.value.ListWithSubRange(y.valueObject,C.valueObject);this.state.PushEvaluationStack(new R(x));break;case D.CommandType.ListRandom:{let t=this.state.PopEvaluationStack();if(null===t)throw new _("Expected list for LIST_RANDOM");let e=t.value,n=null;if(null===e)throw S("list");if(0==e.Count)n=new E;else{let t=this.state.storySeed+this.state.previousRandom,i=new Yt(t).next(),r=i%e.Count,s=e.entries();for(let t=0;t<=r-1;t++)s.next();let a=s.next().value,o={Key:w.fromSerializedKey(a[0]),Value:a[1]};if(null===o.Key.originName)return S("randomItem.Key.originName");n=new E(o.Key.originName,this),n.Add(o.Key,o.Value),this.state.previousRandom=i}this.state.PushEvaluationStack(new R(n));break}default:this.Error("unhandled ControlCommand: "+e)}return!0}if(t instanceof X){let e=t,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(e,n),!0}if(t instanceof mt){let e=t,n=null;if(null!=e.pathForCount){let t=e.containerForCount,i=this.state.VisitCountForContainer(t);n=new N(i)}else n=this.state.variablesState.GetVariableWithName(e.name),null==n&&(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 N(0));return this.state.PushEvaluationStack(n),!0}if(t instanceof B){let e=t,n=this.state.PopEvaluationStack(e.numberOfParameters),i=e.Call(n);return this.state.PushEvaluationStack(i),!0}return!1}ChoosePathString(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];if(this.IfAsyncWeCant("call ChoosePathString right now"),null!==this.onChoosePathString&&this.onChoosePathString(t,n),e)this.ResetCallstack();else if(this.state.callStack.currentElement.type==v.Function){let e="",n=this.state.callStack.currentElement.currentPointer.container;throw null!=n&&(e="("+n.path.toString()+") "),new Error("Story was running a function "+e+"when you called ChoosePathString("+t+") - this is almost certainly not not what you want! Full stack trace: \n"+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new m(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){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];this.state.SetChosenPath(t,e),this.VisitChangedContainersDueToDivert()}ChooseChoiceIndex(t){let e=this.currentChoices;this.Assert(t>=0&&t<e.length,"choice out of range");let n=e[t];return null!==this.onMakeChoice&&this.onMakeChoice(n),null===n.threadAtGeneration?S("choiceToChoose.threadAtGeneration"):null===n.targetPath?S("choiceToChoose.targetPath"):(this.state.callStack.currentThread=n.threadAtGeneration,void this.ChoosePath(n.targetPath))}HasFunction(t){try{return null!=this.KnotContainerWithName(t)}catch(t){return!1}}EvaluateFunction(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(null!==this.onEvaluateFunction&&this.onEvaluateFunction(t,e),this.IfAsyncWeCant("evaluate a function"),null==t)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(null==i)throw new Error("Function doesn't exist: '"+t+"'");let r=[];r.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,e);let s=new b;for(;this.canContinue;)s.Append(this.Continue());let a=s.toString();this._state.ResetOutput(r);let o=this.state.CompleteFunctionEvaluationFromGame();return null!=this.onCompleteEvaluateFunction&&this.onCompleteEvaluateFunction(t,e,a,o),n?{returned:o,output:a}:o}EvaluateExpression(t){let e=this.state.callStack.elements.length;this.state.callStack.Push(v.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(null===t)return S("funcName");let n=this._externals.get(t),i=null,r=void 0!==n;if(r&&!n.lookAheadSafe&&null!==this._stateSnapshotAtLastNewline)return void(this._sawLookaheadUnsafeFunctionAfterNewline=!0);if(!r){if(this.allowExternalFunctionFallbacks)return i=this.KnotContainerWithName(t),this.Assert(null!==i,"Trying to call EXTERNAL function '"+t+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(v.Function,void 0,this.state.outputStream.length),void(this.state.divertedPointer=H.StartOf(i));this.Assert(!1,"Trying to call EXTERNAL function '"+t+"' which has not been bound (and ink fallbacks disabled).")}let s=[];for(let t=0;t<e;++t){let t=a(this.state.PopEvaluationStack(),A).valueObject;s.push(t)}s.reverse();let o=n.function(s),l=null;null!=o?(l=A.Create(o),this.Assert(null!==l,"Could not create ink value from returned object of type "+typeof o)):l=new j,this.state.PushEvaluationStack(l)}BindExternalFunctionGeneral(t,e){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];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){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.Assert(null!=e,"Can't bind a null function"),this.BindExternalFunctionGeneral(t,(t=>{this.Assert(t.length>=e.length,"External function expected "+e.length+" arguments");let n=[];for(let e=0,i=t.length;e<i;e++)n[e]=this.TryCoerce(t[e]);return e.apply(null,n)}),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 L&&(t=arguments[0]),arguments[0]instanceof y&&(e=arguments[0]),null===t&&null===e)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=!0,0==n.size)this._hasValidatedExternals=!0;else{let t="Error: Missing function binding for external";t+=n.size>1?"s":"",t+=": '",t+=Array.from(n).join("', '"),t+="' ",t+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(t)}else if(null!=t){for(let e of t.content){null!=e&&e.hasValidName||this.ValidateExternalBindings(e,n)}for(let[,e]of t.namedContent)this.ValidateExternalBindings(s(e,y),n)}else if(null!=e){let t=s(e,J);if(t&&t.isExternal){let e=t.targetPathString;if(null===e)return S("name");if(!this._externals.has(e))if(this.allowExternalFunctionFallbacks){this.mainContentContainer.namedContent.has(e)||n.add(e)}else n.add(e)}}}ObserveVariable(t,e){if(this.IfAsyncWeCant("observe a new variable"),null===this._variableObservers&&(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"),null!==this._variableObservers)if(null!=e){if(this._variableObservers.has(e))if(null!=t){let n=this._variableObservers.get(e);null!=n&&(n.splice(n.indexOf(t),1),0===n.length&&this._variableObservers.delete(e))}else this._variableObservers.delete(e)}else if(null!=t){let e=this._variableObservers.keys();for(let n of e){let e=this._variableObservers.get(n);null!=e&&(e.splice(e.indexOf(t),1),0===e.length&&this._variableObservers.delete(n))}}}VariableStateDidChangeEvent(t,e){if(null===this._variableObservers)return;let n=this._variableObservers.get(t);if(void 0!==n){if(!(e instanceof A))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=a(e,A);for(let e of n)e(t,i.valueObject)}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(t){return this.TagsAtStartOfFlowContainerWithPathString(t)}TagsAtStartOfFlowContainerWithPathString(t){let e=new m(t),n=this.ContentAtPath(e).container;if(null===n)return S("flowContainer");for(;;){let t=n.content[0];if(!(t instanceof L))break;n=t}let i=!1,r=null;for(let t of n.content){let e=s(t,D);if(null!=e)e.commandType==D.CommandType.BeginTag?i=!0:e.commandType==D.CommandType.EndTag&&(i=!1);else{if(!i)break;{let e=s(t,I);null!==e?(null===r&&(r=[]),null!==e.value&&r.push(e.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().")}}}return r}BuildStringOfHierarchy(){let t=new b;return this.mainContentContainer.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}BuildStringOfContainer(t){let e=new b;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=H.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=!1;this.state.callStack.CanPop(v.Function)?(this.state.PopCallStack(v.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new j),t=!0):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),t=!0):this.state.TryExitFunctionEvaluationFromGame(),t&&!this.state.currentPointer.isNull&&this.NextContent()}}IncrementContentPointer(){let t=!0,e=this.state.callStack.currentElement.currentPointer.copy();if(e.index++,null===e.container)return S("pointer.container");for(;e.index>=e.container.content.length;){t=!1;let n=s(e.container.parent,L);if(n instanceof L==!1)break;let i=n.content.indexOf(e.container);if(-1==i)break;if(e=new H(n,i),e.index++,t=!0,null===e.container)return S("pointer.container")}return t||(e=H.Null),this.state.callStack.currentElement.currentPointer=e.copy(),t}TryFollowDefaultInvisibleChoice(){let t=this._state.currentChoices,e=t.filter((t=>t.isInvisibleDefault));if(0==e.length||t.length>e.length)return!1;let n=e[0];return null===n.targetPath?S("choice.targetPath"):null===n.threadAtGeneration?S("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,null!==this._stateSnapshotAtLastNewline&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,!1),!0)}NextSequenceShuffleIndex(){let t=s(this.state.PopEvaluationStack(),N);if(!(t instanceof N))return this.Error("expected number of elements in sequence for shuffle index"),0;let e=this.state.currentPointer.container;if(null===e)return S("seqContainer");if(null===t.value)return S("numElementsIntVal.value");let n=t.value,i=a(this.state.PopEvaluationStack(),N).value;if(null===i)return S("seqCount");let r=i/n,o=i%n,l=e.path.toString(),h=0;for(let t=0,e=l.length;t<e;t++)h+=l.charCodeAt(t)||0;let u=h+r+this.state.storySeed,c=new Yt(Math.floor(u)),d=[];for(let t=0;t<n;++t)d.push(t);for(let t=0;t<=o;++t){let e=c.next()%d.length,n=d[e];if(d.splice(e,1),t==o)return n}throw new Error("Should never reach here")}Error(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=new _(t);throw n.useEndLineNumber=e,n}Warning(t){this.AddError(t,!0)}AddError(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=this.currentDebugMetadata,r=e?"WARNING":"ERROR";if(null!=i){let e=n?i.endLineNumber:i.startLineNumber;t="RUNTIME "+r+": '"+i.fileName+"' line "+e+": "+t}else t=this.state.currentPointer.isNull?"RUNTIME "+r+": "+t:"RUNTIME "+r+": ("+this.state.currentPointer+"): "+t;this.state.AddError(t,e),e||this.state.ForceEnd()}Assert(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(0==t)throw null==e&&(e="Story assert"),new Error(e+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let t,e=this.state.currentPointer;if(!e.isNull&&null!==e.Resolve()&&(t=e.Resolve().debugMetadata,null!==t))return t;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(e=this.state.callStack.elements[n].currentPointer,!e.isNull&&null!==e.Resolve()&&(t=e.Resolve().debugMetadata,null!==t))return t;for(let e=this.state.outputStream.length-1;e>=0;--e){if(t=this.state.outputStream[e].debugMetadata,null!==t)return t}return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};re.inkVersionCurrent=21,function(t){var e;(e=t.OutputStateChange||(t.OutputStateChange={}))[e.NoChange=0]="NoChange",e[e.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",e[e.NewlineRemoved=2]="NewlineRemoved"}(re||(re={}));class se extends dt{get flowLevel(){return at.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(t){var e;super(null,t,null,!1,arguments.length>1&&void 0!==arguments[1]&&arguments[1]),e=this,this._errorHandler=null,this._hadError=!1,this._hadWarning=!1,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=!1,this.ExportRuntime=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;var n,i;e._errorHandler=t,e.constants=new Map;for(const t of e.FindAll(st)()){const n=e.constants.get(t.constantName);if(n&&!n.Equals(t.expression)){const i=`CONST '${t.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 ${n.debugMetadata}.`;e.Error(i,t,!1)}e.constants.set(t.constantName,t.expression)}e._listDefs=new Map;for(const t of e.FindAll(xt)())(null===(n=t.identifier)||void 0===n?void 0:n.name)&&e._listDefs.set(null===(i=t.identifier)||void 0===i?void 0:i.name,t);e.externals=new Map,e.ResolveWeavePointNaming();const r=e.runtimeObject,s=new L;s.AddContent(D.EvalStart());const a=[];for(const[t,n]of e.variableDeclarations)if(n.isGlobalDeclaration){if(n.listDefinition)e._listDefs.set(t,n.listDefinition),s.AddContent(n.listDefinition.runtimeObject),a.push(n.listDefinition.runtimeListDefinition);else{if(!n.expression)throw new Error;n.expression.GenerateIntoContainer(s)}const i=new X(t,!0);i.isGlobal=!0,s.AddContent(i)}s.AddContent(D.EvalEnd()),s.AddContent(D.End()),e.variableDeclarations.size>0&&(s.name="global decl",r.AddToNamedContentOnly(s)),r.AddContent(D.Done());const o=new re(r,a);return e.runtimeObject=o,e.hadError?null:(e.FlattenContainersIn(r),e.ResolveReferences(e),e.hadError?null:(o.ResetState(),o))},this.ResolveList=t=>{let e=this._listDefs.get(t);return e||null},this.ResolveListItem=function(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=null;if(t)return(r=e._listDefs.get(t))?r.ItemNamed(n):null;{let t=null,r=null;for(const[,s]of e._listDefs.entries()){const a=s.ItemNamed(n);a&&(t?e.Error(`Ambiguous item name '${n}' found in multiple sets, including ${r.identifier} and ${s.identifier}`,i,!1):(t=a,r=s))}return t}},this.FlattenContainersIn=t=>{const e=new Set;if(t.content)for(const n of t.content){const t=s(n,L);t&&e.add(t)}if(t.namedContent)for(const[,n]of t.namedContent){const t=s(n,L);t&&e.add(t)}for(const t of e)this.TryFlattenContainer(t),this.FlattenContainersIn(t)},this.TryFlattenContainer=t=>{if(t.namedContent&&t.namedContent.size>0||t.hasValidName||this._dontFlattenContainers.has(t))return;const e=s(t.parent,L);if(e){let n=e.content.indexOf(t);e.content.splice(n,1);const i=t.ownDebugMetadata;if(t.content)for(const r of t.content)r.parent=null,null!==i&&null===r.ownDebugMetadata&&(r.debugMetadata=i),e.InsertContent(r,n),n+=1}},this.Error=(t,e,n)=>{let r=n?i.Warning:i.Error,s="";if(e instanceof p?(s+="TODO: ",r=i.Author):s+=n?"WARNING: ":"ERROR: ",e&&null!==e.debugMetadata&&e.debugMetadata.startLineNumber>=1&&(null!=e.debugMetadata.fileName&&(s+=`'${e.debugMetadata.fileName}' `),s+=`line ${e.debugMetadata.startLineNumber}: `),s+=t,t=s,null===this._errorHandler)throw new Error(t);this._errorHandler(t,r),this._hadError=r===i.Error,this._hadWarning=r===i.Warning},this.ResetError=()=>{this._hadError=!1,this._hadWarning=!1},this.IsExternal=t=>this.externals.has(t),this.AddExternal=t=>{this.externals.has(t.name)?this.Error(`Duplicate EXTERNAL definition of '${t.name}'`,t,!1):t.name&&this.externals.set(t.name,t)},this.DontFlattenContainer=t=>{this._dontFlattenContainers.add(t)},this.NameConflictError=(t,e,n,i)=>{t.Error(`${i} '${e}': name has already been used for a ${n.typeName.toLowerCase()} on ${n.debugMetadata}`)},this.CheckForNamingCollisions=function(t,n,i){var r;const a=(arguments.length>3&&void 0!==arguments[3]?arguments[3]:"")||t.typeName;if(se.IsReservedKeyword(null==n?void 0:n.name))return void t.Error(`'${n}' cannot be used for the name of a ${a.toLowerCase()} because it's a reserved keyword`);if(gt.IsBuiltIn((null==n?void 0:n.name)||""))return void t.Error(`'${n}' cannot be used for the name of a ${a.toLowerCase()} because it's a built in function`);const o=s(e.ContentWithNameAtLevel((null==n?void 0:n.name)||"",at.Knot),dt);if(o&&(o!==t||i===z.Arg))return void e.NameConflictError(t,(null==n?void 0:n.name)||"",o,a);if(i<z.List)return;for(const[i,r]of e._listDefs)if((null==n?void 0:n.name)===i&&t!==r&&r.variableAssignment!==t&&e.NameConflictError(t,null==n?void 0:n.name,r,a),!(t instanceof Gt))for(const i of r.itemDefinitions)(null==n?void 0:n.name)===i.name&&e.NameConflictError(t,(null==n?void 0:n.name)||"",i,a);if(i<=z.Var)return;const l=(null==n?void 0:n.name)&&e.variableDeclarations.get(null==n?void 0:n.name)||null;if(l&&l!==t&&l.isGlobalDeclaration&&null==l.listDefinition&&e.NameConflictError(t,(null==n?void 0:n.name)||"",l,a),i<z.SubFlowAndWeave)return;const h=new lt(n).ResolveFromContext(t);if(h&&h!==t)e.NameConflictError(t,(null==n?void 0:n.name)||"",h,a);else if(!(i<z.Arg)&&i!==z.Arg){let e=s(t,dt);if(e||(e=ut(t)),e&&e.hasParameters&&e.args)for(const i of e.args)if((null===(r=i.identifier)||void 0===r?void 0:r.name)===(null==n?void 0:n.name))return void t.Error(`${a} '${n}': name has already been used for a argument to ${e.identifier} on ${e.debugMetadata}`)}}}get typeName(){return"Story"}PreProcessTopLevelObjects(t){super.PreProcessTopLevelObjects(t);const e=[];for(let n of t)if(n instanceof Vt){const i=n,r=t.indexOf(n);if(t.splice(r,1),i.includedStory){const n=[],s=i.includedStory;if(null!=s.content){for(const t of s.content)t instanceof dt?e.push(t):n.push(t);n.push(new rt("\n")),t.splice(r,0,...n)}}}else;t.splice(0,0,...e)}}se.IsReservedKeyword=t=>{switch(t){case"true":case"false":case"not":case"return":case"else":case"VAR":case"CONST":case"temp":case"LIST":case"function":return!0}return!1};class ae extends V{get isSingleString(){if(1!==this.content.length)return!1;return this.content[0]instanceof rt}constructor(t){super(),this.GenerateIntoContainer=t=>{t.AddContent(D.BeginString());for(const e of this.content)t.AddContent(e.runtimeObject);t.AddContent(D.EndString())},this.toString=()=>{let t="";for(const e of this.content)t+=e;return t},this.AddContent(t)}get typeName(){return"String"}Equals(t){const e=s(t,ae);if(null===e)return!1;if(!this.isSingleString||!e.isSingleString)return!1;return this.toString()===e.toString()}}class oe extends d{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(),this.GenerateRuntimeObject=()=>this.isStart?D.BeginTag():D.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=t,this.inChoice=e}get typeName(){return"Tag"}}class le{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.")}}}class he extends et{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(t){this._fileHandler=t}constructor(e){var n;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,l=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,h=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;if(super(e),n=this,this.ParseStory=()=>{const e=this.StatementsAtLevel(t.StatementLevel.Top);return new se(e,this._rootParser!==this)},this.SeparatedList=(t,e)=>{const n=this.Parse(t);if(null===n)return null;const i=[];for(i.push(n);;){const n=this.BeginRule();if(null===e()){this.FailRule(n);break}const r=this.Parse(t);if(null===r){this.FailRule(n);break}this.SucceedRule(n),i.push(r)}return i},this.CreateDebugMetadata=(t,e)=>{const n=new It;return n.startLineNumber=((null==t?void 0:t.lineIndex)||0)+1,n.endLineNumber=e.lineIndex+1,n.startCharacterNumber=((null==t?void 0:t.characterInLineIndex)||0)+1,n.endCharacterNumber=e.characterInLineIndex+1,n.fileName=this._filename,n},this.RuleDidSucceed=(t,e,n)=>{const i=s(t,d);i&&(i.debugMetadata=this.CreateDebugMetadata(e,n));const r=Array.isArray(t)?t:null;if(null!==r)for(const t of r){s(t,d)&&(t.hasOwnDebugMetadata||(t.debugMetadata=this.CreateDebugMetadata(e,n)))}const a=s(t,ct);null!=a&&(a.debugMetadata=this.CreateDebugMetadata(e,n))},this.OnStringParserError=function(t,e){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];let a=s?"WARNING:":"ERROR:";if(null!==n._filename&&(a+=` '${n._filename}'`),a+=` line ${r+1}: ${t}`,null===n._externalErrorHandler)throw new Error(a);n._externalErrorHandler(a,s?i.Warning:i.Error)},this.AuthorWarning=()=>{this.Whitespace();const t=this.Parse(this.IdentifierWithMetadata);if(null===t||"TODO"!==t.name)return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();const e=this.ParseUntilCharactersFromString("\n\r");return e?new p(e):null},this.ExtendIdentifierCharacterRanges=t=>{const e=he.ListAllCharacterRanges();for(const n of e)t.AddCharacters(n.ToCharacterSet())},this._parsingChoice=!1,this.Choice=()=>{let t=!0,e=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!e){if(e=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),null===e)return null;t=!1}const n=this.Parse(this.BracketedName);this.Whitespace();const i=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=!0;let r=null;const a=this.Parse(this.MixedTextAndLogic);a&&(r=new pt(a));let o=null,l=null;const h=null!==this.ParseString("[");if(h){this.EndTagIfNecessary(r);const t=this.Parse(this.MixedTextAndLogic);null!==t&&(o=new pt(t)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(o);let e=this.Parse(this.MixedTextAndLogic);null!==e&&(l=new pt(e))}this.Whitespace(),this.EndTagIfNecessary(null!=l?l:r);const u=this.Parse(this.MultiDivert);this._parsingChoice=!1,this.Whitespace();const c=!r&&!l&&!o;if(c&&null===u&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),r||!h||o||this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),l||(l=new pt),this.EndTagIfNecessary(l),null!==u)for(const t of u){const e=s(t,St);e&&e.isEmpty||l.AddContent(t)}l.AddContent(new rt("\n"));const d=new Y(r,o,l);return n&&(d.identifier=n),d.indentationDepth=e.length,d.hasWeaveStyleInlineBrackets=h,d.condition=i,d.onceOnly=t,d.isInvisibleDefault=c,d},this.ChoiceCondition=()=>{const t=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return null===t?null:1===t.length?t[0]:new vt(t)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),tt),this.ChoiceSingleCondition=()=>{if(null===this.ParseString("{"))return null;const t=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(t),this.Expect(this.String("}"),"closing '}' for choice condition"),t},this.Gather=()=>{const t=this.Parse(this.GatherDashes);if(null===t)return null;const e=Number(t),n=this.Parse(this.BracketedName),i=new ot(n,e);return this.Newline(),i},this.GatherDashes=()=>{this.Whitespace();let t=0;for(;null!==this.ParseDashNotArrow();)t+=1,this.Whitespace();return 0===t?null:t},this.ParseDashNotArrow=()=>{const t=this.BeginRule();return null===this.ParseString("->")&&"-"===this.ParseSingleCharacter()?this.SucceedRule(t):this.FailRule(t)},this.BracketedName=()=>{if(null===this.ParseString("("))return null;this.Whitespace();const t=this.Parse(this.IdentifierWithMetadata);return null===t?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),t)},this.InnerConditionalContent=e=>{if(void 0===e){const t=this.Parse(this.ConditionExpression),e=this.Parse((()=>this.InnerConditionalContent(t)));return null===e?null:e}let n;const i=null!==e,r=null===this.Parse(this.Newline);if(r&&!i)return null;if(r)n=this.InlineConditionalBranches();else{if(n=this.MultilineConditionalBranches(),null===n){if(e){let e=this.StatementsAtLevel(t.StatementLevel.InnerBlock);if(null!==e){n=[new Nt(e)];const t=this.Parse(this.SingleMultilineCondition);t&&(t.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",t),t.isElse=!0),n.push(t))}}if(null===n)return null}else if(1===n.length&&n[0].isElse&&e){const t=new Nt(null);t.isTrueBranch=!0,n.unshift(t)}if(e){let t=!1;for(let e=0;e<n.length;++e){const i=n[e],r=e===n.length-1;i.ownExpression?(i.matchingEquality=!0,t=!0):t&&r?(i.matchingEquality=!0,i.isElse=!0):!r&&n.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",i):0===e?i.isTrueBranch=!0:i.isElse=!0}}else{for(let t=0;t<n.length;++t){const e=n[t],i=t===n.length-1;if(null===e.ownExpression)if(i)e.isElse=!0;else if(e.isElse){const t=n[n.length-1];t.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",t):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",e)}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",e)}1===n.length&&null===n[0].ownExpression&&this.ErrorWithParsedObject("Condition block with no conditions",n[0])}}if(null===n)return null;for(const t of n)t.isInline=r;return new it(e,n)},this.InlineConditionalBranches=()=>{const t=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,!1);if(null===t||0===t.length)return null;const e=[];if(t.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else{const n=new Nt(t[0]);if(n.isTrueBranch=!0,e.push(n),t.length>1){const n=new Nt(t[1]);n.isElse=!0,e.push(n)}}return e},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();const t=this.OneOrMore(this.SingleMultilineCondition);return null===t?null:(this.MultilineWhitespace(),t)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),null!==this.ParseString("->")||null===this.ParseString("-"))return null;this.Whitespace();let e=null;const n=null!==this.Parse(this.ElseExpression);n||(e=this.Parse(this.ConditionExpression));let i=this.StatementsAtLevel(t.StatementLevel.InnerBlock);null===e&&null===i&&(this.Error("expected content for the conditional branch following '-'"),i=[new rt("")]),this.MultilineWhitespace();const r=new Nt(i);return r.ownExpression=e,r.isElse=n,r},this.ConditionExpression=()=>{const t=this.Parse(this.Expression);return null===t?null:(this.DisallowIncrement(t),this.Whitespace(),null===this.ParseString(":")?null:t)},this.ElseExpression=()=>null===this.ParseString("else")?null:(this.Whitespace(),null===this.ParseString(":")?null:tt),this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(t,e)=>{if(t.length>0){const n=t.length-1,i=t[n];if(i instanceof rt){const r=i;r.text=r.text.replace(new RegExp(/[ \t]+$/g),""),e?r.text+=" ":0===r.text.length&&(t.splice(n,1),this.TrimEndWhitespace(t,!1))}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let t=this.Parse(this.MixedTextAndLogic);if(!t||!t.length)return null;const e=t[0];if(e&&e.text&&e.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),0===t.length)return null;return t[t.length-1]instanceof St||this.TrimEndWhitespace(t,!1),this.EndTagIfNecessary(t),t.length>0&&t[0]instanceof oe&&t[0].isStart||t.push(new rt("\n")),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),t},this.MixedTextAndLogic=()=>{null!==this.ParseObject(this.Spaced(this.String("~")))&&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 t=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){const e=this.Parse(this.MultiDivert);null!==e&&(null===t&&(t=[]),this.EndTagIfNecessary(t),this.TrimEndWhitespace(t,!0),t.push(...e))}return t||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let t=null;for(;;){let e=this.Parse(this.ContentTextNoEscape);const n=null!==this.ParseString("\\");if(!n&&null===e)break;if(null===t&&(t=""),null!==e&&(t+=String(e)),n){t+=this.ParseSingleCharacter()}}return null!==t?new rt(t):null},this.ContentTextNoEscape=()=>{null===this._nonTextPauseCharacters&&(this._nonTextPauseCharacters=new q("-<")),null===this._nonTextEndCharacters&&(this._nonTextEndCharacters=new q("{}|\n\r\\#"),this._notTextEndCharactersChoice=new q(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new q(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let t=null;t=this.parsingStringExpression?this._notTextEndCharactersString:this._parsingChoice?this._notTextEndCharactersChoice:this._nonTextEndCharacters;const e=this.ParseUntil((()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue])),this._nonTextPauseCharacters,t);return null!==e?e:null},this.MultiDivert=()=>{this.Whitespace();let t=[];const e=this.Parse(this.StartThread);if(e)return t=[e],t;const n=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!n)return null;t=[],this.EndTagIfNecessary(t);for(let e=0;e<n.length;++e){if(e%2==0){if("->->"===n[e]){0===e||e===n.length-1||e===n.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");const i=new _t;if(e<n.length-1){const t=s(n[e+1],St);i.divertAfter=t}t.push(i);break}}else{const i=n[e];e<n.length-1&&(i.isTunnel=!0),t.push(i)}}if(0===t.length&&1===n.length){const e=new St(null);e.isEmpty=!0,t.push(e),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices")}return t},this.StartThread=()=>{if(this.Whitespace(),null===this.ParseThreadArrow())return null;this.Whitespace();const t=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",(()=>new St(null)));return t.isThread=!0,t},this.DivertIdentifierWithArguments=()=>{this.Whitespace();const t=this.Parse(this.DotSeparatedDivertPathComponents);if(!t)return null;this.Whitespace();const e=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();const n=new lt(t);return new St(n,e)},this.SingleDivert=()=>{const t=this.Parse(this.MultiDivert);if(!t)return null;if(1!==t.length)return null;if(t[0]instanceof _t)return null;const e=t[0];return e.isTunnel?null:e},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let t=0;for(;null!==this.ParseString("->");)t+=1;return 0===t?null:1===t?"->":(2===t||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();const t=this.ParseTempKeyword();this.Whitespace();let e=null;if(e=t?this.Expect(this.IdentifierWithMetadata,"variable name"):this.Parse(this.IdentifierWithMetadata),null===e)return null;this.Whitespace();const n=null!==this.ParseString("+"),i=null!==this.ParseString("-");if(n&&i&&this.Error("Unexpected sequence '+-'"),null===this.ParseString("="))return t&&this.Error("Expected '='"),null;const r=this.Expect(this.Expression,"value expression to be assigned");if(n||i){return new Dt(e,r,n)}return new At({variableIdentifier:e,assignedExpression:r,isTemporaryNewDeclaration:t})},this.DisallowIncrement=t=>{t instanceof Dt&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line")},this.ParseTempKeyword=()=>{const t=this.BeginRule();return"temp"===this.Parse(this.Identifier)?(this.SucceedRule(t),!0):(this.FailRule(t),!1)},this.ReturnStatement=()=>{this.Whitespace();if("return"!==this.Parse(this.Identifier))return null;this.Whitespace();const t=this.Parse(this.Expression);return new ht(t)},this.Expression=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;n.Whitespace();let e=n.ExpressionUnary();if(null===e)return null;for(n.Whitespace();;){const i=n.BeginRule(),r=n.ParseInfixOperator();if(!(null!==r&&r.precedence>t)){n.FailRule(i);break}{const t=`right side of '${r.type}' expression`,s=n.Expect((()=>n.ExpressionInfixRight(e,r)),t);if(null===s)return n.FailRule(i),null;e=n.SucceedRule(i,s)}}return n.Whitespace(),e},this.ExpressionUnary=()=>{const t=this.Parse(this.ExpressionDivertTarget);if(null!==t)return t;let e=this.OneOf([this.String("-"),this.String("!")]);null===e&&(e=this.Parse(this.ExpressionNot)),this.Whitespace();let n=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(null===n&&null!==e&&(n=this.ExpressionUnary()),null===n)return null;null!==e&&(n=G.WithInner(n,e)),this.Whitespace();const i=this.OneOf([this.String("++"),this.String("--")]);if(null!==i){const t="++"===i;if(n instanceof ft){n=new Dt(n.identifier,t)}else this.Error(`can only increment and decrement variables, but saw '${n}'.`)}return n},this.ExpressionNot=()=>{const t=this.Identifier();return"not"===t?t:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();const t=this.Parse(this.SingleDivert);return!t||t&&t.isThread?null:(this.Whitespace(),new Ct(t))},this.ExpressionInt=()=>{const t=this.ParseInt();return null===t?null:new M(t,"int")},this.ExpressionFloat=()=>{const t=this.ParseFloat();return null===t?null:new M(t,"float")},this.ExpressionString=()=>{if(null===this.ParseString('"'))return null;this.parsingStringExpression=!0;let t=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=!1,null===t?t=[new rt("")]:t.find((t=>t instanceof St))&&this.Error("String expressions cannot contain diverts (->)"),new ae(t)},this.ExpressionBool=()=>{const t=this.Parse(this.Identifier);return"true"===t?new M(!0,"bool"):"false"===t?new M(!1,"bool"):null},this.ExpressionFunctionCall=()=>{const t=this.Parse(this.IdentifierWithMetadata);if(null===t)return null;this.Whitespace();const e=this.Parse(this.ExpressionFunctionCallArguments);return null===e?null:new gt(t,e)},this.ExpressionFunctionCallArguments=()=>{if(null===this.ParseString("("))return null;const t=this.Exclude(this.String(","));let e=this.Interleave(this.Expression,t);return null===e&&(e=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),e},this.ExpressionVariableName=()=>{const t=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return null===t||se.IsReservedKeyword(t[0].name)?null:new ft(t)},this.ExpressionParen=()=>{if(null===this.ParseString("("))return null;const t=this.Parse(this.Expression);return null===t?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),t)},this.ExpressionInfixRight=(t,e)=>{if(!t)return null;this.Whitespace();const n=this.Parse((()=>this.Expression(e.precedence)));if(n){return new $(t,n,e.type)}return null},this.ParseInfixOperator=()=>{for(const t of this._binaryOperators){const e=this.BeginRule();if(null!==this.ParseString(t.type)){if(t.requireWhitespace&&null===this.Whitespace()){this.FailRule(e);continue}return this.SucceedRule(e,t)}this.FailRule(e)}return null},this.ExpressionList=()=>{if(this.Whitespace(),null===this.ParseString("("))return null;this.Whitespace();const t=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),null===this.ParseString(")")?null:new Mt(t)},this.ListMember=()=>{this.Whitespace();let t=this.Parse(this.IdentifierWithMetadata);if(null===t)return null;if(null!==this.ParseString(".")){const e=this.Expect(this.IdentifierWithMetadata,`element name within the set ${t}`);t.name+=`.${null==e?void 0:e.name}`}return this.Whitespace(),t},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,!0),this.RegisterBinaryOperator("or",1,!0),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,!0),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,!0),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,!0)},this.RegisterBinaryOperator=function(t,e){const i=new jt(t,e,arguments.length>2&&void 0!==arguments[2]&&arguments[2]);n._binaryOperators.push(i),n._maxBinaryOpLength=Math.max(n._maxBinaryOpLength,t.length)},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),null===this.ParseString("INCLUDE"))return null;this.Whitespace();let t=this.Expect((()=>this.ParseUntilCharactersFromString("\n\r")),"filename for include statement");t=t.replace(new RegExp(/[ \t]+$/g),"");const e=this.fileHandler.ResolveInkFilename(t);if(this.FilenameIsAlreadyOpen(e))return this.Error(`Recursive INCLUDE detected: '${e}' is already open.`),this.ParseUntilCharactersFromString("\r\n"),new Vt(null);this.AddOpenFilename(e);let n=null,i="";try{i=this._rootParser.fileHandler.LoadInkFileContents(e)}catch(e){this.Error(`Failed to load: '${t}'.\nError:${e}`)}if(null!=i){n=new he(i,t,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()}return this.RemoveOpenFilename(e),new Vt(n)},this.FilenameIsAlreadyOpen=t=>this._rootParser._openFilenames.includes(t),this.AddOpenFilename=t=>{this._rootParser._openFilenames.push(t)},this.RemoveOpenFilename=t=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(t),1)},this.KnotDefinition=()=>{const e=this.Parse(this.KnotDeclaration);if(null===e)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);const n=this.Expect((()=>this.StatementsAtLevel(t.StatementLevel.Knot)),"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new Bt(e.name,n,e.args,e.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),null===this.KnotTitleEquals())return null;this.Whitespace();const t=this.Parse(this.IdentifierWithMetadata);let e;const n="function"===(null==t?void 0:t.name);n?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),e=this.Parse(this.IdentifierWithMetadata)):e=t,null===e&&(this.Error("Expected the name of the "+(n?"function":"knot")),e=new ct("")),this.Whitespace();const i=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new Wt(e,i,n)},this.KnotTitleEquals=()=>{const t=this.ParseCharactersFromString("=");return null===t||t.length<=1?null:t},this.StitchDefinition=()=>{const e=this.Parse(this.StitchDeclaration);if(null===e)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);const n=this.Expect((()=>this.StatementsAtLevel(t.StatementLevel.Stitch)),"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new qt(e.name,n,e.args,e.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),null===this.ParseString("="))return null;if(null!==this.ParseString("="))return null;this.Whitespace();const t=null!==this.ParseString("function");t&&this.Whitespace();const e=this.Parse(this.IdentifierWithMetadata);if(null===e)return null;this.Whitespace();const n=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new Wt(e,n,t)},this.KnotStitchNoContentRecoveryRule=()=>{this.ParseUntil(this.KnotDeclaration,new q("="),null);return[new rt("<ERROR IN FLOW>")]},this.BracketedKnotDeclArguments=()=>{if(null===this.ParseString("("))return null;let t=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),null===t&&(t=[]),t},this.FlowDeclArgument=()=>{const t=this.Parse(this.IdentifierWithMetadata);this.Whitespace();const e=this.ParseDivertArrow();this.Whitespace();const n=this.Parse(this.IdentifierWithMetadata);if(null==t&&null===n)return null;const i=new r;return null!==e&&(i.isDivertTarget=!0),null!==t&&"ref"===t.name?(null===n&&this.Error("Expected an parameter name after 'ref'"),i.identifier=n,i.isByReference=!0):(i.isDivertTarget?i.identifier=n:i.identifier=t,null===i.identifier&&this.Error("Expected an parameter name"),i.isByReference=!1),i},this.ExternalDeclaration=()=>{this.Whitespace();const t=this.Parse(this.IdentifierWithMetadata);if(null===t||"EXTERNAL"!=t.name)return null;this.Whitespace();const e=this.Expect(this.IdentifierWithMetadata,"name of external function")||new ct("");this.Whitespace();let n=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${e}()'`);null===n&&(n=[]);const i=n.map((t=>{var e;return null===(e=t.identifier)||void 0===e?void 0:e.name})).filter(c);return new Ft(e,i)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),null===this.ParseString("~"))return null;this.Whitespace();let t=this.Expect((()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression])),"expression after '~'",this.SkipToNextLine);if(null===t)return new pt;t instanceof V&&!(t instanceof gt||t instanceof Dt)&&this.Error("Logic following a '~' can't be that type of expression. It can only be something like:\n\t~ return\n\t~ var x = blah\n\t~ x++\n\t~ myFunction()");const e=s(t,gt);return e&&(e.shouldPopReturnedValue=!0),null!==t.Find(gt)()&&(t=new pt(t,new rt("\n"))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),t},this.VariableDeclaration=()=>{this.Whitespace();if("VAR"!==this.Parse(this.Identifier))return null;this.Whitespace();const t=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();const e=this.Expect(this.Expression,"initial value for ");if(e){if(e instanceof M||e instanceof ae||e instanceof Ct||e instanceof ft||e instanceof Mt||this.Error("initial value for a variable must be a number, constant, list or divert target"),null!==this.Parse(this.ListElementDefinitionSeparator))this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR");else if(e instanceof ae){e.isSingleString||this.Error("Constant strings cannot contain any logic.")}return new At({assignedExpression:e,isGlobalDeclaration:!0,variableIdentifier:t})}return null},this.ListDeclaration=()=>{this.Whitespace();if("LIST"!=this.Parse(this.Identifier))return null;this.Whitespace();const t=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();const e=this.Expect(this.ListDefinition,"list item names");return e?(e.identifier=new ct(t.name),new At({variableIdentifier:t,listDef:e})):null},this.ListDefinition=()=>{this.AnyWhitespace();const t=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return null===t?null:new xt(t)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),null===this.ParseString(",")?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{const t=null!==this.ParseString("(");let e=t;this.Whitespace();const n=this.Parse(this.IdentifierWithMetadata);if(null===n)return null;this.Whitespace(),t&&null!=this.ParseString(")")&&(e=!1,this.Whitespace());let i=null;if(null!==this.ParseString("=")){this.Whitespace();const t=this.Expect(this.ExpressionInt,"value to be assigned to list item");null!==t&&(i=t.value),e&&(this.Whitespace(),null!==this.ParseString(")")&&(e=!1))}return e&&this.Error("Expected closing ')'"),new Gt(n,t,i)},this.ConstDeclaration=()=>{this.Whitespace();if("CONST"!==this.Parse(this.Identifier))return null;this.Whitespace();const t=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();const e=this.Expect(this.Expression,"initial value for ");if(e instanceof M||e instanceof Ct||e instanceof ae){if(e instanceof ae){e.isSingleString||this.Error("Constant strings cannot contain any logic.")}}else this.Error("initial value for a constant must be a number or divert target");return new st(t,e)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>null!==this.ParseString("<>")?new kt(new Lt):null,this.InlineLogic=()=>{if(null===this.ParseString("{"))return null;let t=this.parsingStringExpression,e=this.tagActive;this.Whitespace();const n=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(null===n)return this.parsingStringExpression=t,null;this.DisallowIncrement(n);let i=s(n,pt);return i||(i=new pt(n)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=t,e||this.EndTagIfNecessary(i),i},this.InnerLogic=()=>{this.Whitespace();const t=this.ParseObject(this.SequenceTypeAnnotation);if(null!==t){const e=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return null===e?null:new Et(e,t)}const e=this.Parse(this.ConditionExpression);if(e){return this.Expect((()=>this.InnerConditionalContent(e)),"conditional content following query")}const n=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(const t of n){const e=this.BeginRule(),n=this.ParseObject(t);if(n){if(null!==this.Peek(this.Spaced(this.String("}"))))return this.SucceedRule(e,n);this.FailRule(e)}else this.FailRule(e)}return null},this.InnerExpression=()=>{const t=this.Parse(this.Expression);return t&&(t.outputWhenComplete=!0),t},this.IdentifierWithMetadata=()=>{const t=this.Identifier();return null===t?null:new ct(t)},this.Identifier=()=>{const t=this.ParseCharactersFromCharSet(this.identifierCharSet);if(null===t)return null;let e=!0;for(let n of t)if(!(n>="0"&&n<="9")){e=!1;break}return e?null:t},this._sequenceTypeSymbols=new q("!&~$"),this.InnerSequence=()=>{this.Whitespace();let t=wt.Stopping;const e=this.Parse(this.SequenceTypeAnnotation);null!==e&&(t=e);const n=this.Parse(this.InnerSequenceObjects);return null===n||n.length<=1?null:new Et(n,t)},this.SequenceTypeAnnotation=()=>{let t=this.Parse(this.SequenceTypeSymbolAnnotation);if(null===t&&(t=this.Parse(this.SequenceTypeWordAnnotation)),null===t)return null;switch(t){case wt.Once:case wt.Cycle:case wt.Stopping:case wt.Shuffle:case wt.Shuffle|wt.Stopping:case wt.Shuffle|wt.Once:break;default:return this.Error(`Sequence type combination not supported: ${t}`),wt.Stopping}return t},this.SequenceTypeSymbolAnnotation=()=>{null===this._sequenceTypeSymbols&&(this._sequenceTypeSymbols=new q("!&~$ "));let t=0;const e=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(null===e)return null;for(const n of e)switch(n){case"!":t|=wt.Once;break;case"&":t|=wt.Cycle;break;case"~":t|=wt.Shuffle;break;case"$":t|=wt.Stopping}return 0===t?null:t},this.SequenceTypeWordAnnotation=()=>{const t=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(null===t||0===t.length)return null;if(null===this.ParseString(":"))return null;let e=0;for(const n of t)e|=n;return e},this.SequenceTypeSingleWord=()=>{let t=null;const e=this.Parse(this.IdentifierWithMetadata);if(null!==e)switch(e.name){case"once":t=wt.Once;break;case"cycle":t=wt.Cycle;break;case"shuffle":t=wt.Shuffle;break;case"stopping":t=wt.Stopping}return null===t?null:t},this.InnerSequenceObjects=()=>{let t=null;return t=null!==this.Parse(this.Newline)?this.Parse(this.InnerMultilineSequenceObjects):this.Parse(this.InnerInlineSequenceObjects),t},this.InnerInlineSequenceObjects=()=>{const t=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,!1);if(null===t)return null;const e=[];let n=!1;for(const i of t)if("|"===i)n||e.push(new pt),n=!1;else{const t=i;null===t?this.Error(`Expected content, but got ${i} (this is an ink compiler bug!)`):e.push(new pt(t)),n=!0}return n||e.push(new pt),e},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();const t=this.OneOrMore(this.SingleMultilineSequenceElement);return null===t?null:t},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),null!==this.ParseString("->"))return null;if(null===this.ParseString("-"))return null;this.Whitespace();const e=this.StatementsAtLevel(t.StatementLevel.InnerBlock);return null===e?this.MultilineWhitespace():e.unshift(new rt("\n")),new pt(e)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=e=>{if(e===t.StatementLevel.InnerBlock){null!==this.Parse(this.GatherDashes)&&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.")}return this.Interleave(this.Optional(this.MultilineWhitespace),(()=>this.StatementAtLevel(e)),(()=>this.StatementsBreakForLevel(e)))},this.StatementAtLevel=e=>{const n=this._statementRulesAtLevel[e],i=this.OneOf(n);return e===t.StatementLevel.Top&&i instanceof ht&&this.Error("should not have return statement outside of a knot"),i},this.StatementsBreakForLevel=t=>{this.Whitespace();const e=this._statementBreakRulesAtLevel[t],n=this.OneOf(e);return null===n?null:n},this.GenerateStatementLevelRules=()=>{const e=Object.values(t.StatementLevel);this._statementRulesAtLevel="f".repeat(e.length).split("f").map((()=>[])),this._statementBreakRulesAtLevel="f".repeat(e.length).split("f").map((()=>[]));for(const n of e){const e=[],i=[];e.push(this.Line(this.MultiDivert)),n>=t.StatementLevel.Top&&e.push(this.KnotDefinition),e.push(this.Line(this.Choice)),e.push(this.Line(this.AuthorWarning)),n>t.StatementLevel.InnerBlock&&e.push(this.Gather),n>=t.StatementLevel.Knot&&e.push(this.StitchDefinition),e.push(this.Line(this.ListDeclaration)),e.push(this.Line(this.VariableDeclaration)),e.push(this.Line(this.ConstDeclaration)),e.push(this.Line(this.ExternalDeclaration)),e.push(this.Line(this.IncludeStatement)),e.push(this.LogicLine),e.push(this.LineOfMixedTextAndLogic),n<=t.StatementLevel.Knot&&i.push(this.KnotDeclaration),n<=t.StatementLevel.Stitch&&i.push(this.StitchDeclaration),n<=t.StatementLevel.InnerBlock&&(i.push(this.ParseDashNotArrow),i.push(this.String("}"))),this._statementRulesAtLevel[n]=e,this._statementBreakRulesAtLevel[n]=i}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString("\n\r"),this.ParseNewline(),tt),this.Line=t=>()=>{const e=this.ParseObject(t);return null===e?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),e)},this.StartTag=()=>{if(this.Whitespace(),null===this.ParseString("#"))return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let t=null;if(this.tagActive){let e=new pt;e.AddContent(new oe(!1)),e.AddContent(new oe(!0)),t=e}else t=new oe(!0);return this.tagActive=!0,this.Whitespace(),t},this._inlineWhitespaceChars=new q(" \t"),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>{this.Whitespace();return null!==this.ParseNewline()?tt:null},this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?tt:null),this.MultilineWhitespace=()=>{let t=this.OneOrMore(this.Newline);if(null===t)return null;return t.length>=1?tt:null},this.Whitespace=()=>null!==this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)?tt:null,this.Spaced=t=>()=>{this.Whitespace();const e=this.ParseObject(t);return null===e?null:(this.Whitespace(),e)},this.AnyWhitespace=()=>{let t=!1;for(;null!==this.OneOf([this.Whitespace,this.MultilineWhitespace]);)t=!0;return t?tt:null},this.MultiSpaced=t=>()=>{this.AnyWhitespace();const e=this.ParseObject(t);return null===e?null:(this.AnyWhitespace(),e)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=a,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=o,this._fileHandler=null===h?new le:h,null===l){if(this._rootParser=this,this._openFilenames=[],null!==this._filename){const t=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(t)}}else this._rootParser=l}PreProcessInputString(t){return new nt(t).Process()}get parsingStringExpression(){return this.GetFlag(Number(Ot.ParsingString))}set parsingStringExpression(t){this.SetFlag(Number(Ot.ParsingString),t)}get tagActive(){return this.GetFlag(Number(Ot.TagActive))}set tagActive(t){this.SetFlag(Number(Ot.TagActive),t)}get identifierCharSet(){return null===this._identifierCharSet&&((this._identifierCharSet=new q).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(t){this.tagActive&&(null!=t&&(t instanceof pt?t.AddContent(new oe(!1)):t.push(new oe(!1))),this.tagActive=!1)}}he.LatinBasic=U.Define("A","z",(new q).AddRange("[","`")),he.LatinExtendedA=U.Define("Ā","ſ"),he.LatinExtendedB=U.Define("ƀ","ɏ"),he.Greek=U.Define("Ͱ","Ͽ",(new q).AddRange("͸","΅").AddCharacters("ʹ͵͸·΋΍΢")),he.Cyrillic=U.Define("Ѐ","ӿ",(new q).AddRange("҂","҉")),he.Armenian=U.Define("԰","֏",(new q).AddCharacters("԰").AddRange("՗","ՠ").AddRange("ֈ","֎")),he.Hebrew=U.Define("֐","׿",new q),he.Arabic=U.Define("؀","ۿ",new q),he.Korean=U.Define("가","힯",new q),he.ListAllCharacterRanges=()=>[he.LatinBasic,he.LatinExtendedA,he.LatinExtendedB,he.Arabic,he.Armenian,he.Cyrillic,he.Greek,he.Hebrew,he.Korean];t.Compiler=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){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new he(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),0===this.errors.length?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var t;for(const e of this.runtimeStory.state.outputStream){const i=s(e,I);if(null!==i){const e=new n((null===(t=i.value)||void 0===t?void 0:t.length)||0,i.debugMetadata,i.value||"unknown");this.debugSourceRanges.push(e)}}},this.DebugMetadataForContentAtOffset=t=>{let e=0,n=null;for(const i of this.debugSourceRanges){if(null!==i.debugMetadata&&(n=i.debugMetadata),t>=e&&t<e+i.length)return n;e+=i.length}return null},this.OnError=(t,e)=>{switch(e){case i.Author:this._authorMessages.push(t);break;case i.Warning:this._warnings.push(t);break;case i.Error:this._errors.push(t)}null!==this.options.errorHandler&&this.options.errorHandler(t,e)},this._inputString=t,this._options=r||new e}},t.CompilerOptions=e,t.InkList=E,t.InkParser=he,t.JsonFileHandler=class{constructor(t){this.fileHierarchy=t,this.ResolveInkFilename=t=>{if(Object.keys(this.fileHierarchy).includes(t))return t;throw new Error(`Cannot locate ${t}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=t=>{if(Object.keys(this.fileHierarchy).includes(t))return this.fileHierarchy[t];throw new Error(`Cannot open ${t}.`)}}},t.Story=re}));
//# sourceMappingURL=ink-full.js.map