@drincs/pixi-vn-ink 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/parser.mjs CHANGED
@@ -1,91 +1,91 @@
1
- import {ZodType}from'zod';var Hl=Object.create;var Vo=Object.defineProperty;var Ul=Object.getOwnPropertyDescriptor;var Kl=Object.getOwnPropertyNames;var Jl=Object.getPrototypeOf,zl=Object.prototype.hasOwnProperty;var C=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var Xl=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Kl(t))!zl.call(s,i)&&i!==e&&Vo(s,i,{get:()=>t[i],enumerable:!(n=Ul(t,i))||n.enumerable});return s};var Bo=(s,t,e)=>(e=s!=null?Hl(Jl(s)):{},Xl(Vo(e,"default",{value:s,enumerable:true}),s));var fs=C(Rn=>{Object.defineProperty(Rn,"__esModule",{value:true});Rn.CompilerOptions=void 0;var ds=class{constructor(t=null,e=[],n=false,i=null,o=null){this.sourceFilename=t,this.pluginNames=e,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=o;}};Rn.CompilerOptions=ds;});var Jo=C(Vn=>{Object.defineProperty(Vn,"__esModule",{value:true});Vn.DebugSourceRange=void 0;var ps=class{constructor(t,e,n){this.length=t,this.debugMetadata=e,this.text=n;}};Vn.DebugSourceRange=ps;});var $e=C(Bn=>{Object.defineProperty(Bn,"__esModule",{value:true});Bn.ErrorType=void 0;var zo;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(zo||(Bn.ErrorType=zo={}));});var Xo=C(Ln=>{Object.defineProperty(Ln,"__esModule",{value:true});Ln.Argument=void 0;var ms=class{constructor(t=null,e=null,n=null){this.identifier=t,this.isByReference=e,this.isDivertTarget=n;}get typeName(){return "Argument"}};Ln.Argument=ms;});var L=C(Q=>{Object.defineProperty(Q,"__esModule",{value:true});Q.filterUndef=Q.isEquatable=Q.nullIfUndefined=Q.asINamedContentOrNull=Q.asBooleanOrThrows=Q.asNumberOrThrows=Q.asOrThrows=Q.asOrNull=void 0;function hh(s,t){return s instanceof t?Yo(s):null}Q.asOrNull=hh;function ch(s,t){if(s instanceof t)return Yo(s);throw new Error(`${s} is not of type ${t}`)}Q.asOrThrows=ch;function dh(s){if(typeof s=="number")return s;throw new Error(`${s} is not a number`)}Q.asNumberOrThrows=dh;function fh(s){if(typeof s=="boolean")return s;throw new Error(`${s} is not a boolean`)}Q.asBooleanOrThrows=fh;function ph(s){return s.hasValidName&&s.name?s:null}Q.asINamedContentOrNull=ph;function mh(s){return typeof s>"u"?null:s}Q.nullIfUndefined=mh;function gh(s){return typeof s=="object"&&typeof s.Equals=="function"}Q.isEquatable=gh;function Yo(s,t){return s}function Ch(s){return s!=null}Q.filterUndef=Ch;});var G=C(Wn=>{Object.defineProperty(Wn,"__esModule",{value:true});Wn.ParsedObject=void 0;var Qo=L(),gs=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=t=>{this.content===null&&(this.content=[]);let e=Array.isArray(t)?t:[t];for(let n of e)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(t))return t},this.InsertContent=(t,e)=>(this.content===null&&(this.content=[]),e.parent=this,this.content.splice(t,0,e),e),this.Find=t=>(e=null)=>{let n=(0, Qo.asOrNull)(this,t);if(n!==null&&(e===null||e(n)===true))return n;if(this.content===null)return null;for(let i of this.content){let o=i.Find&&i.Find(t)(e);if(o)return o}return null},this.FindAll=t=>(e,n)=>{let i=Array.isArray(n)?n:[],o=(0, Qo.asOrNull)(this,t);if(o!==null&&(!e||e(o)===true)&&i.push(o),this.content===null)return [];for(let r of this.content)r.FindAll&&r.FindAll(t)(e,i);return i},this.Warning=(t,e=null)=>{this.Error(t,e,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let t=this;for(;t.parent;)t=t.parent;return t}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(t){this._runtimeObject=t;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let t=[],e=this.parent;for(;e;)t.push(e),e=e.parent;return t=t.reverse(),t}ResolveReferences(t){if(this.content!==null)for(let e of this.content)e.ResolveReferences(t);}Error(t,e=null,n=false){if(e===null&&(e=this),!(e._alreadyHadError&&!n||e._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(t,e,n);else throw new Error(`No parent object to send error to: ${t}`);n?e._alreadyHadWarning=true:e._alreadyHadError=true;}}};Wn.ParsedObject=gs;});var jn=C(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.AuthorWarning=void 0;var vh=G(),Cs=class extends vh.ParsedObject{constructor(t){super(),this.warningMessage=t,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};qn.AuthorWarning=Cs;});var ct=C(He=>{Object.defineProperty(He,"__esModule",{value:true});He.Path=void 0;var ve=class s{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let t=arguments[0];this.componentsString=t;}else if(arguments[0]instanceof s.Component&&arguments[1]instanceof s){let t=arguments[0],e=arguments[1];this._components.push(t),this._components=this._components.concat(e._components);}else if(arguments[0]instanceof Array){let t=arguments[0],e=!!arguments[1];this._components=this._components.concat(t),this._isRelative=e;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let t=this._components.slice(1,this._components.length);return new s(t)}else return s.self}get length(){return this._components.length}get lastComponent(){let t=this._components.length-1;return t>=0?this._components[t]:null}get containsNamedComponent(){for(let t=0,e=this._components.length;t<e;t++)if(!this._components[t].isIndex)return true;return false}static get self(){let t=new s;return t._isRelative=true,t}GetComponent(t){return this._components[t]}PathByAppendingPath(t){let e=new s,n=0;for(let i=0;i<t._components.length&&t._components[i].isParent;++i)n++;for(let i=0;i<this._components.length-n;++i)e._components.push(this._components[i]);for(let i=n;i<t._components.length;++i)e._components.push(t._components[i]);return e}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(t){if(this._components.length=0,this._componentsString=t,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let e=this._componentsString.split(".");for(let n of e)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new s.Component(parseInt(n))):this._components.push(new s.Component(n));}toString(){return this.componentsString}Equals(t){if(t==null||t._components.length!=this._components.length||t.isRelative!=this.isRelative)return false;for(let e=0,n=t._components.length;e<n;e++)if(!t._components[e].Equals(this._components[e]))return false;return true}PathByAppendingComponent(t){let e=new s;return e._components.push(...this._components),e._components.push(t),e}};He.Path=ve;ve.parentId="^";(function(s){class t{constructor(n){this.index=-1,this.name=null,typeof n=="string"?this.name=n:this.index=n;}get isIndex(){return this.index>=0}get isParent(){return this.name==s.parentId}static ToParent(){return new t(s.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}s.Component=t;})(ve||(He.Path=ve={}));});var Ue=C(Mn=>{Object.defineProperty(Mn,"__esModule",{value:true});Mn.Debug=void 0;var Zo;(function(s){function t(n,i,o){e(n instanceof i,o);}s.AssertType=t;function e(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}s.Assert=e;})(Zo||(Mn.Debug=Zo={}));});var it=C(De=>{Object.defineProperty(De,"__esModule",{value:true});De.throwNullException=De.NullException=void 0;var Gn=class extends Error{};De.NullException=Gn;function Dh(s){throw new Gn(`${s} is null or undefined`)}De.throwNullException=Dh;});var dt=C(Hn=>{Object.defineProperty(Hn,"__esModule",{value:true});Hn.InkObject=void 0;var Ee=ct(),Ke=K(),vs=Ue(),Se=L(),$n=it(),Ds=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(t){if(t===null)return null;let e=this.rootContentContainer;if(e){let n=e.ContentAtPath(t).obj;if(n){let i=n.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Ee.Path;else {let t=[],e=this,n=(0, Se.asOrNull)(e.parent,Ke.Container);for(;n!==null;){let i=(0, Se.asINamedContentOrNull)(e);if(i!=null&&i.hasValidName){if(i.name===null)return (0, $n.throwNullException)("namedChild.name");t.unshift(new Ee.Path.Component(i.name));}else t.unshift(new Ee.Path.Component(n.content.indexOf(e)));e=n,n=(0, Se.asOrNull)(n.parent,Ke.Container);}this._path=new Ee.Path(t);}return this._path}ResolvePath(t){if(t===null)return (0, $n.throwNullException)("path");if(t.isRelative){let e=(0, Se.asOrNull)(this,Ke.Container);return e===null&&(vs.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),e=(0, Se.asOrNull)(this.parent,Ke.Container),vs.Debug.Assert(e!==null,"Expected parent to be a container"),vs.Debug.Assert(t.GetComponent(0).isParent),t=t.tail),e===null?(0, $n.throwNullException)("nearestContainer"):e.ContentAtPath(t)}else {let e=this.rootContentContainer;return e===null?(0, $n.throwNullException)("contentContainer"):e.ContentAtPath(t)}}ConvertPathToRelative(t){let e=this.path,n=Math.min(t.length,e.length),i=-1;for(let u=0;u<n;++u){let l=e.GetComponent(u),h=t.GetComponent(u);if(l.Equals(h))i=u;else break}if(i==-1)return t;let o=e.componentCount-1-i,r=[];for(let u=0;u<o;++u)r.push(Ee.Path.Component.ToParent());for(let u=i+1;u<t.componentCount;++u)r.push(t.GetComponent(u));return new Ee.Path(r,true)}CompactPathString(t){let e=null,n=null;return t.isRelative?(n=t.componentsString,e=this.path.PathByAppendingPath(t).componentsString):(n=this.ConvertPathToRelative(t).componentsString,e=t.componentsString),n.length<e.length?n:e}get rootContentContainer(){let t=this;for(;t.parent;)t=t.parent;return (0, Se.asOrNull)(t,Ke.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(t,e,n){t[e]&&(t[e]=null),t[e]=n,t[e]&&(t[e].parent=this);}Equals(t){return t===this}};Hn.InkObject=Ds;});var se=C(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.StringBuilder=void 0;var Es=class{constructor(t){t=typeof t<"u"?t.toString():"",this.string=t;}get Length(){return this.string.length}Append(t){t!==null&&(this.string+=t);}AppendLine(t){typeof t<"u"&&this.Append(t),this.string+=`
2
- `;}AppendFormat(t,...e){this.string+=t.replace(/{(\d+)}/g,(n,i)=>typeof e[i]<"u"?e[i]:n);}toString(){return this.string}Clear(){this.string="";}};Un.StringBuilder=Es;});var pt=C(ye=>{Object.defineProperty(ye,"__esModule",{value:true});ye.InkList=ye.InkListItem=void 0;var Ot=it(),Eh=se(),ft=class s{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let t=arguments[0],e=arguments[1];this.originName=t,this.itemName=e;}else if(arguments[0]){let e=arguments[0].toString().split(".");this.originName=e[0],this.itemName=e[1];}}static get Null(){return new s(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(t){if(t instanceof s){let e=t;return e.itemName==this.itemName&&e.originName==this.originName}return false}copy(){return new s(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let e=JSON.parse(t);if(!s.isLikeInkListItem(e))return s.Null;let n=e;return new s(n.originName,n.itemName)}static isLikeInkListItem(t){return !(typeof t!="object"||!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName")||typeof t.originName!="string"&&typeof t.originName!==null||typeof t.itemName!="string"&&typeof t.itemName!==null)}};ye.InkListItem=ft;var Ss=class s extends Map{constructor(){if(super(arguments[0]instanceof s?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof s){let t=arguments[0],e=t.originNames;e!==null&&(this._originNames=e.slice()),t.origins!==null&&(this.origins=t.origins.slice());}else if(typeof arguments[0]=="string"){let t=arguments[0],e=arguments[1];if(this.SetInitialOriginName(t),e.listDefinitions===null)return (0, Ot.throwNullException)("originStory.listDefinitions");let n=e.listDefinitions.TryListGetDefinition(t,null);if(n.exists){if(n.result===null)return (0, Ot.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+t)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let t=arguments[0];this.Add(t.Key,t.Value);}}static FromString(t,e){var n;if(t==null||t=="")return new s;let i=(n=e.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(t);if(i)return i.value===null?(0, Ot.throwNullException)("listValue.value"):new s(i.value);throw new Error("Could not find the InkListItem from the string '"+t+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(t,e=null){if(t instanceof ft){let n=t;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, Ot.throwNullException)("this.origins");for(let i of this.origins)if(i.name==n.originName){let o=i.TryGetValueForItem(n,0);if(o.exists){this.Add(n,o.result);return}else throw new Error("Could not add the item "+n+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(t!==null){let n=t,i=null;if(this.origins===null)return (0, Ot.throwNullException)("this.origins");for(let o of this.origins){if(n===null)return (0, Ot.throwNullException)("itemName");if(o.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+o.name+" or "+i.name);i=o;}}if(i==null){if(e==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let o=s.FromString(n,e).orderedItems[0];this.Add(o.Key,o.Value);}}else {let o=new ft(i.name,n),r=i.ValueForItem(o);this.Add(o,r);}}}ContainsItemNamed(t){for(let[e]of this)if(ft.fromSerializedKey(e).itemName==t)return true;return false}ContainsKey(t){return this.has(t.serialized())}Add(t,e){let n=t.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${t}`);this.set(n,e);}Remove(t){return this.delete(t.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let t=this.maxItem.Key.originName,e=null;return this.origins.every(n=>n.name==t?(e=n,false):true),e}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let e=ft.fromSerializedKey(t);if(e.originName===null)return (0, Ot.throwNullException)("item.originName");this._originNames.push(e.originName);}}return this._originNames}SetInitialOriginName(t){this._originNames=[t];}SetInitialOriginNames(t){t==null?this._originNames=null:this._originNames=t.slice();}get maxItem(){let t={Key:ft.Null,Value:0};for(let[e,n]of this){let i=ft.fromSerializedKey(e);(t.Key.isNull||n>t.Value)&&(t={Key:i,Value:n});}return t}get minItem(){let t={Key:ft.Null,Value:0};for(let[e,n]of this){let i=ft.fromSerializedKey(e);(t.Key.isNull||n<t.Value)&&(t={Key:i,Value:n});}return t}get inverse(){let t=new s;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let o=ft.fromSerializedKey(n);this.ContainsKey(o)||t.Add(o,i);}return t}get all(){let t=new s;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let o=ft.fromSerializedKey(n);t.set(o.serialized(),i);}return t}Union(t){let e=new s(this);for(let[n,i]of t)e.set(n,i);return e}Intersect(t){let e=new s;for(let[n,i]of this)t.has(n)&&e.set(n,i);return e}HasIntersection(t){for(let[e]of this)if(t.has(e))return true;return false}Without(t){let e=new s(this);for(let[n]of t)e.delete(n);return e}Contains(t){if(typeof t=="string")return this.ContainsItemNamed(t);let e=t;if(e.size==0||this.size==0)return false;for(let[n]of e)if(!this.has(n))return false;return true}GreaterThan(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>t.maxItem.Value}GreaterThanOrEquals(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value}LessThan(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<t.minItem.Value}LessThanOrEquals(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<=t.maxItem.Value&&this.minItem.Value<=t.minItem.Value}MaxAsList(){return this.Count>0?new s(this.maxItem):new s}MinAsList(){return this.Count>0?new s(this.minItem):new s}ListWithSubRange(t,e){if(this.Count==0)return new s;let n=this.orderedItems,i=0,o=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?i=t:t instanceof s&&t.Count>0&&(i=t.minItem.Value),Number.isInteger(e)?o=e:e instanceof s&&e.Count>0&&(o=e.maxItem.Value);let r=new s;r.SetInitialOriginNames(this.originNames);for(let a of n)a.Value>=i&&a.Value<=o&&r.Add(a.Key,a.Value);return r}Equals(t){if(!(t instanceof s)||t.Count!=this.Count)return false;for(let[e]of this)if(!t.has(e))return false;return true}get orderedItems(){let t=new Array;for(let[e,n]of this){let i=ft.fromSerializedKey(e);t.push({Key:i,Value:n});}return t.sort((e,n)=>e.Key.originName===null?(0, Ot.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, Ot.throwNullException)("y.Key.originName"):e.Value==n.Value?e.Key.originName.localeCompare(n.Key.originName):e.Value<n.Value?-1:e.Value>n.Value?1:0),t}get singleItem(){for(let t of this.orderedItems)return t.Key;return null}toString(){let t=this.orderedItems,e=new Eh.StringBuilder;for(let n=0;n<t.length;n++){n>0&&e.Append(", ");let i=t[n].Key;if(i.itemName===null)return (0, Ot.throwNullException)("item.itemName");e.Append(i.itemName);}return e.toString()}valueOf(){return NaN}};ye.InkList=Ss;});var Je=C(Kn=>{Object.defineProperty(Kn,"__esModule",{value:true});Kn.StoryException=void 0;var ys=class extends Error{constructor(t){super(t),this.useEndLineNumber=false,this.message=t,this.name="StoryException";}};Kn.StoryException=ys;});var be=C(Kt=>{Object.defineProperty(Kt,"__esModule",{value:true});Kt.tryParseFloat=Kt.tryParseInt=Kt.tryGetValueFromMap=void 0;function Sh(s,t,e){if(s===null)return {result:e,exists:false};let n=s.get(t);return typeof n>"u"?{result:e,exists:false}:{result:n,exists:true}}Kt.tryGetValueFromMap=Sh;function yh(s,t=0){let e=parseInt(s);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}Kt.tryParseInt=yh;function bh(s,t=0){let e=parseFloat(s);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}Kt.tryParseFloat=bh;});var $=C(H=>{Object.defineProperty(H,"__esModule",{value:true});H.ValueType=H.ListValue=H.VariablePointerValue=H.DivertTargetValue=H.StringValue=H.FloatValue=H.IntValue=H.BoolValue=H.Value=H.AbstractValue=void 0;var tu=dt(),eu=ct(),ae=pt(),Ah=Je(),ze=L(),nu=be(),Dt=it(),Jn=class s extends tu.InkObject{static Create(t,e){if(e){if(e===M.Int&&Number.isInteger(Number(t)))return new Tt(Number(t));if(e===M.Float&&!isNaN(t))return new Nt(Number(t))}if(typeof t=="boolean")return new Ae(!!t);if(typeof t=="string")return new Mt(String(t));if(Number.isInteger(Number(t)))return new Tt(Number(t));if(isNaN(t)){if(t instanceof eu.Path)return new zn((0, ze.asOrThrows)(t,eu.Path));if(t instanceof ae.InkList)return new Xn((0, ze.asOrThrows)(t,ae.InkList))}else return new Nt(Number(t));return null}Copy(){return (0, ze.asOrThrows)(s.Create(this.valueObject),tu.InkObject)}BadCastException(t){return new Ah.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+t)}};H.AbstractValue=Jn;var Pt=class extends Jn{constructor(t){super(),this.value=t;}get valueObject(){return this.value}toString(){return this.value===null?(0, Dt.throwNullException)("Value.value"):this.value.toString()}};H.Value=Pt;var Ae=class extends Pt{constructor(t){super(t||false);}get isTruthy(){return !!this.value}get valueType(){return M.Bool}Cast(t){if(this.value===null)return (0, Dt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==M.Int)return new Tt(this.value?1:0);if(t==M.Float)return new Nt(this.value?1:0);if(t==M.String)return new Mt(this.value?"true":"false");throw this.BadCastException(t)}toString(){return this.value?"true":"false"}};H.BoolValue=Ae;var Tt=class extends Pt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return M.Int}Cast(t){if(this.value===null)return (0, Dt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==M.Bool)return new Ae(this.value!==0);if(t==M.Float)return new Nt(this.value);if(t==M.String)return new Mt(""+this.value);throw this.BadCastException(t)}};H.IntValue=Tt;var Nt=class extends Pt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return M.Float}Cast(t){if(this.value===null)return (0, Dt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==M.Bool)return new Ae(this.value!==0);if(t==M.Int)return new Tt(this.value);if(t==M.String)return new Mt(""+this.value);throw this.BadCastException(t)}};H.FloatValue=Nt;var Mt=class extends Pt{constructor(t){if(super(t||""),this._isNewline=this.value==`
3
- `,this._isInlineWhitespace=true,this.value===null)return (0, Dt.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(e=>e!=" "&&e!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return M.String}get isTruthy(){return this.value===null?(0, Dt.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(t){if(t==this.valueType)return this;if(t==M.Int){let e=(0, nu.tryParseInt)(this.value);if(e.exists)return new Tt(e.result);throw this.BadCastException(t)}if(t==M.Float){let e=(0, nu.tryParseFloat)(this.value);if(e.exists)return new Nt(e.result);throw this.BadCastException(t)}throw this.BadCastException(t)}};H.StringValue=Mt;var zn=class extends Pt{constructor(t=null){super(t);}get valueType(){return M.DivertTarget}get targetPath(){return this.value===null?(0, Dt.throwNullException)("Value.value"):this.value}set targetPath(t){this.value=t;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(t){if(t==this.valueType)return this;throw this.BadCastException(t)}toString(){return "DivertTargetValue("+this.targetPath+")"}};H.DivertTargetValue=zn;var bs=class s extends Pt{constructor(t,e=-1){super(t),this._contextIndex=e;}get contextIndex(){return this._contextIndex}set contextIndex(t){this._contextIndex=t;}get variableName(){return this.value===null?(0, Dt.throwNullException)("Value.value"):this.value}set variableName(t){this.value=t;}get valueType(){return M.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 s(this.variableName,this.contextIndex)}};H.VariablePointerValue=bs;var Xn=class s extends Pt{get isTruthy(){return this.value===null?(0, Dt.throwNullException)("this.value"):this.value.Count>0}get valueType(){return M.List}Cast(t){if(this.value===null)return (0, Dt.throwNullException)("Value.value");if(t==M.Int){let e=this.value.maxItem;return e.Key.isNull?new Tt(0):new Tt(e.Value)}else if(t==M.Float){let e=this.value.maxItem;return e.Key.isNull?new Nt(0):new Nt(e.Value)}else if(t==M.String){let e=this.value.maxItem;return e.Key.isNull?new Mt(""):new Mt(e.Key.toString())}if(t==this.valueType)return this;throw this.BadCastException(t)}constructor(t,e){super(null),!t&&!e?this.value=new ae.InkList:t instanceof ae.InkList?this.value=new ae.InkList(t):t instanceof ae.InkListItem&&typeof e=="number"&&(this.value=new ae.InkList({Key:t,Value:e}));}static RetainListOriginsForAssignment(t,e){let n=(0, ze.asOrNull)(t,s),i=(0, ze.asOrNull)(e,s);if(i&&i.value===null)return (0, Dt.throwNullException)("newList.value");if(n&&n.value===null)return (0, Dt.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};H.ListValue=Xn;var M;(function(s){s[s.Bool=-1]="Bool",s[s.Int=0]="Int",s[s.Float=1]="Float",s[s.List=2]="List",s[s.String=3]="String",s[s.DivertTarget=4]="DivertTarget",s[s.VariablePointer=5]="VariablePointer";})(M||(H.ValueType=M={}));});var iu=C(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.SearchResult=void 0;var _h=K(),As=class s{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof _h.Container?this.obj:null}copy(){let t=new s;return t.obj=this.obj,t.approximate=this.approximate,t}};Yn.SearchResult=As;});var K=C(Ye=>{Object.defineProperty(Ye,"__esModule",{value:true});Ye.Container=void 0;var Fh=$(),ru=it(),wh=se(),_e=dt(),xh=iu(),su=ct(),au=Ue(),Oh=be(),Jt=L(),Xe=class s extends _e.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(t){this.AddContent(t);}get namedOnlyContent(){let t=new Map;for(let[e,n]of this.namedContent){let i=(0, Jt.asOrThrows)(n,_e.InkObject);t.set(e,i);}for(let e of this.content){let n=(0, Jt.asINamedContentOrNull)(e);n!=null&&n.hasValidName&&t.delete(n.name);}return t.size==0&&(t=null),t}set namedOnlyContent(t){let e=this.namedOnlyContent;if(e!=null)for(let[n]of e)this.namedContent.delete(n);if(t!=null)for(let[,n]of t){let i=(0, Jt.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let t=0;return this.visitsShouldBeCounted&&(t|=s.CountFlags.Visits),this.turnIndexShouldBeCounted&&(t|=s.CountFlags.Turns),this.countingAtStartOnly&&(t|=s.CountFlags.CountStartOnly),t==s.CountFlags.CountStartOnly&&(t=0),t}set countFlags(t){let e=t;(e&s.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(e&s.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(e&s.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let t=[],e=this;for(;e instanceof s;)e.content.length>0&&(t.push(new su.Path.Component(0)),e=e.content[0]);return new su.Path(t)}AddContent(t){if(t instanceof Array){let e=t;for(let n of e)this.AddContent(n);}else {let e=t;if(this._content.push(e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}}TryAddNamedContent(t){let e=(0, Jt.asINamedContentOrNull)(t);e!=null&&e.hasValidName&&this.AddToNamedContentOnly(e);}AddToNamedContentOnly(t){au.Debug.AssertType(t,_e.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let e=(0, Jt.asOrThrows)(t,_e.InkObject);if(e.parent=this,t.name===null)return (0, ru.throwNullException)("namedContentObj.name");this.namedContent.set(t.name,t);}ContentAtPath(t,e=0,n=-1){n==-1&&(n=t.length);let i=new xh.SearchResult;i.approximate=false;let o=this,r=this;for(let a=e;a<n;++a){let u=t.GetComponent(a);if(o==null){i.approximate=true;break}let l=o.ContentWithPathComponent(u);if(l==null){i.approximate=true;break}let h=(0, Jt.asOrNull)(l,s);if(a<n-1&&h==null){i.approximate=true;break}r=l,o=h;}return i.obj=r,i}InsertContent(t,e){if(this.content.splice(e,0,t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}AddContentsOfContainer(t){this.content.push(...t.content);for(let e of t.content)e.parent=this,this.TryAddNamedContent(e);}ContentWithPathComponent(t){if(t.isIndex)return t.index>=0&&t.index<this.content.length?this.content[t.index]:null;if(t.isParent)return this.parent;{if(t.name===null)return (0, ru.throwNullException)("component.name");let e=(0, Oh.tryGetValueFromMap)(this.namedContent,t.name,null);return e.exists?(0, Jt.asOrThrows)(e.result,_e.InkObject):null}}BuildStringOfHierarchy(){let t;if(arguments.length==0)return t=new wh.StringBuilder,this.BuildStringOfHierarchy(t,0,null),t.toString();t=arguments[0];let e=arguments[1],n=arguments[2];function i(){for(let a=0;a<4*e;++a)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 a=this.content[r];a instanceof s?a.BuildStringOfHierarchy(t,e,n):(i(),a instanceof Fh.StringValue?(t.Append('"'),t.Append(a.toString().replace(`
4
- `,"\\n")),t.Append('"')):t.Append(a.toString())),r!=this.content.length-1&&t.Append(","),!(a instanceof s)&&a==n&&t.Append(" <---"),t.AppendLine();}let o=new Map;for(let[r,a]of this.namedContent)this.content.indexOf((0, Jt.asOrThrows)(a,_e.InkObject))>=0||o.set(r,a);if(o.size>0){i(),t.AppendLine("-- named: --");for(let[,r]of o)au.Debug.AssertType(r,s,"Can only print out named Containers"),r.BuildStringOfHierarchy(t,e,n),t.AppendLine();}e--,i(),t.Append("]");}};Ye.Container=Xe;(function(s){(function(e){e[e.Start=0]="Start",e[e.Visits=1]="Visits",e[e.Turns=2]="Turns",e[e.CountStartOnly=4]="CountStartOnly";})(s.CountFlags||(s.CountFlags={}));})(Xe||(Ye.Container=Xe={}));});var rt=C(Ze=>{Object.defineProperty(Ze,"__esModule",{value:true});Ze.ControlCommand=void 0;var Ph=dt(),Qe=class s extends Ph.InkObject{get commandType(){return this._commandType}constructor(t=s.CommandType.NotSet){super(),this._commandType=t;}Copy(){return new s(this.commandType)}static EvalStart(){return new s(s.CommandType.EvalStart)}static EvalOutput(){return new s(s.CommandType.EvalOutput)}static EvalEnd(){return new s(s.CommandType.EvalEnd)}static Duplicate(){return new s(s.CommandType.Duplicate)}static PopEvaluatedValue(){return new s(s.CommandType.PopEvaluatedValue)}static PopFunction(){return new s(s.CommandType.PopFunction)}static PopTunnel(){return new s(s.CommandType.PopTunnel)}static BeginString(){return new s(s.CommandType.BeginString)}static EndString(){return new s(s.CommandType.EndString)}static NoOp(){return new s(s.CommandType.NoOp)}static ChoiceCount(){return new s(s.CommandType.ChoiceCount)}static Turns(){return new s(s.CommandType.Turns)}static TurnsSince(){return new s(s.CommandType.TurnsSince)}static ReadCount(){return new s(s.CommandType.ReadCount)}static Random(){return new s(s.CommandType.Random)}static SeedRandom(){return new s(s.CommandType.SeedRandom)}static VisitIndex(){return new s(s.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new s(s.CommandType.SequenceShuffleIndex)}static StartThread(){return new s(s.CommandType.StartThread)}static Done(){return new s(s.CommandType.Done)}static End(){return new s(s.CommandType.End)}static ListFromInt(){return new s(s.CommandType.ListFromInt)}static ListRange(){return new s(s.CommandType.ListRange)}static ListRandom(){return new s(s.CommandType.ListRandom)}static BeginTag(){return new s(s.CommandType.BeginTag)}static EndTag(){return new s(s.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};Ze.ControlCommand=Qe;(function(s){(function(e){e[e.NotSet=-1]="NotSet",e[e.EvalStart=0]="EvalStart",e[e.EvalOutput=1]="EvalOutput",e[e.EvalEnd=2]="EvalEnd",e[e.Duplicate=3]="Duplicate",e[e.PopEvaluatedValue=4]="PopEvaluatedValue",e[e.PopFunction=5]="PopFunction",e[e.PopTunnel=6]="PopTunnel",e[e.BeginString=7]="BeginString",e[e.EndString=8]="EndString",e[e.NoOp=9]="NoOp",e[e.ChoiceCount=10]="ChoiceCount",e[e.Turns=11]="Turns",e[e.TurnsSince=12]="TurnsSince",e[e.ReadCount=13]="ReadCount",e[e.Random=14]="Random",e[e.SeedRandom=15]="SeedRandom",e[e.VisitIndex=16]="VisitIndex",e[e.SequenceShuffleIndex=17]="SequenceShuffleIndex",e[e.StartThread=18]="StartThread",e[e.Done=19]="Done",e[e.End=20]="End",e[e.ListFromInt=21]="ListFromInt",e[e.ListRange=22]="ListRange",e[e.ListRandom=23]="ListRandom",e[e.BeginTag=24]="BeginTag",e[e.EndTag=25]="EndTag",e[e.TOTAL_VALUES=26]="TOTAL_VALUES";})(s.CommandType||(s.CommandType={}));})(Qe||(Ze.ControlCommand=Qe={}));});var Et=C(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.Expression=void 0;var ou=K(),_s=rt(),Th=G(),Fs=class extends Th.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let t=new ou.Container;return t.AddContent(_s.ControlCommand.EvalStart()),this.GenerateIntoContainer(t),this.outputWhenComplete&&t.AddContent(_s.ControlCommand.EvalOutput()),t.AddContent(_s.ControlCommand.EvalEnd()),t},this.GenerateConstantIntoContainer=t=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new ou.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let e of this._prototypeRuntimeConstantExpression.content){let n=e.Copy();n&&t.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(t){return false}};Qn.Expression=Fs;});var oe=C(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.Void=void 0;var Nh=dt(),ws=class extends Nh.InkObject{toString(){return "Void"}};Zn.Void=ws;});var It=C(ei=>{Object.defineProperty(ei,"__esModule",{value:true});ei.NativeFunctionCall=void 0;var b=$(),tn=Je(),Ih=oe(),ti=pt(),kh=dt(),St=L(),mt=it(),I=class s extends kh.InkObject{static CallWithName(t){return new s(t)}static CallExistsWithName(t){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(t)}get name(){return this._name===null?(0, mt.throwNullException)("NativeFunctionCall._name"):this._name}set name(t){this._name=t,this._isPrototype||(s._nativeFunctions===null?(0, mt.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=s._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(t){this._numberOfParameters=t;}Call(t){if(this._prototype)return this._prototype.Call(t);if(this.numberOfParameters!=t.length)throw new Error("Unexpected number of parameters");let e=false;for(let o of t){if(o instanceof Ih.Void)throw new tn.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');o instanceof b.ListValue&&(e=true);}if(t.length==2&&e)return this.CallBinaryListOperation(t);let n=this.CoerceValuesToSingleType(t),i=n[0].valueType;return i==b.ValueType.Int?this.CallType(n):i==b.ValueType.Float?this.CallType(n):i==b.ValueType.String?this.CallType(n):i==b.ValueType.DivertTarget?this.CallType(n):i==b.ValueType.List?this.CallType(n):null}CallType(t){let e=(0, St.asOrThrows)(t[0],b.Value),n=e.valueType,i=e,o=t.length;if(o==2||o==1){if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(n);if(!r){let a=b.ValueType[n];throw new tn.StoryException("Cannot perform operation "+this.name+" on "+a)}if(o==2){let u=(0, St.asOrThrows)(t[1],b.Value),l=r;if(i.value===null||u.value===null)return (0, mt.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=l(i.value,u.value);return b.Value.Create(h)}else {let a=r;if(i.value===null)return (0, mt.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=a(i.value);return this.name===s.Int?b.Value.Create(u,b.ValueType.Int):this.name===s.Float?b.Value.Create(u,b.ValueType.Float):b.Value.Create(u,e.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+t.length)}CallBinaryListOperation(t){if((this.name=="+"||this.name=="-")&&t[0]instanceof b.ListValue&&t[1]instanceof b.IntValue)return this.CallListIncrementOperation(t);let e=(0, St.asOrThrows)(t[0],b.Value),n=(0, St.asOrThrows)(t[1],b.Value);if((this.name=="&&"||this.name=="||")&&(e.valueType!=b.ValueType.List||n.valueType!=b.ValueType.List)){if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(b.ValueType.Int);if(i===null)return (0, mt.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let o=(0, St.asBooleanOrThrows)(i(e.isTruthy?1:0,n.isTruthy?1:0));return new b.BoolValue(o)}if(e.valueType==b.ValueType.List&&n.valueType==b.ValueType.List)return this.CallType([e,n]);throw new tn.StoryException("Can not call use "+this.name+" operation on "+b.ValueType[e.valueType]+" and "+b.ValueType[n.valueType])}CallListIncrementOperation(t){let e=(0, St.asOrThrows)(t[0],b.ListValue),n=(0, St.asOrThrows)(t[1],b.IntValue),i=new ti.InkList;if(e.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[o,r]of e.value){let a=ti.InkListItem.fromSerializedKey(o);if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(b.ValueType.Int);if(n.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(r,n.value),h=null;if(e.value.origins===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of e.value.origins)if(c.name==a.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(l,ti.InkListItem.Null);c.exists&&i.Add(c.result,l);}}return new b.ListValue(i)}CoerceValuesToSingleType(t){let e=b.ValueType.Int,n=null;for(let o of t){let r=(0, St.asOrThrows)(o,b.Value);r.valueType>e&&(e=r.valueType),r.valueType==b.ValueType.List&&(n=(0, St.asOrNull)(r,b.ListValue));}let i=[];if(b.ValueType[e]==b.ValueType[b.ValueType.List])for(let o of t){let r=(0, St.asOrThrows)(o,b.Value);if(r.valueType==b.ValueType.List)i.push(r);else if(r.valueType==b.ValueType.Int){let a=parseInt(r.valueObject);if(n=(0, St.asOrThrows)(n,b.ListValue),n.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=n.value.originOfMaxItem;if(u===null)return (0, mt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(a,ti.InkListItem.Null);if(l.exists){let h=new b.ListValue(l.result,a);i.push(h);}else throw new tn.StoryException("Could not find List item with the value "+a+" in "+u.name)}else {let a=b.ValueType[r.valueType];throw new tn.StoryException("Cannot mix Lists and "+a+" values in this operation")}}else for(let o of t){let a=(0, St.asOrThrows)(o,b.Value).Cast(e);i.push(a);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)s.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let t=arguments[0];s.GenerateNativeFunctionsIfNecessary(),this.name=t;}else if(arguments.length===2){let t=arguments[0],e=arguments[1];this._isPrototype=true,this.name=t,this.numberOfParameters=e;}}static Identity(t){return t}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,i)=>n+i),this.AddIntBinaryOp(this.Subtract,(n,i)=>n-i),this.AddIntBinaryOp(this.Multiply,(n,i)=>n*i),this.AddIntBinaryOp(this.Divide,(n,i)=>Math.floor(n/i)),this.AddIntBinaryOp(this.Mod,(n,i)=>n%i),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,i)=>n==i),this.AddIntBinaryOp(this.Greater,(n,i)=>n>i),this.AddIntBinaryOp(this.Less,(n,i)=>n<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddIntBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddIntBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddIntBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddIntBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddIntBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddIntUnaryOp(this.Floor,s.Identity),this.AddIntUnaryOp(this.Ceiling,s.Identity),this.AddIntUnaryOp(this.Int,s.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,i)=>n+i),this.AddFloatBinaryOp(this.Subtract,(n,i)=>n-i),this.AddFloatBinaryOp(this.Multiply,(n,i)=>n*i),this.AddFloatBinaryOp(this.Divide,(n,i)=>n/i),this.AddFloatBinaryOp(this.Mod,(n,i)=>n%i),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,i)=>n==i),this.AddFloatBinaryOp(this.Greater,(n,i)=>n>i),this.AddFloatBinaryOp(this.Less,(n,i)=>n<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddFloatBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddFloatBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddFloatBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddFloatBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,s.Identity),this.AddStringBinaryOp(this.Add,(n,i)=>n+i),this.AddStringBinaryOp(this.Equal,(n,i)=>n===i),this.AddStringBinaryOp(this.NotEquals,(n,i)=>n!==i),this.AddStringBinaryOp(this.Has,(n,i)=>n.includes(i)),this.AddStringBinaryOp(this.Hasnt,(n,i)=>!n.includes(i)),this.AddListBinaryOp(this.Add,(n,i)=>n.Union(i)),this.AddListBinaryOp(this.Subtract,(n,i)=>n.Without(i)),this.AddListBinaryOp(this.Has,(n,i)=>n.Contains(i)),this.AddListBinaryOp(this.Hasnt,(n,i)=>!n.Contains(i)),this.AddListBinaryOp(this.Intersect,(n,i)=>n.Intersect(i)),this.AddListBinaryOp(this.Equal,(n,i)=>n.Equals(i)),this.AddListBinaryOp(this.Greater,(n,i)=>n.GreaterThan(i)),this.AddListBinaryOp(this.Less,(n,i)=>n.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,i)=>n.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(n,i)=>n.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(n,i)=>!n.Equals(i)),this.AddListBinaryOp(this.And,(n,i)=>n.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(n,i)=>n.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let t=(n,i)=>n.Equals(i),e=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,b.ValueType.DivertTarget,t),this.AddOpToNativeFunc(this.NotEquals,2,b.ValueType.DivertTarget,e);}}AddOpFuncForType(t,e){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(t,e);}static AddOpToNativeFunc(t,e,n,i){if(this._nativeFunctions===null)return (0, mt.throwNullException)("NativeFunctionCall._nativeFunctions");let o=this._nativeFunctions.get(t);o||(o=new s(t,e),this._nativeFunctions.set(t,o)),o.AddOpFuncForType(n,i);}static AddIntBinaryOp(t,e){this.AddOpToNativeFunc(t,2,b.ValueType.Int,e);}static AddIntUnaryOp(t,e){this.AddOpToNativeFunc(t,1,b.ValueType.Int,e);}static AddFloatBinaryOp(t,e){this.AddOpToNativeFunc(t,2,b.ValueType.Float,e);}static AddFloatUnaryOp(t,e){this.AddOpToNativeFunc(t,1,b.ValueType.Float,e);}static AddStringBinaryOp(t,e){this.AddOpToNativeFunc(t,2,b.ValueType.String,e);}static AddListBinaryOp(t,e){this.AddOpToNativeFunc(t,2,b.ValueType.List,e);}static AddListUnaryOp(t,e){this.AddOpToNativeFunc(t,1,b.ValueType.List,e);}toString(){return 'Native "'+this.name+'"'}};ei.NativeFunctionCall=I;I.Add="+";I.Subtract="-";I.Divide="/";I.Multiply="*";I.Mod="%";I.Negate="_";I.Equal="==";I.Greater=">";I.Less="<";I.GreaterThanOrEquals=">=";I.LessThanOrEquals="<=";I.NotEquals="!=";I.Not="!";I.And="&&";I.Or="||";I.Min="MIN";I.Max="MAX";I.Pow="POW";I.Floor="FLOOR";I.Ceiling="CEILING";I.Int="INT";I.Float="FLOAT";I.Has="?";I.Hasnt="!?";I.Intersect="^";I.ListMin="LIST_MIN";I.ListMax="LIST_MAX";I.All="LIST_ALL";I.Count="LIST_COUNT";I.ValueOfList="LIST_VALUE";I.Invert="LIST_INVERT";I._nativeFunctions=null;});var ii=C(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.NumberExpression=void 0;var Rh=Et(),xs=$(),Vh=L(),Os=class s extends Rh.Expression{constructor(t,e){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new xs.IntValue(this.value)):this.isFloat()?n.AddContent(new xs.FloatValue(this.value)):this.isBool()&&n.AddContent(new xs.BoolValue(this.value));},this.toString=()=>String(this.value),typeof t=="number"&&!Number.isNaN(t)||typeof t=="boolean")this.value=t,this.subtype=e;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(t){let e=(0, Vh.asOrNull)(t,s);return e?e.subtype==this.subtype&&e.value==this.value:false}};ni.NumberExpression=Os;});var Ps=C(ri=>{Object.defineProperty(ri,"__esModule",{value:true});ri.UnaryExpression=void 0;var Bh=Et(),Lh=It(),Fe=ii(),Wh=L(),en=class extends Bh.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(t,e){super(),this.op=e,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(Lh.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(t);}get typeName(){return "UnaryExpression"}};ri.UnaryExpression=en;en.WithInner=(s,t)=>{let e=(0, Wh.asOrNull)(s,Fe.NumberExpression);if(e){if(t==="-"){if(e.isInt())return new Fe.NumberExpression(-e.value,"int");if(e.isFloat())return new Fe.NumberExpression(-e.value,"float")}else if(t=="!"||t=="not"){if(e.isInt())return new Fe.NumberExpression(e.value==0,"bool");if(e.isFloat())return new Fe.NumberExpression(e.value==0,"bool");if(e.isBool())return new Fe.NumberExpression(!e.value,"bool")}throw new Error("Unexpected operation or number type")}return new en(s,t)};});var Ns=C(si=>{Object.defineProperty(si,"__esModule",{value:true});si.BinaryExpression=void 0;var qh=Et(),jh=It(),Mh=Ps(),Gh=L(),Ts=class extends qh.Expression{constructor(t,e,n){super(),this.opName=n,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(jh.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(t),this.rightExpression=this.AddContent(e),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(t){if(super.ResolveReferences(t),this.NativeNameForOp(this.opName)==="?"){let e=(0, Gh.asOrNull)(this.leftExpression,Mh.UnaryExpression);e!==null&&(e.op==="not"||e.op==="!")&&this.Error(`Using 'not' or '!' here negates '${e.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};si.BinaryExpression=Ts;});var rn=C(ai=>{Object.defineProperty(ai,"__esModule",{value:true});ai.CharacterSet=void 0;var nn=class{constructor(t){this.set=new Set,this.Add=e=>this.set.add(e),this.AddRange=(e,n)=>{for(let i=e.charCodeAt(0);i<=n.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=e=>{if(typeof e=="string"||Array.isArray(e))for(let n of e)this.Add(n);else for(let n of e.set)this.Add(n);return this},t&&this.AddCharacters(t);}};ai.CharacterSet=nn;nn.FromRange=(s,t)=>new nn().AddRange(s,t);});var lu=C(oi=>{Object.defineProperty(oi,"__esModule",{value:true});oi.CharacterRange=void 0;var uu=rn(),sn=class{constructor(t,e,n=[]){if(this._start=t,this._end=e,this._correspondingCharSet=new uu.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),o;i<=this.end.charCodeAt(0);i+=1)o=String.fromCharCode(i),this._excludes.has(o)||this._correspondingCharSet.AddCharacters(o);return this._correspondingCharSet},n instanceof uu.CharacterSet)this._excludes=n.set;else for(let i of n)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};oi.CharacterRange=sn;sn.Define=(s,t,e=[])=>new sn(s,t,e);});var li=C(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.ChoicePoint=void 0;var $h=dt(),Hh=ct(),Is=it(),ks=class extends $h.InkObject{constructor(t=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=t;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path);}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t;}get choiceTarget(){return this._pathOnChoice===null?(0, Is.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Is.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new Hh.Path(t);}get flags(){let t=0;return this.hasCondition&&(t|=1),this.hasStartContent&&(t|=2),this.hasChoiceOnlyContent&&(t|=4),this.isInvisibleDefault&&(t|=8),this.onceOnly&&(t|=16),t}set flags(t){this.hasCondition=(t&1)>0,this.hasStartContent=(t&2)>0,this.hasChoiceOnlyContent=(t&4)>0,this.isInvisibleDefault=(t&8)>0,this.onceOnly=(t&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Is.throwNullException)("ChoicePoint.pathOnChoice");let e=this.pathOnChoice.toString();return "Choice: -> "+e}};ui.ChoicePoint=ks;});var ue=C(hi=>{Object.defineProperty(hi,"__esModule",{value:true});hi.PushPopType=void 0;var hu;(function(s){s[s.Tunnel=0]="Tunnel",s[s.Function=1]="Function",s[s.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(hu||(hi.PushPopType=hu={}));});var an=C(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.Pointer=void 0;var Uh=ct(),Rs=class s{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new Uh.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new s(this.container,this.index)}static StartOf(t){return new s(t,0)}static get Null(){return new s(null,-1)}};ci.Pointer=Rs;});var kt=C(fi=>{Object.defineProperty(fi,"__esModule",{value:true});fi.Divert=void 0;var Kh=ct(),Jh=ue(),zh=se(),Xh=dt(),Vs=an(),cu=K(),di=it(),Bs=class s extends Xh.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let t=this.targetPointer.Resolve();t&&(this._targetPath=t.path);}return this._targetPath}set targetPath(t){this._targetPath=t,this._targetPointer=Vs.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let t=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, di.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, di.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(t===null)return (0, di.throwNullException)("targetObj");this._targetPointer.container=t.parent instanceof cu.Container?t.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Vs.Pointer.StartOf(t instanceof cu.Container?t:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(t){t==null?this.targetPath=null:this.targetPath=new Kh.Path(t);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(t){super(),this._targetPath=null,this._targetPointer=Vs.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof t<"u"&&(this.pushesToStack=true,this.stackPushType=t);}Equals(t){let e=t;return e instanceof s&&this.hasVariableTarget==e.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==e.variableDivertName:this.targetPath===null?(0, di.throwNullException)("this.targetPath"):this.targetPath.Equals(e.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let t=new zh.StringBuilder,e=this.targetPath.toString();return t.Append("Divert"),this.isConditional&&t.Append("?"),this.pushesToStack&&(this.stackPushType==Jh.PushPopType.Function?t.Append(" function"):t.Append(" tunnel")),t.Append(" -> "),t.Append(this.targetPathString),t.Append(" ("),t.Append(e),t.Append(")"),t.toString()}}};fi.Divert=Bs;});var Gt=C(pi=>{Object.defineProperty(pi,"__esModule",{value:true});pi.SymbolType=void 0;var du;(function(s){s[s.Knot=0]="Knot",s[s.List=1]="List",s[s.ListItem=2]="ListItem",s[s.Var=3]="Var",s[s.SubFlowAndWeave=4]="SubFlowAndWeave",s[s.Arg=5]="Arg",s[s.Temp=6]="Temp";})(du||(pi.SymbolType=du={}));});var zt=C(mi=>{Object.defineProperty(mi,"__esModule",{value:true});mi.VariableAssignment=void 0;var Yh=dt(),Ls=class extends Yh.InkObject{constructor(t,e){super(),this.variableName=t||null,this.isNewDeclaration=!!e,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};mi.VariableAssignment=Ls;});var we=C(Ci=>{Object.defineProperty(Ci,"__esModule",{value:true});Ci.Choice=void 0;var Qh=li(),gi=K(),Xt=rt(),Ws=kt(),fu=$(),Zh=G(),tc=Gt(),pu=zt(),qs=class extends Zh.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get condition(){return this._condition}set condition(t){this._condition=t,t&&this.AddContent(t);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(t,e,n){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new gi.Container,this._runtimeChoice=new Qh.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Xt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new fu.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new pu.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Xt.ControlCommand.BeginString()),this._divertToStartContentOuter=new Ws.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let o=new Ws.Divert;o.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(o),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new gi.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Xt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Xt.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Xt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Xt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new gi.Container,this.startContent){this._returnToR2=new fu.DivertTargetValue,this._innerContentContainer.AddContent(Xt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Xt.ControlCommand.EvalEnd());let i=new pu.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Ws.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new gi.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=t,this.choiceOnlyContent=e,this.innerContent=n,this.indentationDepth=1,t&&this.AddContent(this.startContent),e&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(t){var e;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(t),this.identifier&&(((e=this.identifier)===null||e===void 0?void 0:e.name)||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,tc.SymbolType.SubFlowAndWeave);}};Ci.Choice=qs;});var mu=C(Di=>{Object.defineProperty(Di,"__esModule",{value:true});Di.StringParserElement=void 0;var vi=class s{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=t=>{s._uniqueIdCounter++,this.uniqueId=s._uniqueIdCounter,this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.customFlags=t.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=t=>{this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.reportedErrorInScope=t.reportedErrorInScope,this.customFlags=t.customFlags;};}};Di.StringParserElement=vi;vi._uniqueIdCounter=1e3;});var Cu=C(Ei=>{Object.defineProperty(Ei,"__esModule",{value:true});Ei.StringParserState=void 0;var gu=mu(),js=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(t){this.currentElement.lineIndex=t;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(t){this.currentElement.characterIndex=t;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(t){this.currentElement.characterInLineIndex=t;}get customFlags(){return this.currentElement.customFlags}set customFlags(t){this.currentElement.customFlags=t;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new gu.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let e=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(e),n.uniqueId},this.Pop=e=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=e)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=e=>{if(this.currentElement.uniqueId!=e)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let e=this._stack[this._numElements-2],n=this._stack[this._numElements-1];e.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let e of this._stack)e.reportedErrorInScope=true;};let t=200;for(let e=0;e<t;e++)this._stack[e]=new gu.StringParserElement;this._numElements=1;}};Ei.StringParserState=js;});var Gs=C(le=>{Object.defineProperty(le,"__esModule",{value:true});le.StringParser=le.ParseSuccess=void 0;var Ms=rn(),ec=Cu();le.ParseSuccess=Symbol("ParseSuccessStruct");var on=class s{constructor(t){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=n=>(this.state.Pop(n),null),this.CancelRule=n=>{this.state.Pop(n);},this.SucceedRule=(n,i=null)=>{let o=this.state.Peek(n),r=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,r,o),this.state.Squash();let a=i;return a===null&&(a=s.ParseSuccess),a},this.Expect=(n,i=null,o=null)=>{let r=this.ParseObject(n);if(r===null){i===null&&(i=n.name);let a,u=this.LineRemainder();u===null||u.length===0?a="end of line":a=`'${u}'`,this.Error(`Expected ${i} but saw ${a}`),o!==null&&(r=o());}return r},this.Error=(n,i=false)=>{this.ErrorOnLine(n,this.lineIndex+1,i);},this.ErrorWithParsedObject=(n,i,o=false)=>{this.ErrorOnLine(n,i.debugMetadata?i.debugMetadata.startLineNumber:-1,o);},this.ErrorOnLine=(n,i,o)=>{if(!this.state.errorReportedAlreadyInScope){let r=o?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,i-1,o);else throw new Error(`${r} on line ${i}: ${n}`);this.state.NoteErrorReported();}o||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
1
+ import {ZodType}from'zod';import em from'ajv';var Ul=Object.create;var Vo=Object.defineProperty;var Kl=Object.getOwnPropertyDescriptor;var Jl=Object.getOwnPropertyNames;var zl=Object.getPrototypeOf,Xl=Object.prototype.hasOwnProperty;var C=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var Yl=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Jl(t))!Xl.call(s,i)&&i!==e&&Vo(s,i,{get:()=>t[i],enumerable:!(n=Kl(t,i))||n.enumerable});return s};var Bo=(s,t,e)=>(e=s!=null?Ul(zl(s)):{},Yl(Vo(e,"default",{value:s,enumerable:true}),s));var ps=C(Vn=>{Object.defineProperty(Vn,"__esModule",{value:true});Vn.CompilerOptions=void 0;var fs=class{constructor(t=null,e=[],n=false,i=null,o=null){this.sourceFilename=t,this.pluginNames=e,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=o;}};Vn.CompilerOptions=fs;});var Jo=C(Bn=>{Object.defineProperty(Bn,"__esModule",{value:true});Bn.DebugSourceRange=void 0;var ms=class{constructor(t,e,n){this.length=t,this.debugMetadata=e,this.text=n;}};Bn.DebugSourceRange=ms;});var He=C(Ln=>{Object.defineProperty(Ln,"__esModule",{value:true});Ln.ErrorType=void 0;var zo;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(zo||(Ln.ErrorType=zo={}));});var Xo=C(Wn=>{Object.defineProperty(Wn,"__esModule",{value:true});Wn.Argument=void 0;var gs=class{constructor(t=null,e=null,n=null){this.identifier=t,this.isByReference=e,this.isDivertTarget=n;}get typeName(){return "Argument"}};Wn.Argument=gs;});var W=C(Q=>{Object.defineProperty(Q,"__esModule",{value:true});Q.filterUndef=Q.isEquatable=Q.nullIfUndefined=Q.asINamedContentOrNull=Q.asBooleanOrThrows=Q.asNumberOrThrows=Q.asOrThrows=Q.asOrNull=void 0;function ch(s,t){return s instanceof t?Yo(s):null}Q.asOrNull=ch;function dh(s,t){if(s instanceof t)return Yo(s);throw new Error(`${s} is not of type ${t}`)}Q.asOrThrows=dh;function fh(s){if(typeof s=="number")return s;throw new Error(`${s} is not a number`)}Q.asNumberOrThrows=fh;function ph(s){if(typeof s=="boolean")return s;throw new Error(`${s} is not a boolean`)}Q.asBooleanOrThrows=ph;function mh(s){return s.hasValidName&&s.name?s:null}Q.asINamedContentOrNull=mh;function gh(s){return typeof s>"u"?null:s}Q.nullIfUndefined=gh;function Ch(s){return typeof s=="object"&&typeof s.Equals=="function"}Q.isEquatable=Ch;function Yo(s,t){return s}function vh(s){return s!=null}Q.filterUndef=vh;});var $=C(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.ParsedObject=void 0;var Qo=W(),Cs=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=t=>{this.content===null&&(this.content=[]);let e=Array.isArray(t)?t:[t];for(let n of e)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(t))return t},this.InsertContent=(t,e)=>(this.content===null&&(this.content=[]),e.parent=this,this.content.splice(t,0,e),e),this.Find=t=>(e=null)=>{let n=(0, Qo.asOrNull)(this,t);if(n!==null&&(e===null||e(n)===true))return n;if(this.content===null)return null;for(let i of this.content){let o=i.Find&&i.Find(t)(e);if(o)return o}return null},this.FindAll=t=>(e,n)=>{let i=Array.isArray(n)?n:[],o=(0, Qo.asOrNull)(this,t);if(o!==null&&(!e||e(o)===true)&&i.push(o),this.content===null)return [];for(let r of this.content)r.FindAll&&r.FindAll(t)(e,i);return i},this.Warning=(t,e=null)=>{this.Error(t,e,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let t=this;for(;t.parent;)t=t.parent;return t}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(t){this._runtimeObject=t;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let t=[],e=this.parent;for(;e;)t.push(e),e=e.parent;return t=t.reverse(),t}ResolveReferences(t){if(this.content!==null)for(let e of this.content)e.ResolveReferences(t);}Error(t,e=null,n=false){if(e===null&&(e=this),!(e._alreadyHadError&&!n||e._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(t,e,n);else throw new Error(`No parent object to send error to: ${t}`);n?e._alreadyHadWarning=true:e._alreadyHadError=true;}}};qn.ParsedObject=Cs;});var Mn=C(jn=>{Object.defineProperty(jn,"__esModule",{value:true});jn.AuthorWarning=void 0;var Dh=$(),vs=class extends Dh.ParsedObject{constructor(t){super(),this.warningMessage=t,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};jn.AuthorWarning=vs;});var ct=C(Ue=>{Object.defineProperty(Ue,"__esModule",{value:true});Ue.Path=void 0;var ve=class s{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let t=arguments[0];this.componentsString=t;}else if(arguments[0]instanceof s.Component&&arguments[1]instanceof s){let t=arguments[0],e=arguments[1];this._components.push(t),this._components=this._components.concat(e._components);}else if(arguments[0]instanceof Array){let t=arguments[0],e=!!arguments[1];this._components=this._components.concat(t),this._isRelative=e;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let t=this._components.slice(1,this._components.length);return new s(t)}else return s.self}get length(){return this._components.length}get lastComponent(){let t=this._components.length-1;return t>=0?this._components[t]:null}get containsNamedComponent(){for(let t=0,e=this._components.length;t<e;t++)if(!this._components[t].isIndex)return true;return false}static get self(){let t=new s;return t._isRelative=true,t}GetComponent(t){return this._components[t]}PathByAppendingPath(t){let e=new s,n=0;for(let i=0;i<t._components.length&&t._components[i].isParent;++i)n++;for(let i=0;i<this._components.length-n;++i)e._components.push(this._components[i]);for(let i=n;i<t._components.length;++i)e._components.push(t._components[i]);return e}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(t){if(this._components.length=0,this._componentsString=t,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let e=this._componentsString.split(".");for(let n of e)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new s.Component(parseInt(n))):this._components.push(new s.Component(n));}toString(){return this.componentsString}Equals(t){if(t==null||t._components.length!=this._components.length||t.isRelative!=this.isRelative)return false;for(let e=0,n=t._components.length;e<n;e++)if(!t._components[e].Equals(this._components[e]))return false;return true}PathByAppendingComponent(t){let e=new s;return e._components.push(...this._components),e._components.push(t),e}};Ue.Path=ve;ve.parentId="^";(function(s){class t{constructor(n){this.index=-1,this.name=null,typeof n=="string"?this.name=n:this.index=n;}get isIndex(){return this.index>=0}get isParent(){return this.name==s.parentId}static ToParent(){return new t(s.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}s.Component=t;})(ve||(Ue.Path=ve={}));});var Ke=C(Gn=>{Object.defineProperty(Gn,"__esModule",{value:true});Gn.Debug=void 0;var Zo;(function(s){function t(n,i,o){e(n instanceof i,o);}s.AssertType=t;function e(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}s.Assert=e;})(Zo||(Gn.Debug=Zo={}));});var it=C(De=>{Object.defineProperty(De,"__esModule",{value:true});De.throwNullException=De.NullException=void 0;var $n=class extends Error{};De.NullException=$n;function Eh(s){throw new $n(`${s} is null or undefined`)}De.throwNullException=Eh;});var dt=C(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.InkObject=void 0;var Ee=ct(),Je=J(),Ds=Ke(),ye=W(),Hn=it(),Es=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(t){if(t===null)return null;let e=this.rootContentContainer;if(e){let n=e.ContentAtPath(t).obj;if(n){let i=n.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Ee.Path;else {let t=[],e=this,n=(0, ye.asOrNull)(e.parent,Je.Container);for(;n!==null;){let i=(0, ye.asINamedContentOrNull)(e);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Hn.throwNullException)("namedChild.name");t.unshift(new Ee.Path.Component(i.name));}else t.unshift(new Ee.Path.Component(n.content.indexOf(e)));e=n,n=(0, ye.asOrNull)(n.parent,Je.Container);}this._path=new Ee.Path(t);}return this._path}ResolvePath(t){if(t===null)return (0, Hn.throwNullException)("path");if(t.isRelative){let e=(0, ye.asOrNull)(this,Je.Container);return e===null&&(Ds.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),e=(0, ye.asOrNull)(this.parent,Je.Container),Ds.Debug.Assert(e!==null,"Expected parent to be a container"),Ds.Debug.Assert(t.GetComponent(0).isParent),t=t.tail),e===null?(0, Hn.throwNullException)("nearestContainer"):e.ContentAtPath(t)}else {let e=this.rootContentContainer;return e===null?(0, Hn.throwNullException)("contentContainer"):e.ContentAtPath(t)}}ConvertPathToRelative(t){let e=this.path,n=Math.min(t.length,e.length),i=-1;for(let u=0;u<n;++u){let l=e.GetComponent(u),h=t.GetComponent(u);if(l.Equals(h))i=u;else break}if(i==-1)return t;let o=e.componentCount-1-i,r=[];for(let u=0;u<o;++u)r.push(Ee.Path.Component.ToParent());for(let u=i+1;u<t.componentCount;++u)r.push(t.GetComponent(u));return new Ee.Path(r,true)}CompactPathString(t){let e=null,n=null;return t.isRelative?(n=t.componentsString,e=this.path.PathByAppendingPath(t).componentsString):(n=this.ConvertPathToRelative(t).componentsString,e=t.componentsString),n.length<e.length?n:e}get rootContentContainer(){let t=this;for(;t.parent;)t=t.parent;return (0, ye.asOrNull)(t,Je.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(t,e,n){t[e]&&(t[e]=null),t[e]=n,t[e]&&(t[e].parent=this);}Equals(t){return t===this}};Un.InkObject=Es;});var se=C(Kn=>{Object.defineProperty(Kn,"__esModule",{value:true});Kn.StringBuilder=void 0;var ys=class{constructor(t){t=typeof t<"u"?t.toString():"",this.string=t;}get Length(){return this.string.length}Append(t){t!==null&&(this.string+=t);}AppendLine(t){typeof t<"u"&&this.Append(t),this.string+=`
2
+ `;}AppendFormat(t,...e){this.string+=t.replace(/{(\d+)}/g,(n,i)=>typeof e[i]<"u"?e[i]:n);}toString(){return this.string}Clear(){this.string="";}};Kn.StringBuilder=ys;});var pt=C(Se=>{Object.defineProperty(Se,"__esModule",{value:true});Se.InkList=Se.InkListItem=void 0;var Ot=it(),yh=se(),ft=class s{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let t=arguments[0],e=arguments[1];this.originName=t,this.itemName=e;}else if(arguments[0]){let e=arguments[0].toString().split(".");this.originName=e[0],this.itemName=e[1];}}static get Null(){return new s(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(t){if(t instanceof s){let e=t;return e.itemName==this.itemName&&e.originName==this.originName}return false}copy(){return new s(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let e=JSON.parse(t);if(!s.isLikeInkListItem(e))return s.Null;let n=e;return new s(n.originName,n.itemName)}static isLikeInkListItem(t){return !(typeof t!="object"||!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName")||typeof t.originName!="string"&&typeof t.originName!==null||typeof t.itemName!="string"&&typeof t.itemName!==null)}};Se.InkListItem=ft;var Ss=class s extends Map{constructor(){if(super(arguments[0]instanceof s?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof s){let t=arguments[0],e=t.originNames;e!==null&&(this._originNames=e.slice()),t.origins!==null&&(this.origins=t.origins.slice());}else if(typeof arguments[0]=="string"){let t=arguments[0],e=arguments[1];if(this.SetInitialOriginName(t),e.listDefinitions===null)return (0, Ot.throwNullException)("originStory.listDefinitions");let n=e.listDefinitions.TryListGetDefinition(t,null);if(n.exists){if(n.result===null)return (0, Ot.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+t)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let t=arguments[0];this.Add(t.Key,t.Value);}}static FromString(t,e){var n;if(t==null||t=="")return new s;let i=(n=e.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(t);if(i)return i.value===null?(0, Ot.throwNullException)("listValue.value"):new s(i.value);throw new Error("Could not find the InkListItem from the string '"+t+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(t,e=null){if(t instanceof ft){let n=t;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, Ot.throwNullException)("this.origins");for(let i of this.origins)if(i.name==n.originName){let o=i.TryGetValueForItem(n,0);if(o.exists){this.Add(n,o.result);return}else throw new Error("Could not add the item "+n+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(t!==null){let n=t,i=null;if(this.origins===null)return (0, Ot.throwNullException)("this.origins");for(let o of this.origins){if(n===null)return (0, Ot.throwNullException)("itemName");if(o.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+o.name+" or "+i.name);i=o;}}if(i==null){if(e==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let o=s.FromString(n,e).orderedItems[0];this.Add(o.Key,o.Value);}}else {let o=new ft(i.name,n),r=i.ValueForItem(o);this.Add(o,r);}}}ContainsItemNamed(t){for(let[e]of this)if(ft.fromSerializedKey(e).itemName==t)return true;return false}ContainsKey(t){return this.has(t.serialized())}Add(t,e){let n=t.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${t}`);this.set(n,e);}Remove(t){return this.delete(t.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let t=this.maxItem.Key.originName,e=null;return this.origins.every(n=>n.name==t?(e=n,false):true),e}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let e=ft.fromSerializedKey(t);if(e.originName===null)return (0, Ot.throwNullException)("item.originName");this._originNames.push(e.originName);}}return this._originNames}SetInitialOriginName(t){this._originNames=[t];}SetInitialOriginNames(t){t==null?this._originNames=null:this._originNames=t.slice();}get maxItem(){let t={Key:ft.Null,Value:0};for(let[e,n]of this){let i=ft.fromSerializedKey(e);(t.Key.isNull||n>t.Value)&&(t={Key:i,Value:n});}return t}get minItem(){let t={Key:ft.Null,Value:0};for(let[e,n]of this){let i=ft.fromSerializedKey(e);(t.Key.isNull||n<t.Value)&&(t={Key:i,Value:n});}return t}get inverse(){let t=new s;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let o=ft.fromSerializedKey(n);this.ContainsKey(o)||t.Add(o,i);}return t}get all(){let t=new s;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let o=ft.fromSerializedKey(n);t.set(o.serialized(),i);}return t}Union(t){let e=new s(this);for(let[n,i]of t)e.set(n,i);return e}Intersect(t){let e=new s;for(let[n,i]of this)t.has(n)&&e.set(n,i);return e}HasIntersection(t){for(let[e]of this)if(t.has(e))return true;return false}Without(t){let e=new s(this);for(let[n]of t)e.delete(n);return e}Contains(t){if(typeof t=="string")return this.ContainsItemNamed(t);let e=t;if(e.size==0||this.size==0)return false;for(let[n]of e)if(!this.has(n))return false;return true}GreaterThan(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>t.maxItem.Value}GreaterThanOrEquals(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value}LessThan(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<t.minItem.Value}LessThanOrEquals(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<=t.maxItem.Value&&this.minItem.Value<=t.minItem.Value}MaxAsList(){return this.Count>0?new s(this.maxItem):new s}MinAsList(){return this.Count>0?new s(this.minItem):new s}ListWithSubRange(t,e){if(this.Count==0)return new s;let n=this.orderedItems,i=0,o=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?i=t:t instanceof s&&t.Count>0&&(i=t.minItem.Value),Number.isInteger(e)?o=e:e instanceof s&&e.Count>0&&(o=e.maxItem.Value);let r=new s;r.SetInitialOriginNames(this.originNames);for(let a of n)a.Value>=i&&a.Value<=o&&r.Add(a.Key,a.Value);return r}Equals(t){if(!(t instanceof s)||t.Count!=this.Count)return false;for(let[e]of this)if(!t.has(e))return false;return true}get orderedItems(){let t=new Array;for(let[e,n]of this){let i=ft.fromSerializedKey(e);t.push({Key:i,Value:n});}return t.sort((e,n)=>e.Key.originName===null?(0, Ot.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, Ot.throwNullException)("y.Key.originName"):e.Value==n.Value?e.Key.originName.localeCompare(n.Key.originName):e.Value<n.Value?-1:e.Value>n.Value?1:0),t}get singleItem(){for(let t of this.orderedItems)return t.Key;return null}toString(){let t=this.orderedItems,e=new yh.StringBuilder;for(let n=0;n<t.length;n++){n>0&&e.Append(", ");let i=t[n].Key;if(i.itemName===null)return (0, Ot.throwNullException)("item.itemName");e.Append(i.itemName);}return e.toString()}valueOf(){return NaN}};Se.InkList=Ss;});var ze=C(Jn=>{Object.defineProperty(Jn,"__esModule",{value:true});Jn.StoryException=void 0;var bs=class extends Error{constructor(t){super(t),this.useEndLineNumber=false,this.message=t,this.name="StoryException";}};Jn.StoryException=bs;});var be=C(Kt=>{Object.defineProperty(Kt,"__esModule",{value:true});Kt.tryParseFloat=Kt.tryParseInt=Kt.tryGetValueFromMap=void 0;function Sh(s,t,e){if(s===null)return {result:e,exists:false};let n=s.get(t);return typeof n>"u"?{result:e,exists:false}:{result:n,exists:true}}Kt.tryGetValueFromMap=Sh;function bh(s,t=0){let e=parseInt(s);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}Kt.tryParseInt=bh;function Ah(s,t=0){let e=parseFloat(s);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}Kt.tryParseFloat=Ah;});var H=C(U=>{Object.defineProperty(U,"__esModule",{value:true});U.ValueType=U.ListValue=U.VariablePointerValue=U.DivertTargetValue=U.StringValue=U.FloatValue=U.IntValue=U.BoolValue=U.Value=U.AbstractValue=void 0;var tu=dt(),eu=ct(),ae=pt(),_h=ze(),Xe=W(),nu=be(),Dt=it(),zn=class s extends tu.InkObject{static Create(t,e){if(e){if(e===G.Int&&Number.isInteger(Number(t)))return new Tt(Number(t));if(e===G.Float&&!isNaN(t))return new Nt(Number(t))}if(typeof t=="boolean")return new Ae(!!t);if(typeof t=="string")return new Mt(String(t));if(Number.isInteger(Number(t)))return new Tt(Number(t));if(isNaN(t)){if(t instanceof eu.Path)return new Xn((0, Xe.asOrThrows)(t,eu.Path));if(t instanceof ae.InkList)return new Yn((0, Xe.asOrThrows)(t,ae.InkList))}else return new Nt(Number(t));return null}Copy(){return (0, Xe.asOrThrows)(s.Create(this.valueObject),tu.InkObject)}BadCastException(t){return new _h.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+t)}};U.AbstractValue=zn;var Pt=class extends zn{constructor(t){super(),this.value=t;}get valueObject(){return this.value}toString(){return this.value===null?(0, Dt.throwNullException)("Value.value"):this.value.toString()}};U.Value=Pt;var Ae=class extends Pt{constructor(t){super(t||false);}get isTruthy(){return !!this.value}get valueType(){return G.Bool}Cast(t){if(this.value===null)return (0, Dt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==G.Int)return new Tt(this.value?1:0);if(t==G.Float)return new Nt(this.value?1:0);if(t==G.String)return new Mt(this.value?"true":"false");throw this.BadCastException(t)}toString(){return this.value?"true":"false"}};U.BoolValue=Ae;var Tt=class extends Pt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return G.Int}Cast(t){if(this.value===null)return (0, Dt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==G.Bool)return new Ae(this.value!==0);if(t==G.Float)return new Nt(this.value);if(t==G.String)return new Mt(""+this.value);throw this.BadCastException(t)}};U.IntValue=Tt;var Nt=class extends Pt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return G.Float}Cast(t){if(this.value===null)return (0, Dt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==G.Bool)return new Ae(this.value!==0);if(t==G.Int)return new Tt(this.value);if(t==G.String)return new Mt(""+this.value);throw this.BadCastException(t)}};U.FloatValue=Nt;var Mt=class extends Pt{constructor(t){if(super(t||""),this._isNewline=this.value==`
3
+ `,this._isInlineWhitespace=true,this.value===null)return (0, Dt.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(e=>e!=" "&&e!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return G.String}get isTruthy(){return this.value===null?(0, Dt.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(t){if(t==this.valueType)return this;if(t==G.Int){let e=(0, nu.tryParseInt)(this.value);if(e.exists)return new Tt(e.result);throw this.BadCastException(t)}if(t==G.Float){let e=(0, nu.tryParseFloat)(this.value);if(e.exists)return new Nt(e.result);throw this.BadCastException(t)}throw this.BadCastException(t)}};U.StringValue=Mt;var Xn=class extends Pt{constructor(t=null){super(t);}get valueType(){return G.DivertTarget}get targetPath(){return this.value===null?(0, Dt.throwNullException)("Value.value"):this.value}set targetPath(t){this.value=t;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(t){if(t==this.valueType)return this;throw this.BadCastException(t)}toString(){return "DivertTargetValue("+this.targetPath+")"}};U.DivertTargetValue=Xn;var As=class s extends Pt{constructor(t,e=-1){super(t),this._contextIndex=e;}get contextIndex(){return this._contextIndex}set contextIndex(t){this._contextIndex=t;}get variableName(){return this.value===null?(0, Dt.throwNullException)("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 s(this.variableName,this.contextIndex)}};U.VariablePointerValue=As;var Yn=class s extends Pt{get isTruthy(){return this.value===null?(0, Dt.throwNullException)("this.value"):this.value.Count>0}get valueType(){return G.List}Cast(t){if(this.value===null)return (0, Dt.throwNullException)("Value.value");if(t==G.Int){let e=this.value.maxItem;return e.Key.isNull?new Tt(0):new Tt(e.Value)}else if(t==G.Float){let e=this.value.maxItem;return e.Key.isNull?new Nt(0):new Nt(e.Value)}else if(t==G.String){let e=this.value.maxItem;return e.Key.isNull?new Mt(""):new Mt(e.Key.toString())}if(t==this.valueType)return this;throw this.BadCastException(t)}constructor(t,e){super(null),!t&&!e?this.value=new ae.InkList:t instanceof ae.InkList?this.value=new ae.InkList(t):t instanceof ae.InkListItem&&typeof e=="number"&&(this.value=new ae.InkList({Key:t,Value:e}));}static RetainListOriginsForAssignment(t,e){let n=(0, Xe.asOrNull)(t,s),i=(0, Xe.asOrNull)(e,s);if(i&&i.value===null)return (0, Dt.throwNullException)("newList.value");if(n&&n.value===null)return (0, Dt.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};U.ListValue=Yn;var G;(function(s){s[s.Bool=-1]="Bool",s[s.Int=0]="Int",s[s.Float=1]="Float",s[s.List=2]="List",s[s.String=3]="String",s[s.DivertTarget=4]="DivertTarget",s[s.VariablePointer=5]="VariablePointer";})(G||(U.ValueType=G={}));});var iu=C(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.SearchResult=void 0;var Fh=J(),_s=class s{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof Fh.Container?this.obj:null}copy(){let t=new s;return t.obj=this.obj,t.approximate=this.approximate,t}};Qn.SearchResult=_s;});var J=C(Qe=>{Object.defineProperty(Qe,"__esModule",{value:true});Qe.Container=void 0;var wh=H(),ru=it(),xh=se(),_e=dt(),Oh=iu(),su=ct(),au=Ke(),Ph=be(),Jt=W(),Ye=class s extends _e.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(t){this.AddContent(t);}get namedOnlyContent(){let t=new Map;for(let[e,n]of this.namedContent){let i=(0, Jt.asOrThrows)(n,_e.InkObject);t.set(e,i);}for(let e of this.content){let n=(0, Jt.asINamedContentOrNull)(e);n!=null&&n.hasValidName&&t.delete(n.name);}return t.size==0&&(t=null),t}set namedOnlyContent(t){let e=this.namedOnlyContent;if(e!=null)for(let[n]of e)this.namedContent.delete(n);if(t!=null)for(let[,n]of t){let i=(0, Jt.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let t=0;return this.visitsShouldBeCounted&&(t|=s.CountFlags.Visits),this.turnIndexShouldBeCounted&&(t|=s.CountFlags.Turns),this.countingAtStartOnly&&(t|=s.CountFlags.CountStartOnly),t==s.CountFlags.CountStartOnly&&(t=0),t}set countFlags(t){let e=t;(e&s.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(e&s.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(e&s.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let t=[],e=this;for(;e instanceof s;)e.content.length>0&&(t.push(new su.Path.Component(0)),e=e.content[0]);return new su.Path(t)}AddContent(t){if(t instanceof Array){let e=t;for(let n of e)this.AddContent(n);}else {let e=t;if(this._content.push(e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}}TryAddNamedContent(t){let e=(0, Jt.asINamedContentOrNull)(t);e!=null&&e.hasValidName&&this.AddToNamedContentOnly(e);}AddToNamedContentOnly(t){au.Debug.AssertType(t,_e.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let e=(0, Jt.asOrThrows)(t,_e.InkObject);if(e.parent=this,t.name===null)return (0, ru.throwNullException)("namedContentObj.name");this.namedContent.set(t.name,t);}ContentAtPath(t,e=0,n=-1){n==-1&&(n=t.length);let i=new Oh.SearchResult;i.approximate=false;let o=this,r=this;for(let a=e;a<n;++a){let u=t.GetComponent(a);if(o==null){i.approximate=true;break}let l=o.ContentWithPathComponent(u);if(l==null){i.approximate=true;break}let h=(0, Jt.asOrNull)(l,s);if(a<n-1&&h==null){i.approximate=true;break}r=l,o=h;}return i.obj=r,i}InsertContent(t,e){if(this.content.splice(e,0,t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}AddContentsOfContainer(t){this.content.push(...t.content);for(let e of t.content)e.parent=this,this.TryAddNamedContent(e);}ContentWithPathComponent(t){if(t.isIndex)return t.index>=0&&t.index<this.content.length?this.content[t.index]:null;if(t.isParent)return this.parent;{if(t.name===null)return (0, ru.throwNullException)("component.name");let e=(0, Ph.tryGetValueFromMap)(this.namedContent,t.name,null);return e.exists?(0, Jt.asOrThrows)(e.result,_e.InkObject):null}}BuildStringOfHierarchy(){let t;if(arguments.length==0)return t=new xh.StringBuilder,this.BuildStringOfHierarchy(t,0,null),t.toString();t=arguments[0];let e=arguments[1],n=arguments[2];function i(){for(let a=0;a<4*e;++a)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 a=this.content[r];a instanceof s?a.BuildStringOfHierarchy(t,e,n):(i(),a instanceof wh.StringValue?(t.Append('"'),t.Append(a.toString().replace(`
4
+ `,"\\n")),t.Append('"')):t.Append(a.toString())),r!=this.content.length-1&&t.Append(","),!(a instanceof s)&&a==n&&t.Append(" <---"),t.AppendLine();}let o=new Map;for(let[r,a]of this.namedContent)this.content.indexOf((0, Jt.asOrThrows)(a,_e.InkObject))>=0||o.set(r,a);if(o.size>0){i(),t.AppendLine("-- named: --");for(let[,r]of o)au.Debug.AssertType(r,s,"Can only print out named Containers"),r.BuildStringOfHierarchy(t,e,n),t.AppendLine();}e--,i(),t.Append("]");}};Qe.Container=Ye;(function(s){(function(e){e[e.Start=0]="Start",e[e.Visits=1]="Visits",e[e.Turns=2]="Turns",e[e.CountStartOnly=4]="CountStartOnly";})(s.CountFlags||(s.CountFlags={}));})(Ye||(Qe.Container=Ye={}));});var rt=C(tn=>{Object.defineProperty(tn,"__esModule",{value:true});tn.ControlCommand=void 0;var Th=dt(),Ze=class s extends Th.InkObject{get commandType(){return this._commandType}constructor(t=s.CommandType.NotSet){super(),this._commandType=t;}Copy(){return new s(this.commandType)}static EvalStart(){return new s(s.CommandType.EvalStart)}static EvalOutput(){return new s(s.CommandType.EvalOutput)}static EvalEnd(){return new s(s.CommandType.EvalEnd)}static Duplicate(){return new s(s.CommandType.Duplicate)}static PopEvaluatedValue(){return new s(s.CommandType.PopEvaluatedValue)}static PopFunction(){return new s(s.CommandType.PopFunction)}static PopTunnel(){return new s(s.CommandType.PopTunnel)}static BeginString(){return new s(s.CommandType.BeginString)}static EndString(){return new s(s.CommandType.EndString)}static NoOp(){return new s(s.CommandType.NoOp)}static ChoiceCount(){return new s(s.CommandType.ChoiceCount)}static Turns(){return new s(s.CommandType.Turns)}static TurnsSince(){return new s(s.CommandType.TurnsSince)}static ReadCount(){return new s(s.CommandType.ReadCount)}static Random(){return new s(s.CommandType.Random)}static SeedRandom(){return new s(s.CommandType.SeedRandom)}static VisitIndex(){return new s(s.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new s(s.CommandType.SequenceShuffleIndex)}static StartThread(){return new s(s.CommandType.StartThread)}static Done(){return new s(s.CommandType.Done)}static End(){return new s(s.CommandType.End)}static ListFromInt(){return new s(s.CommandType.ListFromInt)}static ListRange(){return new s(s.CommandType.ListRange)}static ListRandom(){return new s(s.CommandType.ListRandom)}static BeginTag(){return new s(s.CommandType.BeginTag)}static EndTag(){return new s(s.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};tn.ControlCommand=Ze;(function(s){(function(e){e[e.NotSet=-1]="NotSet",e[e.EvalStart=0]="EvalStart",e[e.EvalOutput=1]="EvalOutput",e[e.EvalEnd=2]="EvalEnd",e[e.Duplicate=3]="Duplicate",e[e.PopEvaluatedValue=4]="PopEvaluatedValue",e[e.PopFunction=5]="PopFunction",e[e.PopTunnel=6]="PopTunnel",e[e.BeginString=7]="BeginString",e[e.EndString=8]="EndString",e[e.NoOp=9]="NoOp",e[e.ChoiceCount=10]="ChoiceCount",e[e.Turns=11]="Turns",e[e.TurnsSince=12]="TurnsSince",e[e.ReadCount=13]="ReadCount",e[e.Random=14]="Random",e[e.SeedRandom=15]="SeedRandom",e[e.VisitIndex=16]="VisitIndex",e[e.SequenceShuffleIndex=17]="SequenceShuffleIndex",e[e.StartThread=18]="StartThread",e[e.Done=19]="Done",e[e.End=20]="End",e[e.ListFromInt=21]="ListFromInt",e[e.ListRange=22]="ListRange",e[e.ListRandom=23]="ListRandom",e[e.BeginTag=24]="BeginTag",e[e.EndTag=25]="EndTag",e[e.TOTAL_VALUES=26]="TOTAL_VALUES";})(s.CommandType||(s.CommandType={}));})(Ze||(tn.ControlCommand=Ze={}));});var Et=C(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.Expression=void 0;var ou=J(),Fs=rt(),Nh=$(),ws=class extends Nh.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let t=new ou.Container;return t.AddContent(Fs.ControlCommand.EvalStart()),this.GenerateIntoContainer(t),this.outputWhenComplete&&t.AddContent(Fs.ControlCommand.EvalOutput()),t.AddContent(Fs.ControlCommand.EvalEnd()),t},this.GenerateConstantIntoContainer=t=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new ou.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let e of this._prototypeRuntimeConstantExpression.content){let n=e.Copy();n&&t.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(t){return false}};Zn.Expression=ws;});var oe=C(ti=>{Object.defineProperty(ti,"__esModule",{value:true});ti.Void=void 0;var Ih=dt(),xs=class extends Ih.InkObject{toString(){return "Void"}};ti.Void=xs;});var It=C(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.NativeFunctionCall=void 0;var A=H(),en=ze(),kh=oe(),ei=pt(),Rh=dt(),yt=W(),mt=it(),k=class s extends Rh.InkObject{static CallWithName(t){return new s(t)}static CallExistsWithName(t){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(t)}get name(){return this._name===null?(0, mt.throwNullException)("NativeFunctionCall._name"):this._name}set name(t){this._name=t,this._isPrototype||(s._nativeFunctions===null?(0, mt.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=s._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(t){this._numberOfParameters=t;}Call(t){if(this._prototype)return this._prototype.Call(t);if(this.numberOfParameters!=t.length)throw new Error("Unexpected number of parameters");let e=false;for(let o of t){if(o instanceof kh.Void)throw new en.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');o instanceof A.ListValue&&(e=true);}if(t.length==2&&e)return this.CallBinaryListOperation(t);let n=this.CoerceValuesToSingleType(t),i=n[0].valueType;return i==A.ValueType.Int?this.CallType(n):i==A.ValueType.Float?this.CallType(n):i==A.ValueType.String?this.CallType(n):i==A.ValueType.DivertTarget?this.CallType(n):i==A.ValueType.List?this.CallType(n):null}CallType(t){let e=(0, yt.asOrThrows)(t[0],A.Value),n=e.valueType,i=e,o=t.length;if(o==2||o==1){if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(n);if(!r){let a=A.ValueType[n];throw new en.StoryException("Cannot perform operation "+this.name+" on "+a)}if(o==2){let u=(0, yt.asOrThrows)(t[1],A.Value),l=r;if(i.value===null||u.value===null)return (0, mt.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=l(i.value,u.value);return A.Value.Create(h)}else {let a=r;if(i.value===null)return (0, mt.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=a(i.value);return this.name===s.Int?A.Value.Create(u,A.ValueType.Int):this.name===s.Float?A.Value.Create(u,A.ValueType.Float):A.Value.Create(u,e.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+t.length)}CallBinaryListOperation(t){if((this.name=="+"||this.name=="-")&&t[0]instanceof A.ListValue&&t[1]instanceof A.IntValue)return this.CallListIncrementOperation(t);let e=(0, yt.asOrThrows)(t[0],A.Value),n=(0, yt.asOrThrows)(t[1],A.Value);if((this.name=="&&"||this.name=="||")&&(e.valueType!=A.ValueType.List||n.valueType!=A.ValueType.List)){if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(A.ValueType.Int);if(i===null)return (0, mt.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let o=(0, yt.asBooleanOrThrows)(i(e.isTruthy?1:0,n.isTruthy?1:0));return new A.BoolValue(o)}if(e.valueType==A.ValueType.List&&n.valueType==A.ValueType.List)return this.CallType([e,n]);throw new en.StoryException("Can not call use "+this.name+" operation on "+A.ValueType[e.valueType]+" and "+A.ValueType[n.valueType])}CallListIncrementOperation(t){let e=(0, yt.asOrThrows)(t[0],A.ListValue),n=(0, yt.asOrThrows)(t[1],A.IntValue),i=new ei.InkList;if(e.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[o,r]of e.value){let a=ei.InkListItem.fromSerializedKey(o);if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(A.ValueType.Int);if(n.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(r,n.value),h=null;if(e.value.origins===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of e.value.origins)if(c.name==a.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(l,ei.InkListItem.Null);c.exists&&i.Add(c.result,l);}}return new A.ListValue(i)}CoerceValuesToSingleType(t){let e=A.ValueType.Int,n=null;for(let o of t){let r=(0, yt.asOrThrows)(o,A.Value);r.valueType>e&&(e=r.valueType),r.valueType==A.ValueType.List&&(n=(0, yt.asOrNull)(r,A.ListValue));}let i=[];if(A.ValueType[e]==A.ValueType[A.ValueType.List])for(let o of t){let r=(0, yt.asOrThrows)(o,A.Value);if(r.valueType==A.ValueType.List)i.push(r);else if(r.valueType==A.ValueType.Int){let a=parseInt(r.valueObject);if(n=(0, yt.asOrThrows)(n,A.ListValue),n.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=n.value.originOfMaxItem;if(u===null)return (0, mt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(a,ei.InkListItem.Null);if(l.exists){let h=new A.ListValue(l.result,a);i.push(h);}else throw new en.StoryException("Could not find List item with the value "+a+" in "+u.name)}else {let a=A.ValueType[r.valueType];throw new en.StoryException("Cannot mix Lists and "+a+" values in this operation")}}else for(let o of t){let a=(0, yt.asOrThrows)(o,A.Value).Cast(e);i.push(a);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)s.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let t=arguments[0];s.GenerateNativeFunctionsIfNecessary(),this.name=t;}else if(arguments.length===2){let t=arguments[0],e=arguments[1];this._isPrototype=true,this.name=t,this.numberOfParameters=e;}}static Identity(t){return t}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,i)=>n+i),this.AddIntBinaryOp(this.Subtract,(n,i)=>n-i),this.AddIntBinaryOp(this.Multiply,(n,i)=>n*i),this.AddIntBinaryOp(this.Divide,(n,i)=>Math.floor(n/i)),this.AddIntBinaryOp(this.Mod,(n,i)=>n%i),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,i)=>n==i),this.AddIntBinaryOp(this.Greater,(n,i)=>n>i),this.AddIntBinaryOp(this.Less,(n,i)=>n<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddIntBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddIntBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddIntBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddIntBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddIntBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddIntUnaryOp(this.Floor,s.Identity),this.AddIntUnaryOp(this.Ceiling,s.Identity),this.AddIntUnaryOp(this.Int,s.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,i)=>n+i),this.AddFloatBinaryOp(this.Subtract,(n,i)=>n-i),this.AddFloatBinaryOp(this.Multiply,(n,i)=>n*i),this.AddFloatBinaryOp(this.Divide,(n,i)=>n/i),this.AddFloatBinaryOp(this.Mod,(n,i)=>n%i),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,i)=>n==i),this.AddFloatBinaryOp(this.Greater,(n,i)=>n>i),this.AddFloatBinaryOp(this.Less,(n,i)=>n<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddFloatBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddFloatBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddFloatBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddFloatBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,s.Identity),this.AddStringBinaryOp(this.Add,(n,i)=>n+i),this.AddStringBinaryOp(this.Equal,(n,i)=>n===i),this.AddStringBinaryOp(this.NotEquals,(n,i)=>n!==i),this.AddStringBinaryOp(this.Has,(n,i)=>n.includes(i)),this.AddStringBinaryOp(this.Hasnt,(n,i)=>!n.includes(i)),this.AddListBinaryOp(this.Add,(n,i)=>n.Union(i)),this.AddListBinaryOp(this.Subtract,(n,i)=>n.Without(i)),this.AddListBinaryOp(this.Has,(n,i)=>n.Contains(i)),this.AddListBinaryOp(this.Hasnt,(n,i)=>!n.Contains(i)),this.AddListBinaryOp(this.Intersect,(n,i)=>n.Intersect(i)),this.AddListBinaryOp(this.Equal,(n,i)=>n.Equals(i)),this.AddListBinaryOp(this.Greater,(n,i)=>n.GreaterThan(i)),this.AddListBinaryOp(this.Less,(n,i)=>n.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,i)=>n.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(n,i)=>n.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(n,i)=>!n.Equals(i)),this.AddListBinaryOp(this.And,(n,i)=>n.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(n,i)=>n.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let t=(n,i)=>n.Equals(i),e=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,A.ValueType.DivertTarget,t),this.AddOpToNativeFunc(this.NotEquals,2,A.ValueType.DivertTarget,e);}}AddOpFuncForType(t,e){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(t,e);}static AddOpToNativeFunc(t,e,n,i){if(this._nativeFunctions===null)return (0, mt.throwNullException)("NativeFunctionCall._nativeFunctions");let o=this._nativeFunctions.get(t);o||(o=new s(t,e),this._nativeFunctions.set(t,o)),o.AddOpFuncForType(n,i);}static AddIntBinaryOp(t,e){this.AddOpToNativeFunc(t,2,A.ValueType.Int,e);}static AddIntUnaryOp(t,e){this.AddOpToNativeFunc(t,1,A.ValueType.Int,e);}static AddFloatBinaryOp(t,e){this.AddOpToNativeFunc(t,2,A.ValueType.Float,e);}static AddFloatUnaryOp(t,e){this.AddOpToNativeFunc(t,1,A.ValueType.Float,e);}static AddStringBinaryOp(t,e){this.AddOpToNativeFunc(t,2,A.ValueType.String,e);}static AddListBinaryOp(t,e){this.AddOpToNativeFunc(t,2,A.ValueType.List,e);}static AddListUnaryOp(t,e){this.AddOpToNativeFunc(t,1,A.ValueType.List,e);}toString(){return 'Native "'+this.name+'"'}};ni.NativeFunctionCall=k;k.Add="+";k.Subtract="-";k.Divide="/";k.Multiply="*";k.Mod="%";k.Negate="_";k.Equal="==";k.Greater=">";k.Less="<";k.GreaterThanOrEquals=">=";k.LessThanOrEquals="<=";k.NotEquals="!=";k.Not="!";k.And="&&";k.Or="||";k.Min="MIN";k.Max="MAX";k.Pow="POW";k.Floor="FLOOR";k.Ceiling="CEILING";k.Int="INT";k.Float="FLOAT";k.Has="?";k.Hasnt="!?";k.Intersect="^";k.ListMin="LIST_MIN";k.ListMax="LIST_MAX";k.All="LIST_ALL";k.Count="LIST_COUNT";k.ValueOfList="LIST_VALUE";k.Invert="LIST_INVERT";k._nativeFunctions=null;});var ri=C(ii=>{Object.defineProperty(ii,"__esModule",{value:true});ii.NumberExpression=void 0;var Vh=Et(),Os=H(),Bh=W(),Ps=class s extends Vh.Expression{constructor(t,e){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new Os.IntValue(this.value)):this.isFloat()?n.AddContent(new Os.FloatValue(this.value)):this.isBool()&&n.AddContent(new Os.BoolValue(this.value));},this.toString=()=>String(this.value),typeof t=="number"&&!Number.isNaN(t)||typeof t=="boolean")this.value=t,this.subtype=e;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(t){let e=(0, Bh.asOrNull)(t,s);return e?e.subtype==this.subtype&&e.value==this.value:false}};ii.NumberExpression=Ps;});var Ts=C(si=>{Object.defineProperty(si,"__esModule",{value:true});si.UnaryExpression=void 0;var Lh=Et(),Wh=It(),Fe=ri(),qh=W(),nn=class extends Lh.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(t,e){super(),this.op=e,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(Wh.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(t);}get typeName(){return "UnaryExpression"}};si.UnaryExpression=nn;nn.WithInner=(s,t)=>{let e=(0, qh.asOrNull)(s,Fe.NumberExpression);if(e){if(t==="-"){if(e.isInt())return new Fe.NumberExpression(-e.value,"int");if(e.isFloat())return new Fe.NumberExpression(-e.value,"float")}else if(t=="!"||t=="not"){if(e.isInt())return new Fe.NumberExpression(e.value==0,"bool");if(e.isFloat())return new Fe.NumberExpression(e.value==0,"bool");if(e.isBool())return new Fe.NumberExpression(!e.value,"bool")}throw new Error("Unexpected operation or number type")}return new nn(s,t)};});var Is=C(ai=>{Object.defineProperty(ai,"__esModule",{value:true});ai.BinaryExpression=void 0;var jh=Et(),Mh=It(),Gh=Ts(),$h=W(),Ns=class extends jh.Expression{constructor(t,e,n){super(),this.opName=n,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(Mh.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(t),this.rightExpression=this.AddContent(e),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(t){if(super.ResolveReferences(t),this.NativeNameForOp(this.opName)==="?"){let e=(0, $h.asOrNull)(this.leftExpression,Gh.UnaryExpression);e!==null&&(e.op==="not"||e.op==="!")&&this.Error(`Using 'not' or '!' here negates '${e.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};ai.BinaryExpression=Ns;});var sn=C(oi=>{Object.defineProperty(oi,"__esModule",{value:true});oi.CharacterSet=void 0;var rn=class{constructor(t){this.set=new Set,this.Add=e=>this.set.add(e),this.AddRange=(e,n)=>{for(let i=e.charCodeAt(0);i<=n.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=e=>{if(typeof e=="string"||Array.isArray(e))for(let n of e)this.Add(n);else for(let n of e.set)this.Add(n);return this},t&&this.AddCharacters(t);}};oi.CharacterSet=rn;rn.FromRange=(s,t)=>new rn().AddRange(s,t);});var lu=C(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.CharacterRange=void 0;var uu=sn(),an=class{constructor(t,e,n=[]){if(this._start=t,this._end=e,this._correspondingCharSet=new uu.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),o;i<=this.end.charCodeAt(0);i+=1)o=String.fromCharCode(i),this._excludes.has(o)||this._correspondingCharSet.AddCharacters(o);return this._correspondingCharSet},n instanceof uu.CharacterSet)this._excludes=n.set;else for(let i of n)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};ui.CharacterRange=an;an.Define=(s,t,e=[])=>new an(s,t,e);});var hi=C(li=>{Object.defineProperty(li,"__esModule",{value:true});li.ChoicePoint=void 0;var Hh=dt(),Uh=ct(),ks=it(),Rs=class extends Hh.InkObject{constructor(t=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=t;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path);}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t;}get choiceTarget(){return this._pathOnChoice===null?(0, ks.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, ks.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new Uh.Path(t);}get flags(){let t=0;return this.hasCondition&&(t|=1),this.hasStartContent&&(t|=2),this.hasChoiceOnlyContent&&(t|=4),this.isInvisibleDefault&&(t|=8),this.onceOnly&&(t|=16),t}set flags(t){this.hasCondition=(t&1)>0,this.hasStartContent=(t&2)>0,this.hasChoiceOnlyContent=(t&4)>0,this.isInvisibleDefault=(t&8)>0,this.onceOnly=(t&16)>0;}toString(){if(this.pathOnChoice===null)return (0, ks.throwNullException)("ChoicePoint.pathOnChoice");let e=this.pathOnChoice.toString();return "Choice: -> "+e}};li.ChoicePoint=Rs;});var ue=C(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.PushPopType=void 0;var hu;(function(s){s[s.Tunnel=0]="Tunnel",s[s.Function=1]="Function",s[s.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(hu||(ci.PushPopType=hu={}));});var on=C(di=>{Object.defineProperty(di,"__esModule",{value:true});di.Pointer=void 0;var Kh=ct(),Vs=class s{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new Kh.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new s(this.container,this.index)}static StartOf(t){return new s(t,0)}static get Null(){return new s(null,-1)}};di.Pointer=Vs;});var kt=C(pi=>{Object.defineProperty(pi,"__esModule",{value:true});pi.Divert=void 0;var Jh=ct(),zh=ue(),Xh=se(),Yh=dt(),Bs=on(),cu=J(),fi=it(),Ls=class s extends Yh.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let t=this.targetPointer.Resolve();t&&(this._targetPath=t.path);}return this._targetPath}set targetPath(t){this._targetPath=t,this._targetPointer=Bs.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let t=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, fi.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, fi.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(t===null)return (0, fi.throwNullException)("targetObj");this._targetPointer.container=t.parent instanceof cu.Container?t.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Bs.Pointer.StartOf(t instanceof cu.Container?t:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(t){t==null?this.targetPath=null:this.targetPath=new Jh.Path(t);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(t){super(),this._targetPath=null,this._targetPointer=Bs.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof t<"u"&&(this.pushesToStack=true,this.stackPushType=t);}Equals(t){let e=t;return e instanceof s&&this.hasVariableTarget==e.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==e.variableDivertName:this.targetPath===null?(0, fi.throwNullException)("this.targetPath"):this.targetPath.Equals(e.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let t=new Xh.StringBuilder,e=this.targetPath.toString();return t.Append("Divert"),this.isConditional&&t.Append("?"),this.pushesToStack&&(this.stackPushType==zh.PushPopType.Function?t.Append(" function"):t.Append(" tunnel")),t.Append(" -> "),t.Append(this.targetPathString),t.Append(" ("),t.Append(e),t.Append(")"),t.toString()}}};pi.Divert=Ls;});var Gt=C(mi=>{Object.defineProperty(mi,"__esModule",{value:true});mi.SymbolType=void 0;var du;(function(s){s[s.Knot=0]="Knot",s[s.List=1]="List",s[s.ListItem=2]="ListItem",s[s.Var=3]="Var",s[s.SubFlowAndWeave=4]="SubFlowAndWeave",s[s.Arg=5]="Arg",s[s.Temp=6]="Temp";})(du||(mi.SymbolType=du={}));});var zt=C(gi=>{Object.defineProperty(gi,"__esModule",{value:true});gi.VariableAssignment=void 0;var Qh=dt(),Ws=class extends Qh.InkObject{constructor(t,e){super(),this.variableName=t||null,this.isNewDeclaration=!!e,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};gi.VariableAssignment=Ws;});var we=C(vi=>{Object.defineProperty(vi,"__esModule",{value:true});vi.Choice=void 0;var Zh=hi(),Ci=J(),Xt=rt(),qs=kt(),fu=H(),tc=$(),ec=Gt(),pu=zt(),js=class extends tc.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get condition(){return this._condition}set condition(t){this._condition=t,t&&this.AddContent(t);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(t,e,n){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new Ci.Container,this._runtimeChoice=new Zh.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Xt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new fu.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new pu.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Xt.ControlCommand.BeginString()),this._divertToStartContentOuter=new qs.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let o=new qs.Divert;o.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(o),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Ci.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Xt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Xt.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Xt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Xt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Ci.Container,this.startContent){this._returnToR2=new fu.DivertTargetValue,this._innerContentContainer.AddContent(Xt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Xt.ControlCommand.EvalEnd());let i=new pu.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new qs.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Ci.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=t,this.choiceOnlyContent=e,this.innerContent=n,this.indentationDepth=1,t&&this.AddContent(this.startContent),e&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(t){var e;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(t),this.identifier&&(((e=this.identifier)===null||e===void 0?void 0:e.name)||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,ec.SymbolType.SubFlowAndWeave);}};vi.Choice=js;});var mu=C(Ei=>{Object.defineProperty(Ei,"__esModule",{value:true});Ei.StringParserElement=void 0;var Di=class s{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=t=>{s._uniqueIdCounter++,this.uniqueId=s._uniqueIdCounter,this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.customFlags=t.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=t=>{this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.reportedErrorInScope=t.reportedErrorInScope,this.customFlags=t.customFlags;};}};Ei.StringParserElement=Di;Di._uniqueIdCounter=1e3;});var Cu=C(yi=>{Object.defineProperty(yi,"__esModule",{value:true});yi.StringParserState=void 0;var gu=mu(),Ms=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(t){this.currentElement.lineIndex=t;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(t){this.currentElement.characterIndex=t;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(t){this.currentElement.characterInLineIndex=t;}get customFlags(){return this.currentElement.customFlags}set customFlags(t){this.currentElement.customFlags=t;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new gu.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let e=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(e),n.uniqueId},this.Pop=e=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=e)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=e=>{if(this.currentElement.uniqueId!=e)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let e=this._stack[this._numElements-2],n=this._stack[this._numElements-1];e.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let e of this._stack)e.reportedErrorInScope=true;};let t=200;for(let e=0;e<t;e++)this._stack[e]=new gu.StringParserElement;this._numElements=1;}};yi.StringParserState=Ms;});var $s=C(le=>{Object.defineProperty(le,"__esModule",{value:true});le.StringParser=le.ParseSuccess=void 0;var Gs=sn(),nc=Cu();le.ParseSuccess=Symbol("ParseSuccessStruct");var un=class s{constructor(t){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=n=>(this.state.Pop(n),null),this.CancelRule=n=>{this.state.Pop(n);},this.SucceedRule=(n,i=null)=>{let o=this.state.Peek(n),r=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,r,o),this.state.Squash();let a=i;return a===null&&(a=s.ParseSuccess),a},this.Expect=(n,i=null,o=null)=>{let r=this.ParseObject(n);if(r===null){i===null&&(i=n.name);let a,u=this.LineRemainder();u===null||u.length===0?a="end of line":a=`'${u}'`,this.Error(`Expected ${i} but saw ${a}`),o!==null&&(r=o());}return r},this.Error=(n,i=false)=>{this.ErrorOnLine(n,this.lineIndex+1,i);},this.ErrorWithParsedObject=(n,i,o=false)=>{this.ErrorOnLine(n,i.debugMetadata?i.debugMetadata.startLineNumber:-1,o);},this.ErrorOnLine=(n,i,o)=>{if(!this.state.errorReportedAlreadyInScope){let r=o?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,i-1,o);else throw new Error(`${r} on line ${i}: ${n}`);this.state.NoteErrorReported();}o||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
5
5
  \r`)),this.SetFlag=(n,i)=>{i?this.state.customFlags|=n:this.state.customFlags&=~n;},this.GetFlag=n=>!!(this.state.customFlags&n),this.ParseObject=n=>{let i=this.BeginRule(),o=this.state.stackHeight,r=n();if(o!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return r===null?this.FailRule(i):(this.SucceedRule(i,r),r)},this.Parse=n=>{let i=this.BeginRule(),o=n();return o===null?(this.FailRule(i),null):(this.SucceedRule(i,o),o)},this.OneOf=n=>{for(let i of n){let o=this.ParseObject(i);if(o!==null)return o}return null},this.OneOrMore=n=>{let i=[],o=null;do o=this.ParseObject(n),o!==null&&i.push(o);while(o!==null);return i.length>0?i:null},this.Optional=n=>()=>{let i=this.ParseObject(n);return i===null?s.ParseSuccess:i},this.Exclude=n=>()=>this.ParseObject(n)&&s.ParseSuccess,this.OptionalExclude=n=>()=>(this.ParseObject(n),s.ParseSuccess),this.String=n=>()=>this.ParseString(n),this.TryAddResultToList=(n,i,o=true)=>{if(n!==s.ParseSuccess){if(o&&Array.isArray(n)){let r=n;if(r!==null){for(let a of r)i.push(a);return}}i.push(n);}},this.Interleave=(n,i,o=null,r=true)=>{let a=this.BeginRule(),u=[],l=this.ParseObject(n);if(l===null)return this.FailRule(a);this.TryAddResultToList(l,u,r);let h=null,c=null;do{if(o!==null&&this.Peek(o)!==null||(h=this.ParseObject(i),h===null))break;if(this.TryAddResultToList(h,u,r),c=null,h!==null){if(c=this.ParseObject(n),c===null)break;this.TryAddResultToList(c,u,r);}}while((h!==null||c!==null)&&!(h===s.ParseSuccess&&c==s.ParseSuccess)&&this.remainingLength>0);return u.length===0?this.FailRule(a):this.SucceedRule(a,u)},this.ParseString=n=>{if(n.length>this.remainingLength)return null;let i=this.BeginRule(),o=this.index,r=this.characterInLineIndex,a=this.lineIndex,u=true;for(let l=0;l<n.length;l+=1){let h=n[l];if(this._chars[o]!==h){u=false;break}h===`
6
6
  `&&(a++,r=-1),o++,r++;}return this.index=o,this.characterInLineIndex=r,this.lineIndex=a,u?this.SucceedRule(i,n):this.FailRule(i)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){let n=this._chars[this.index];return n===`
7
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,i=-1)=>this.ParseCharactersFromString(n,false,i),this.ParseUntilCharactersFromCharSet=(n,i=-1)=>this.ParseCharactersFromCharSet(n,false,i),this.ParseCharactersFromString=(n,i=-1,o=-1)=>{let r=new Ms.CharacterSet(n);return typeof i=="number"?this.ParseCharactersFromCharSet(r,true,i):this.ParseCharactersFromCharSet(r,i,o)},this.ParseCharactersFromCharSet=(n,i=true,o=-1)=>{o===-1&&(o=Number.MAX_SAFE_INTEGER);let r=this.index,a=this.index,u=this.characterInLineIndex,l=this.lineIndex,h=0;for(;a<this._chars.length&&n.set.has(this._chars[a])===i&&h<o;)this._chars[a]===`
7
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,i=-1)=>this.ParseCharactersFromString(n,false,i),this.ParseUntilCharactersFromCharSet=(n,i=-1)=>this.ParseCharactersFromCharSet(n,false,i),this.ParseCharactersFromString=(n,i=-1,o=-1)=>{let r=new Gs.CharacterSet(n);return typeof i=="number"?this.ParseCharactersFromCharSet(r,true,i):this.ParseCharactersFromCharSet(r,i,o)},this.ParseCharactersFromCharSet=(n,i=true,o=-1)=>{o===-1&&(o=Number.MAX_SAFE_INTEGER);let r=this.index,a=this.index,u=this.characterInLineIndex,l=this.lineIndex,h=0;for(;a<this._chars.length&&n.set.has(this._chars[a])===i&&h<o;)this._chars[a]===`
8
8
  `&&(l+=1,u=-1),a+=1,u+=1,h+=1;return this.index=a,this.characterInLineIndex=u,this.lineIndex=l,this.index>r?this._chars.slice(r,this.index).join(""):null},this.Peek=n=>{let i=this.BeginRule(),o=n();return this.CancelRule(i),o},this.ParseInt=()=>{let n=this.index,i=this.characterInLineIndex,o=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");let r=this.ParseCharactersFromCharSet(s.numbersCharacterSet);if(r===null)return this.index=n,this.characterInLineIndex=i,null;let a;return Number.isNaN(Number(r))?(this.Error("Failed to read integer value: "+r+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(a=Number(r),o?-a:a)},this.ParseFloat=()=>{let n=this.index,i=this.characterInLineIndex,o=this.ParseInt();if(o!==null&&this.ParseString(".")!==null){let r=this.ParseCharactersFromCharSet(s.numbersCharacterSet);return +`${o}.${r}`}return this.index=n,this.characterInLineIndex=i,null},this.ParseNewline=()=>{let n=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
9
9
  `)===null?this.FailRule(n):this.SucceedRule(n,`
10
- `)};let e=this.PreProcessInputString(t);this.state=new ec.StringParserState,t?this._chars=e.split(""):this._chars=[],this.inputString=e;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(t){return t}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(t){this.state.lineIndex=t;}set characterInLineIndex(t){this.state.characterInLineIndex=t;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(t){this.state.characterIndex=t;}ParseUntil(t,e=null,n=null){let i=this.BeginRule(),o=new Ms.CharacterSet;e!==null&&(o.set=new Set([...o.set.values(),...e.set.values()])),n!==null&&(o.set=new Set([...o.set.values(),...n.set.values()]));let r="",a=null;do{let u=this.ParseUntilCharactersFromCharSet(o);if(u&&(r+=u),a=this.Peek(t),a!==null)break;{if(this.endOfInput)break;let l=this.currentCharacter;if(e!==null&&e.set.has(l)){r+=l,l===`
11
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return r.length>0?this.SucceedRule(i,String(r)):this.FailRule(i)}};le.StringParser=on;on.ParseSuccess=le.ParseSuccess;on.numbersCharacterSet=new Ms.CharacterSet("0123456789");});var vu=C(Si=>{Object.defineProperty(Si,"__esModule",{value:true});Si.CommentEliminator=void 0;var $s=rn(),nc=Gs(),Hs=class extends nc.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new $s.CharacterSet(`/\r
12
- `),this._commentBlockEndCharacter=new $s.CharacterSet("*"),this._newlineCharacters=new $s.CharacterSet(`
10
+ `)};let e=this.PreProcessInputString(t);this.state=new nc.StringParserState,t?this._chars=e.split(""):this._chars=[],this.inputString=e;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(t){return t}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(t){this.state.lineIndex=t;}set characterInLineIndex(t){this.state.characterInLineIndex=t;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(t){this.state.characterIndex=t;}ParseUntil(t,e=null,n=null){let i=this.BeginRule(),o=new Gs.CharacterSet;e!==null&&(o.set=new Set([...o.set.values(),...e.set.values()])),n!==null&&(o.set=new Set([...o.set.values(),...n.set.values()]));let r="",a=null;do{let u=this.ParseUntilCharactersFromCharSet(o);if(u&&(r+=u),a=this.Peek(t),a!==null)break;{if(this.endOfInput)break;let l=this.currentCharacter;if(e!==null&&e.set.has(l)){r+=l,l===`
11
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return r.length>0?this.SucceedRule(i,String(r)):this.FailRule(i)}};le.StringParser=un;un.ParseSuccess=le.ParseSuccess;un.numbersCharacterSet=new Gs.CharacterSet("0123456789");});var vu=C(Si=>{Object.defineProperty(Si,"__esModule",{value:true});Si.CommentEliminator=void 0;var Hs=sn(),ic=$s(),Us=class extends ic.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Hs.CharacterSet(`/\r
12
+ `),this._commentBlockEndCharacter=new Hs.CharacterSet("*"),this._newlineCharacters=new Hs.CharacterSet(`
13
13
  \r`),this.Process=()=>{let t=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return t!==null?t.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let t=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return t!==null?t.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>this.ParseString("//")===null?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(this.ParseString("/*")===null)return null;let t=this.lineIndex,e=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),e!=null?`
14
- `.repeat(this.lineIndex-t):null};}PreProcessInputString(t){return t}};Si.CommentEliminator=Hs;});var bi=C(yi=>{Object.defineProperty(yi,"__esModule",{value:true});yi.Conditional=void 0;var ic=K(),Du=rt(),rc=G(),Us=class extends rc.ParsedObject{constructor(t,e){super(),this.initialCondition=t,this.branches=e,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new ic.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let o=i.runtimeObject;n.AddContent(o);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(Du.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Du.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(t){let e=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=e;}super.ResolveReferences(t);}};yi.Conditional=Us;});var Yt=C(Ai=>{Object.defineProperty(Ai,"__esModule",{value:true});Ai.Text=void 0;var sc=G(),ac=$(),Ks=class extends sc.ParsedObject{constructor(t){super(),this.text=t,this.GenerateRuntimeObject=()=>new ac.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Ai.Text=Ks;});var Fi=C(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.ConstantDeclaration=void 0;var oc=G(),uc=Gt(),Js=class extends oc.ParsedObject{get constantName(){var t;return (t=this.constantIdentifier)===null||t===void 0?void 0:t.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(t,e){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=t,e&&(this._expression=this.AddContent(e));}get typeName(){return "CONST"}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.constantIdentifier,uc.SymbolType.Var);}};_i.ConstantDeclaration=Js;});var xe=C(wi=>{Object.defineProperty(wi,"__esModule",{value:true});wi.FlowLevel=void 0;var Eu;(function(s){s[s.Story=0]="Story",s[s.Knot=1]="Knot",s[s.Stitch=2]="Stitch",s[s.WeavePoint=3]="WeavePoint";})(Eu||(wi.FlowLevel=Eu={}));});var un=C(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.Gather=void 0;var lc=K(),hc=G(),cc=Gt(),zs=class extends hc.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(t,e){super(),this.indentationDepth=e,this.GenerateRuntimeObject=()=>{let n=new lc.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let i of this.content)n.AddContent(i.runtimeObject);return n},this.toString=()=>{var n,i;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},t&&(this.identifier=t);}get typeName(){return "Gather"}ResolveReferences(t){super.ResolveReferences(t),this.identifier&&(this.identifier.name||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,cc.SymbolType.SubFlowAndWeave);}};xi.Gather=zs;});var he=C(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.Path=void 0;var Oi=L(),Su=Rt(),Oe=xe(),dc=ce(),Xs=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Oe.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(t=>t.name).filter(Oi.filterUndef).join(".")),this._dotSeparatedComponents}constructor(t,e){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Oe.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(n);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=n=>{let i=this.firstComponent,o=n;for(;o;){let r=o===n,a=this.GetChildFromContext(o,i,null,r);if(a)return a;o=o.parent;}return null},this.ResolveTailComponents=n=>{let i=n;if(!this.components)return null;for(let o=1;o<this.components.length;++o){let r=this.components[o].name,a,u=(0, Oi.asOrNull)(i,Su.FlowBase);if(u!==null?a=u.flowLevel+1:a=Oe.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,r,a),i===null)break}return i},this.GetChildFromContext=(n,i,o,r=false)=>{let a=o===null,u=(0, Oi.asOrNull)(n,dc.Weave);if(i&&u!==null&&(a||o===Oe.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, Oi.asOrNull)(n,Su.FlowBase);if(i&&l!==null){let h=r||l.flowLevel===Oe.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,o,h)}return null},Object.values(Oe.FlowLevel).includes(t)?(this._baseTargetLevel=t,this.components=e||[]):Array.isArray(t)?(this._baseTargetLevel=null,this.components=t||[]):(this._baseTargetLevel=null,this.components=[t]);}get typeName(){return "Path"}};Pi.Path=Xs;});var Zs=C(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.ReturnType=void 0;var fc=G(),pc=K(),Ys=rt(),mc=oe(),Qs=class extends fc.ParsedObject{constructor(t=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let e=new pc.Container;return this.returnedExpression?e.AddContent(this.returnedExpression.runtimeObject):(e.AddContent(Ys.ControlCommand.EvalStart()),e.AddContent(new mc.Void),e.AddContent(Ys.ControlCommand.EvalEnd())),e.AddContent(Ys.ControlCommand.PopFunction()),e},t&&(this.returnedExpression=this.AddContent(t));}get typeName(){return "ReturnType"}};Ti.ReturnType=Qs;});var ln=C(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.ClosestFlowBase=void 0;function gc(s){let t=s.parent;for(;t;){if(t.hasOwnProperty("iamFlowbase")&&t.iamFlowbase())return t;t=t.parent;}return null}Ni.ClosestFlowBase=gc;});var ki=C(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.Identifier=void 0;var ta=class s{constructor(t){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=t;}get typeName(){return "Identifier"}static Done(){return new s("DONE")}};Ii.Identifier=ta;});var Rt=C(Ri=>{Object.defineProperty(Ri,"__esModule",{value:true});Ri.FlowBase=void 0;var Cc=we(),ea=Te(),vc=Pe(),Vt=xe(),Dc=un(),Ec=G(),Sc=he(),yc=Zs(),bc=K(),Ac=kt(),_c=zt(),na=Gt(),Fc=ce(),wc=ln(),xc=ki(),yu=L(),ia=class s extends Ec.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e=null,n=null,i=false,o=false){super(),this.isFunction=i,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(r,a)=>{var u,l;let h=[],c=[];this._subFlowsByName=new Map;for(let m of r){let D=(0, yu.asOrNull)(m,s);D?(this._firstChildFlow===null&&(this._firstChildFlow=D),c.push(m),!((u=D.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=D.identifier)===null||l===void 0?void 0:l.name,D)):h.push(m);}a&&h.push(new Dc.Gather(null,1),new ea.Divert(new Sc.Path(xc.Identifier.Done())));let d=[];return h.length>0&&(this._rootWeave=new Fc.Weave(h,0),d.push(this._rootWeave)),c.length>0&&d.push(...c),d},this.ResolveVariableWithName=(r,a)=>{var u;let l={},h=a===null?this:(0, wc.ClosestFlowBase)(a);if(h){if(h.args!==null){for(let c of h.args)if(((u=c.identifier)===null||u===void 0?void 0:u.name)===r)return l.found=true,l.isArgument=true,l.ownerFlow=h,l}if(h!==this.story&&h.variableDeclarations.has(r))return l.found=true,l.ownerFlow=h,l.isTemporary=true,l}return this.story.variableDeclarations.has(r)?(l.found=true,l.ownerFlow=this.story,l.isGlobal=true,l):(l.found=false,l)},this.AddNewVariableDeclaration=r=>{let a=r.variableName;if(this.variableDeclarations.has(a)){let u=this.variableDeclarations.get(a),l="";u.debugMetadata&&(l=` (${u.debugMetadata})`),this.Error(`found declaration variable '${a}' that was already declared${l}`,r,false);return}this.variableDeclarations.set(r.variableName,r);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,r]of this._subFlowsByName)r.hasOwnProperty("ResolveWeavePointNaming")&&r.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var r;let a=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===Vt.FlowLevel.Knot||this.flowLevel===Vt.FlowLevel.Stitch)&&(a=this.Find(yc.ReturnType)(),a!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,a));let u=new bc.Container;u.name=(r=this.identifier)===null||r===void 0?void 0:r.name,this.story.countAllVisits&&(u.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(u);let l=0;for(;this.content!==null&&l<this.content.length;){let h=this.content[l];if(h instanceof s){let c=h,d=c.runtimeObject;l===0&&!c.hasParameters&&this.flowLevel===Vt.FlowLevel.Knot&&(this._startingSubFlowDivert=new Ac.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=d);let m=d,D=u.namedContent.get(m.name)||null;if(D){let v=`${this.GetType()} already contains flow named '${m.name}' (at ${D.debugMetadata})`;this.Error(v,c);}u.AddToNamedContentOnly(m);}else h&&u.AddContent(h.runtimeObject);l+=1;}return this.flowLevel!==Vt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&a===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),u},this.GenerateArgumentVariableAssignments=r=>{var a;if(!(this.args===null||this.args.length===0))for(let u=this.args.length-1;u>=0;--u){let l=((a=this.args[u].identifier)===null||a===void 0?void 0:a.name)||null,h=new _c.VariableAssignment(l,true);r.AddContent(h);}},this.ContentWithNameAtLevel=(r,a=null,u=false)=>{var l;if((a===this.flowLevel||a===null)&&r===((l=this.identifier)===null||l===void 0?void 0:l.name))return this;if(a===Vt.FlowLevel.WeavePoint||a===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(r),c))return c;if(a===Vt.FlowLevel.WeavePoint)return u?this.DeepSearchForAnyLevelContent(r):null}if(a!==null&&a<this.flowLevel)return null;let h=this._subFlowsByName.get(r)||null;return h&&(a===null||a===h.flowLevel)?h:u?this.DeepSearchForAnyLevelContent(r):null},this.DeepSearchForAnyLevelContent=r=>{let a=this.ContentWithNameAtLevel(r,Vt.FlowLevel.WeavePoint,false);if(a)return a;for(let[,u]of this._subFlowsByName){let l=u.ContentWithNameAtLevel(r,null,true);if(l)return l}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==Vt.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[u,l]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${u}' within the function '${this.identifier}'`,l);if(!this._rootWeave)throw new Error;let r=this._rootWeave.FindAll(ea.Divert)();for(let u of r)!u.isFunctionCall&&!(u.parent instanceof vc.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let a=this._rootWeave.FindAll(Cc.Choice)();for(let u of a)this.Error(`Functions may not contain choices, but saw '${u}'`,u);},this.WarningInTermination=r=>{let a="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";r.parent===this._rootWeave&&this._firstChildFlow&&(a=`${a} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let u=(0, yu.asOrNull)(r,ea.Divert);u&&u.isTunnel&&(a+=` When final tunnel to '${u.target} ->' returns it won't have anywhere to go.`),this.Warning(a,r);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=t,this.args=n,e===null&&(e=[]),this.PreProcessTopLevelObjects(e),e=this.SplitWeaveAndSubFlowContent(e,this.GetType()=="Story"&&!o),this.AddContent(e);}PreProcessTopLevelObjects(t){}ResolveReferences(t){var e,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(t),this.args!==null){for(let i of this.args)t.CheckForNamingCollisions(this,i.identifier,na.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let o=i+1;o<this.args.length;o+=1)((e=this.args[i].identifier)===null||e===void 0?void 0:e.name)==((n=this.args[o].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==Vt.FlowLevel.Story){let i=this.flowLevel===Vt.FlowLevel.Knot?na.SymbolType.Knot:na.SymbolType.SubFlowAndWeave;t.CheckForNamingCollisions(this,this.identifier,i);}}};Ri.FlowBase=ia;});var Bi=C(Vi=>{Object.defineProperty(Vi,"__esModule",{value:true});Vi.ContentList=void 0;var Oc=K(),Pc=G(),Tc=Yt(),Nc=L(),ra=class extends Pc.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(t,...e){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let i=(0, Nc.asOrNull)(this.content[n],Tc.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new Oc.Container;if(this.content!==null)for(let i of this.content){let o=i.runtimeObject;o&&n.AddContent(o);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,t&&this.AddContent(t),e&&this.AddContent(e);}get typeName(){return "ContentList"}};Vi.ContentList=ra;});var Ne=C(Li=>{Object.defineProperty(Li,"__esModule",{value:true});Li.VariableReference=void 0;var Ic=dt(),kc=ct(),sa=class extends Ic.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(t){t===null?this.pathForCount=null:this.pathForCount=new kc.Path(t);}constructor(t=null){super(),this.pathForCount=null,this.name=t;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};Li.VariableReference=sa;});var Ie=C(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.VariableReference=void 0;var Rc=Bi(),Vc=Et(),bu=Rt(),Bc=he(),Lc=Ne(),Wc=ce(),qc=ki(),Au=L(),aa=class extends Vc.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(t=>t.name).filter(Au.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let t=this.path.join(".");return new qc.Identifier(t)}get runtimeVarRef(){return this._runtimeVarRef}constructor(t){super(),this.pathIdentifiers=t,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=e=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(e),this.isConstantReference=true;return}if(this._runtimeVarRef=new Lc.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",o="";this.path.length===1?i=this.path[0]:(o=this.path[0],i=this.path[1]),this.story.ResolveListItem(o,i,this)&&(this.isListItemReference=true);}e.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(t){if(super.ResolveReferences(t),this.isConstantReference||this.isListItemReference)return;let e=new Bc.Path(this.pathIdentifiers),n=e.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let i=(0, Au.asOrNull)(n,bu.FlowBase);i&&i.isFunction&&(this.parent instanceof Wc.Weave||this.parent instanceof Rc.ContentList||this.parent instanceof bu.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${e}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}t.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};Wi.VariableReference=aa;});var hn=C(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.FunctionCall=void 0;var Bt=rt(),jc=Te(),Mc=Pe(),Gc=Et(),$c=pt(),Hc=$(),ji=It(),_u=ii(),Uc=he(),Kc=$(),Jc=Ie(),qi=L(),Mi=class s extends Gc.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(t,e){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=n=>{let i=this.story.ResolveList(this.name),o=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),n.AddContent(Bt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(Bt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let r=(0, qi.asOrNull)(this.args[0],Mc.DivertTarget),a=(0, qi.asOrNull)(this.args[0],Jc.VariableReference);if(this.args.length!==1||r===null&&a===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}r?(this._divertTargetToCount=r,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):a&&(this._variableReferenceToCount=a,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(Bt.ControlCommand.TurnsSince()):n.AddContent(Bt.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let r=0;r<this.args.length;r+=1){let a=(0, qi.asOrNull)(this.args[r],_u.NumberExpression);if(a&&!a.isInt()){let u=r===0?"minimum":"maximum";this.Error(`RANDOM's ${u} parameter should be an integer`);}this.args[r].GenerateIntoContainer(n);}n.AddContent(Bt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let r=(0, qi.asOrNull)(this.args[0],_u.NumberExpression);r&&!r.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let r=0;r<this.args.length;r+=1)this.args[r].GenerateIntoContainer(n);n.AddContent(Bt.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.ListRandom());else if(ji.NativeFunctionCall.CallExistsWithName(this.name)){let r=ji.NativeFunctionCall.CallWithName(this.name);if(r.numberOfParameters!==this.args.length){let a=`${s.name} should take ${r.numberOfParameters} parameter`;r.numberOfParameters>1&&(a+="s"),this.Error(a);}for(let a=0;a<this.args.length;a+=1)this.args[a].GenerateIntoContainer(n);n.AddContent(ji.NativeFunctionCall.CallWithName(this.name));}else if(i!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)n.AddContent(new Kc.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.ListFromInt());else {let r=new $c.InkList;r.SetInitialOriginName(this.name),n.AddContent(new Hc.ListValue(r));}else n.AddContent(this._proxyDivert.runtimeObject),o=true;o||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(Bt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new jc.Divert(new Uc.Path(t),e),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(t){if(super.ResolveReferences(t),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let e of this.args)e.ResolveReferences(t);if(this._divertTargetToCount){let e=this._divertTargetToCount.divert,n=e.runtimeDivert.variableDivertName!=null;if(n){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${e.runtimeDivert.variableDivertName})`);return}let i=e.targetContent;if(i===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${e.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let e=this._variableReferenceToCount.runtimeVarRef;if(!e)throw new Error;e.pathForCount!==null&&this.Error(`Should be '${s.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Gi.FunctionCall=Mi;Mi.IsBuiltIn=s=>ji.NativeFunctionCall.CallExistsWithName(s)?true:s==="CHOICE_COUNT"||s==="TURNS_SINCE"||s==="TURNS"||s==="RANDOM"||s==="SEED_RANDOM"||s==="LIST_VALUE"||s==="LIST_RANDOM"||s==="READ_COUNT";});var ua=C($i=>{Object.defineProperty($i,"__esModule",{value:true});$i.MultipleConditionExpression=void 0;var zc=Et(),Xc=It(),oa=class extends zc.Expression{get subExpressions(){return this.content}constructor(t){super(),this.GenerateIntoContainer=e=>{let n=true;for(let i of this.subExpressions)i.GenerateIntoContainer(e),n||e.AddContent(Xc.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(t);}get typeName(){return "MultipleConditionExpression"}};$i.MultipleConditionExpression=oa;});var Pe=C(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.DivertTarget=void 0;var Yc=Ns(),Qc=we(),Zc=bi(),td=da(),ed=$(),la=Et(),nd=Rt(),Fu=hn(),id=ua(),wu=Ie(),ha=L(),ca=class s extends la.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(t){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=e=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new ed.DivertTargetValue,e.AddContent(this.runtimeDivertTargetValue);},this.Equals=e=>{let n=(0, ha.asOrNull)(e,s);if(!n||!this.divert.target||!n.divert.target)return false;let i=this.divert.target.dotSeparatedComponents,o=n.divert.target.dotSeparatedComponents;return i===o},this.divert=this.AddContent(t);}get typeName(){return "DivertTarget"}ResolveReferences(t){if(super.ResolveReferences(t),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let e=this;for(;e&&e instanceof la.Expression;){let i=false,o=false,r=e.parent;if(r instanceof Yc.BinaryExpression){let a=r;a.opName!=="=="&&a.opName!=="!="?i=true:(a.leftExpression instanceof s||a.leftExpression instanceof wu.VariableReference)&&(a.rightExpression instanceof s||a.rightExpression instanceof wu.VariableReference)||(i=true),o=true;}else if(r instanceof Fu.FunctionCall){let a=r;!a.isTurnsSince&&!a.isReadCount&&(i=true),o=true;}else (r instanceof la.Expression||r instanceof id.MultipleConditionExpression||r instanceof Qc.Choice&&r.condition===e||r instanceof Zc.Conditional||r instanceof td.ConditionalSingleBranch)&&(i=true,o=true);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),o)break;e=r;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let n=this.divert.targetContent;if(n!==null){let i=n.containerForCounting;if(i!==null){let r=(0, ha.asOrNull)(this.parent,Fu.FunctionCall);r&&r.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let o=(0, ha.asOrNull)(n,nd.FlowBase);if(o!=null&&o.args!==null)for(let r of o.args)r.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${o.identifier}' has 'ref ${r.identifier}').`);}}};Hi.DivertTarget=ca;});var Te=C(Ui=>{Object.defineProperty(Ui,"__esModule",{value:true});Ui.Divert=void 0;var rd=K(),cn=rt(),sd=kt(),fa=Pe(),pa=Rt(),ad=hn(),od=G(),xu=he(),ud=ct(),Ou=ue(),ld=$(),Pu=Ie(),hd=ln(),dn=L(),ma=class extends od.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(t){this._runtimeDivert=t;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(t,e){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return cn.ControlCommand.End();if(this.isDone)return cn.ControlCommand.Done();this.runtimeDivert=new sd.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let n=this.args!==null&&this.args.length>0;if(n||this.isFunctionCall||this.isTunnel||this.isThread){let i=new rd.Container;if(n){this.isFunctionCall||i.AddContent(cn.ControlCommand.EvalStart());let o=null;this.targetContent&&(o=this.targetContent.args);for(let r=0;r<this.args.length;++r){let a=this.args[r],u=null;if(o&&r<o.length&&(u=o[r]),u&&u.isByReference){let l=(0, dn.asOrNull)(a,Pu.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${a}`);break}let h=new xu.Path(l.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let d=new ld.VariablePointerValue(l.name);i.AddContent(d);}else a.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(cn.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(cn.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Ou.PushPopType.Function:Ou.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let i=(0, dn.asOrNull)((0, hd.ClosestFlowBase)(this),pa.FlowBase);if(i){let o=i.ResolveVariableWithName(n,this);if(o.found){if(o.isArgument&&o.ownerFlow&&o.ownerFlow.args){let r=o.ownerFlow.args.find(a=>{var u;return ((u=a.identifier)===null||u===void 0?void 0:u.name)==n});r&&!r.isDivertTarget&&this.Error(`Since '${r.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${r.identifier}`,o.ownerFlow);}this.runtimeDivert.variableDivertName=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let i=(0, dn.asOrNull)(this.targetContent,pa.FlowBase);if(n===0&&(i===null||!i.hasParameters))return;if(i===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&n>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof fa.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let o=i.args.length;if(o!==n){let r;n===0?r="but there weren't any passed to it":n<o?r=`but only got ${n}`:r=`but got ${n}`,this.Error(`to '${i.identifier}' requires ${o} arguments, ${r}`);return}for(let r=0;r<o;++r){let a=i.args[r],u=this.args[r];if(a.isDivertTarget){let l=(0, dn.asOrNull)(u,Pu.VariableReference);if(!(u instanceof fa.DivertTarget)&&l===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${a.identifier} but saw ${u}`,u);else if(l){let h=new xu.Path(l.pathIdentifiers);h.ResolveFromContext(l)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let i=this.target?this.target.firstComponent:null,o=n.externals.get(i);if(!o)throw new Error("external not found");let r=o.argumentNames.length,a=0;this.args&&(a=this.args.length),a!==r&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${r} but got ${a}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},t&&(this.target=t),e&&(this.args=e,this.AddContent(e));}get typeName(){return "Divert"}ResolveReferences(t){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(t);let e=(0, dn.asOrNull)(this.targetContent,pa.FlowBase);e&&(!e.isFunction&&this.isFunctionCall?super.Error(`${e.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${e.identifier} =='?`):e.isFunction&&!this.isFunctionCall&&!(this.parent instanceof fa.DivertTarget)&&super.Error(e.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+e.identifier+"(...)'"));let n=this.targetContent!==null,i=false,o=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=ad.FunctionCall.IsBuiltIn(this.target.firstComponent),o=t.IsExternal(this.target.firstComponent),i||o){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),o&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new ud.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(t));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!i&&!o&&this.Error(`target not found: '${this.target}'`);}Error(t,e=null,n=false){if(e!==this&&e){super.Error(t,e);return}this.isFunctionCall?super.Error(`Function call ${t}`,e,n):super.Error(`Divert ${t}`,e,n);}};Ui.Divert=ma;});var Tu=C(Ki=>{Object.defineProperty(Ki,"__esModule",{value:true});Ki.GatherPointToResolve=void 0;var ga=class{constructor(t,e){this.divert=t,this.targetRuntimeObj=e;}};Ki.GatherPointToResolve=ga;});var Nu=C(Ji=>{Object.defineProperty(Ji,"__esModule",{value:true});Ji.SequenceDivertToResolve=void 0;var Ca=class{constructor(t,e){this.divert=t,this.targetContent=e;}};Ji.SequenceDivertToResolve=Ca;});var va=C(zi=>{Object.defineProperty(zi,"__esModule",{value:true});zi.SequenceType=void 0;var Iu;(function(s){s[s.Stopping=1]="Stopping",s[s.Cycle=2]="Cycle",s[s.Shuffle=4]="Shuffle",s[s.Once=8]="Once";})(Iu||(zi.SequenceType=Iu={}));});var Sa=C(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.Sequence=void 0;var ku=K(),wt=rt(),Da=kt(),fn=$(),Xi=It(),cd=G(),dd=Nu(),Yi=va(),fd=ce(),Ea=class extends cd.ParsedObject{constructor(t,e){super(),this.sequenceType=e,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new ku.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(wt.ControlCommand.EvalStart()),n.AddContent(wt.ControlCommand.VisitIndex());let i=(this.sequenceType&Yi.SequenceType.Once)>0,o=(this.sequenceType&Yi.SequenceType.Cycle)>0,r=(this.sequenceType&Yi.SequenceType.Stopping)>0,a=(this.sequenceType&Yi.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),r||i?(n.AddContent(new fn.IntValue(u-1)),n.AddContent(Xi.NativeFunctionCall.CallWithName("MIN"))):o&&(n.AddContent(new fn.IntValue(this.sequenceElements.length)),n.AddContent(Xi.NativeFunctionCall.CallWithName("%"))),a){let h=wt.ControlCommand.NoOp();if(i||r){let d=r?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(wt.ControlCommand.Duplicate()),n.AddContent(new fn.IntValue(d)),n.AddContent(Xi.NativeFunctionCall.CallWithName("=="));let m=new Da.Divert;m.isConditional=true,n.AddContent(m),this.AddDivertToResolve(m,h);}let c=this.sequenceElements.length;r&&(c-=1),n.AddContent(new fn.IntValue(c)),n.AddContent(wt.ControlCommand.SequenceShuffleIndex()),(i||r)&&n.AddContent(h);}n.AddContent(wt.ControlCommand.EvalEnd());let l=wt.ControlCommand.NoOp();for(let h=0;h<u;h+=1){n.AddContent(wt.ControlCommand.EvalStart()),n.AddContent(wt.ControlCommand.Duplicate()),n.AddContent(new fn.IntValue(h)),n.AddContent(Xi.NativeFunctionCall.CallWithName("==")),n.AddContent(wt.ControlCommand.EvalEnd());let c=new Da.Divert;c.isConditional=true,n.AddContent(c);let d;h<this.sequenceElements.length?d=this.sequenceElements[h].runtimeObject:d=new ku.Container,d.name=`s${h}`,d.InsertContent(wt.ControlCommand.PopEvaluatedValue(),0);let m=new Da.Divert;d.AddContent(m),n.AddToNamedContentOnly(d),this.AddDivertToResolve(c,d),this.AddDivertToResolve(m,l);}return n.AddContent(l),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new dd.SequenceDivertToResolve(n,i));},this.sequenceType=e,this.sequenceElements=[];for(let n of t){let i=n.content,o=null;i===null||i.length===0?o=n:o=new fd.Weave(i),this.sequenceElements.push(o),this.AddContent(o);}}get typeName(){return "Sequence"}ResolveReferences(t){super.ResolveReferences(t);for(let e of this._sequenceDivertsToResolve)e.divert.targetPath=e.targetContent.path;}};Qi.Sequence=Ea;});var ba=C(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.TunnelOnwards=void 0;var pd=K(),pn=rt(),md=kt(),gd=$(),Cd=G(),vd=oe(),Dd=L(),Ed=Ne(),ya=class extends Cd.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let t=new pd.Container;if(t.AddContent(pn.ControlCommand.EvalStart()),this.divertAfter){let e=this.divertAfter.GenerateRuntimeObject(),n=e;if(n){let o=this.divertAfter.args;if(o!==null&&o.length>0){let r=-1,a=-1;for(let u=0;u<n.content.length;u+=1){let l=n.content[u];l&&(r==-1&&l.commandType===pn.ControlCommand.CommandType.EvalStart?r=u:l.commandType===pn.ControlCommand.CommandType.EvalEnd&&(a=u));}for(let u=r+1;u<a;u+=1){let l=n.content[u];l.parent=null,t.AddContent(n.content[u]);}}}let i=(0, Dd.asOrNull)(e,md.Divert);if(i!=null&&i.hasVariableTarget){let o=new Ed.VariableReference(i.variableDivertName);t.AddContent(o);}else this._overrideDivertTarget=new gd.DivertTargetValue,t.AddContent(this._overrideDivertTarget);}else t.AddContent(new vd.Void);return t.AddContent(pn.ControlCommand.EvalEnd()),t.AddContent(pn.ControlCommand.PopTunnel()),t},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(t){this._divertAfter=t,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(t){super.ResolveReferences(t),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};Zi.TunnelOnwards=ya;});var Fa=C(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.ListDefinition=void 0;var Aa=pt(),_a=class{constructor(t,e){this._name=t||"",this._items=null,this._itemNameToValues=e||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[t,e]of this._itemNameToValues){let n=new Aa.InkListItem(this.name,t);this._items.set(n.serialized(),e);}}return this._items}ValueForItem(t){if(!t.itemName)return 0;let e=this._itemNameToValues.get(t.itemName);return typeof e<"u"?e:0}ContainsItem(t){return !t.itemName||t.originName!=this.name?false:this._itemNameToValues.has(t.itemName)}ContainsItemWithName(t){return this._itemNameToValues.has(t)}TryGetItemWithValue(t,e){for(let[n,i]of this._itemNameToValues)if(i==t)return e=new Aa.InkListItem(this.name,n),{result:e,exists:true};return e=Aa.InkListItem.Null,{result:e,exists:false}}TryGetValueForItem(t,e){if(!t.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(t.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};tr.ListDefinition=_a;});var nr=C(er=>{Object.defineProperty(er,"__esModule",{value:true});er.ListDefinition=void 0;var Sd=pt(),yd=pt(),bd=Fa(),Ad=$(),_d=G(),Fd=Gt(),wa=class extends _d.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var t;let e=new Map;for(let n of this.itemDefinitions)e.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):e.set(n.name,n.seriesValue);return new bd.ListDefinition(((t=this.identifier)===null||t===void 0?void 0:t.name)||"",e)}constructor(t){super(),this.itemDefinitions=t,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let o of this.itemDefinitions)this._elementsByName.set(o.name,o);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,i;let o=new Sd.InkList;for(let r of this.itemDefinitions)if(r.inInitialList){let a=new yd.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,r.name||null);o.Add(a,r.seriesValue);}return o.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new Ad.ListValue(o)};let e=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(e=n.explicitValue),n.seriesValue=e,e+=1;this.AddContent(t);}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.identifier,Fd.SymbolType.List);}};er.ListDefinition=wa;});var Oa=C(ir=>{Object.defineProperty(ir,"__esModule",{value:true});ir.VariableAssignment=void 0;var wd=K(),xd=ln(),Od=nr(),Pd=G(),Ru=Gt(),Td=zt(),Nd=Ie(),Id=L(),xa=class extends Pd.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:t,isGlobalDeclaration:e,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:o}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let r=null;if(this.isGlobalDeclaration?r=this.story:this.isNewTemporaryDeclaration&&(r=(0, xd.ClosestFlowBase)(this)),r&&r.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let a=new wd.Container;return this.expression?a.AddContent(this.expression.runtimeObject):this.listDefinition&&a.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Td.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),a.AddContent(this._runtimeAssignment),a},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=o,this.isGlobalDeclaration=!!e,this.isNewTemporaryDeclaration=!!n,i instanceof Od.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):t&&(this.expression=this.AddContent(t));}ResolveReferences(t){if(super.ResolveReferences(t),this.isDeclaration&&this.listDefinition===null&&t.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?Ru.SymbolType.Var:Ru.SymbolType.Temp),this.isGlobalDeclaration){let e=(0, Id.asOrNull)(this.expression,Nd.VariableReference);e&&!e.isConstantReference&&!e.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let e=t.ResolveVariableWithName(this.variableName,this);e.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=e.isGlobal);}}};ir.VariableAssignment=xa;});var ce=C(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.Weave=void 0;var Vu=jn(),yt=we(),rr=bi(),kd=Fi(),Rd=K(),sr=Te(),Vd=kt(),Bd=Pe(),Ld=Rt(),Lt=un(),Wd=Tu(),qd=G(),Pa=Sa(),jd=Yt(),Md=ba(),Gd=Oa(),bt=L(),Ta=class s extends qd.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let t=null;for(let n=this.content.length-1;n>=0;--n){t=this.content[n];let i=(0, bt.asOrNull)(t,jd.Text);if(!(i&&i.text===`
15
- `)&&!this.IsGlobalDeclaration(t))break}let e=(0, bt.asOrNull)(t,s);return e&&(t=e.lastParsedSignificantObject),t}constructor(t,e=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var n,i,o;let r=[...this.FindAll(Lt.Gather)(a=>!(a.name===null||a.name===void 0)),...this.FindAll(yt.Choice)(a=>!(a.name===null||a.name===void 0))];this._namedWeavePoints=new Map;for(let a of r){let u=this.namedWeavePoints.get(((n=a.identifier)===null||n===void 0?void 0:n.name)||"");if(u){let l=u instanceof Lt.Gather?"gather":"choice",h=u;this.Error(`A ${l} with the same label name '${a.name}' already exists in this context on line ${h.debugMetadata?h.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,a);}!((i=a.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((o=a.identifier)===null||o===void 0?void 0:o.name,a);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;n<this.content.length;){let i=this.content[n];if(i instanceof yt.Choice||i instanceof Lt.Gather){let r=i.indentationDepth-1;if(r>this.baseIndentIndex){let a=n;for(;n<this.content.length;){let c=(0, bt.asOrNull)(this.content[n],yt.Choice)||(0, bt.asOrNull)(this.content[n],Lt.Gather);if(c!==null&&c.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let u=n-a,l=this.content.slice(a,a+u);this.content.splice(a,u);let h=new s(l,r);this.InsertContent(a,h),n=a;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let i of n)if(i instanceof yt.Choice||i instanceof Lt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new Rd.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof yt.Choice||n instanceof Lt.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof s){let i=n;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let o=n.runtimeContainer;if(n.name||(o.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(o);}else this.rootContainer.AddToNamedContentOnly(o);for(let r of this.looseEnds){let a=r;if(a instanceof Lt.Gather&&a.indentationDepth==n.indentationDepth)continue;let u=null;if(a instanceof sr.Divert)u=a.runtimeObject;else {u=new Vd.Divert;let l=a;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new Wd.GatherPointToResolve(u,o));}this.looseEnds=[],this.currentContainer=o;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof Lt.Gather)this.AddRuntimeForGather(n);else if(n instanceof yt.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Lt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=n;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, bt.asOrNull)(n,yt.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=n;},this.AddRuntimeForNestedWeave=n=>{this.AddGeneralRuntimeContent(n.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=n=>{if(n!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(n);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let n=null,i=null,o=false;for(let r=this.parent;r!==null;r=r.parent){let a=(0, bt.asOrNull)(r,s);a&&(!o&&n===null&&(n=a),o&&i===null&&(i=a)),(r instanceof Pa.Sequence||r instanceof rr.Conditional)&&(o=true);}if(!(n===null&&i===null))for(let r=this.looseEnds.length-1;r>=0;r-=1){let a=this.looseEnds[r],u=false;if(o){if(a instanceof yt.Choice&&n!==null)n.ReceiveLooseEnd(a),u=true;else if(!(a instanceof yt.Choice)){let l=n||i;l!==null&&(l.ReceiveLooseEnd(a),u=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(a),u=true;u&&this.looseEnds.splice(r,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(n);return i||null},this.IsGlobalDeclaration=n=>{let i=(0, bt.asOrNull)(n,Gd.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, bt.asOrNull)(n,kd.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let i=[],o=n;if(o.content!==null)for(let u of o.content)this.IsGlobalDeclaration(u)||i.push(u);let r=(0, bt.asOrNull)(o.parent,s);if(r===null)throw new Error("Expected weave point parent to be weave?");let a=r.content.indexOf(o);for(let u=a+1;u<r.content.length;u+=1){let l=r.content[u];if(!this.IsGlobalDeclaration(l)){if(l instanceof yt.Choice||l instanceof Lt.Gather||l instanceof s)break;i.push(l);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof Vu.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let o of this.looseEnds){let r=this.ContentThatFollowsWeavePoint(o);this.ValidateFlowOfObjectsTerminates(r,o,n);}else {for(let o of this.content)if(o instanceof yt.Choice||o instanceof sr.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let i=null;for(let r=n.parent;r!==null;r=r.parent)if(r instanceof Pa.Sequence||r instanceof rr.Conditional){i=(0, bt.asOrNull)(r,rr.Conditional);break}let o="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(yt.Choice)().length===1&&(o=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${o.toLowerCase()}`),this.Error(o,n);},this.ValidateFlowOfObjectsTerminates=(n,i,o)=>{let r=false,a=i;for(let u of n){if(u.Find(sr.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof Bd.DivertTarget))!==null&&(r=true),u.Find(Md.TunnelOnwards)()!=null){r=true;break}a=u;}if(!r){if(a instanceof Vu.AuthorWarning)return;o(a);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return true;for(let i=n.content.length-1;i>=0;--i){let o=(0, bt.asOrNull)(n.content[i],sr.Divert);if(o&&!(o.isThread||o.isTunnel||o.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let i of this.ancestry){let o=(0, bt.asOrNull)(i,Ld.FlowBase);if(o)n.push(o);else break}for(let[i,o]of this.namedWeavePoints)for(let r of n){let a=r.ContentWithNameAtLevel(i);if(a&&a!==o){let u=`${o.GetType()} '${i}' has the same label name as a ${a.GetType()} (on ${a.debugMetadata})`;this.Error(u,o);}}},e==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(t):this.baseIndentIndex=e,this.AddContent(t),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(t){if(super.ResolveReferences(t),this.looseEnds!==null&&this.looseEnds.length>0){let e=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof Pa.Sequence||n instanceof rr.Conditional){e=true;break}e&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let e of this.gatherPointsToResolve)e.divert.targetPath=e.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};ar.Weave=Ta;});var da=C(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.ConditionalSingleBranch=void 0;var Bu=K(),or=rt(),Lu=kt(),$d=G(),Hd=It(),Ud=$(),Kd=Yt(),Jd=ce(),zd=L(),Na=class extends $d.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(t){this._ownExpression=t,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(t){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let o=(0, zd.asOrNull)(i,Kd.Text);o&&o.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",o);}let e=new Bu.Container,n=this.matchingEquality&&!this.isElse;if(n&&e.AddContent(or.ControlCommand.Duplicate()),this._conditionalDivert=new Lu.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&e.AddContent(or.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(e),this.matchingEquality&&e.AddContent(Hd.NativeFunctionCall.CallWithName("==")),i&&e.AddContent(or.ControlCommand.EvalEnd());}return e.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new Ud.StringValue(`
16
- `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(or.ControlCommand.PopEvaluatedValue(),0),e.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Lu.Divert,this._contentContainer.AddContent(this.returnDivert),e},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new Bu.Container:this._innerWeave.rootContainer,t&&(this._innerWeave=new Jd.Weave(t),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(t){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(t);}};ur.ConditionalSingleBranch=Na;});var qu=C(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.CustomFlags=void 0;var Wu;(function(s){s[s.ParsingString=1]="ParsingString",s[s.TagActive=2]="TagActive";})(Wu||(lr.CustomFlags=Wu={}));});var ju=C(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.DebugMetadata=void 0;var Ia=class s{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(t){let e=new s;return e.fileName=this.fileName,e.sourceName=this.sourceName,this.startLineNumber<t.startLineNumber?(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>t.startLineNumber?(e.startLineNumber=t.startLineNumber,e.startCharacterNumber=t.startCharacterNumber):(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=Math.min(this.startCharacterNumber,t.startCharacterNumber)),this.endLineNumber>t.endLineNumber?(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<t.endLineNumber?(e.endLineNumber=t.endLineNumber,e.endCharacterNumber=t.endCharacterNumber):(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=Math.max(this.endCharacterNumber,t.endCharacterNumber)),e}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};hr.DebugMetadata=Ia;});var Mu=C(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.ExternalDeclaration=void 0;var Xd=G(),ka=class extends Xd.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e){super(),this.identifier=t,this.argumentNames=e,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var t;return `EXTERNAL ${(t=this.identifier)===null||t===void 0?void 0:t.name}`}};cr.ExternalDeclaration=ka;});var Gu=C(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.FlowDecl=void 0;var Ra=class{constructor(t,e,n){this.name=t,this.args=e,this.isFunction=n;}};dr.FlowDecl=Ra;});var Ba=C(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.Wrap=void 0;var Yd=G(),Va=class extends Yd.ParsedObject{constructor(t){super(),this._objToWrap=t,this.GenerateRuntimeObject=()=>this._objToWrap;}};fr.Wrap=Va;});var $u=C(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.Glue=void 0;var Qd=Ba(),La=class extends Qd.Wrap{constructor(t){super(t);}get typeName(){return "Glue"}};pr.Glue=La;});var gr=C(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.Glue=void 0;var Zd=dt(),Wa=class extends Zd.InkObject{toString(){return "Glue"}};mr.Glue=Wa;});var Uu=C(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.IncDecExpression=void 0;var tf=Bi(),Hu=Et(),ef=Rt(),nf=It(),rf=$(),sf=zt(),af=Ne(),of=ce(),qa=class extends Hu.Expression{constructor(t,e,n){super(),this.varIdentifier=t,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var o,r;i.AddContent(new af.VariableReference(((o=this.varIdentifier)===null||o===void 0?void 0:o.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new rf.IntValue(1)),i.AddContent(nf.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new sf.VariableAssignment(((r=this.varIdentifier)===null||r===void 0?void 0:r.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,o;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(o=this.varIdentifier)===null||o===void 0?void 0:o.name}`+(this.isInc?"++":"--")},e instanceof Hu.Expression?(this.expression=e,this.AddContent(this.expression),this.isInc=!!n):this.isInc=e;}get typeName(){return "IncDecExpression"}ResolveReferences(t){var e;super.ResolveReferences(t);let n=t.ResolveVariableWithName(((e=this.varIdentifier)===null||e===void 0?void 0:e.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof of.Weave)&&!(this.parent instanceof ef.FlowBase)&&!(this.parent instanceof tf.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Cr.IncDecExpression=qa;});var Ma=C(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.IncludedFile=void 0;var uf=G(),ja=class extends uf.ParsedObject{constructor(t){super(),this.includedStory=t,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};vr.IncludedFile=ja;});var Ku=C(Dr=>{Object.defineProperty(Dr,"__esModule",{value:true});Dr.InfixOperator=void 0;var Ga=class{constructor(t,e,n){this.type=t,this.precedence=e,this.requireWhitespace=n,this.toString=()=>this.type;}};Dr.InfixOperator=Ga;});var Ha=C(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.Knot=void 0;var lf=Rt(),Ju=xe(),$a=class extends lf.FlowBase{get flowLevel(){return Ju.FlowLevel.Knot}constructor(t,e,n,i){super(t,e,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(t){super.ResolveReferences(t);let e=this.story;for(let n in this.subFlowsByName){let i=e.ContentWithNameAtLevel(n,Ju.FlowLevel.Knot,false);if(i){let o=this.subFlowsByName.get(n),r=`Stitch '${o?o.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(r,o);}}}};Er.Knot=$a;});var zu=C(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.List=void 0;var hf=Et(),cf=pt(),df=pt(),ff=$(),Ua=class extends hf.Expression{constructor(t){super(),this.itemIdentifierList=t,this.GenerateIntoContainer=e=>{var n,i;let o=new cf.InkList;if(this.itemIdentifierList!=null)for(let r of this.itemIdentifierList){let a=((n=r?.name)===null||n===void 0?void 0:n.split("."))||[],u=null,l="";a.length>1?(u=a[0],l=a[1]):l=a[0];let h=this.story.ResolveListItem(u,l,this);if(h===null)u===null?this.Error(`Could not find list definition that contains item '${r}'`):this.Error(`Could not find list item ${r}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${r}`);return}u||(u=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new df.InkListItem(u,h.name||null);o.has(c.serialized())?this.Warning(`Duplicate of item '${r}' in list.`):o.Add(c,h.seriesValue);}}e.AddContent(new ff.ListValue(o));};}get typeName(){return "List"}};Sr.List=Ua;});var Ja=C(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.ListElementDefinition=void 0;var pf=G(),mf=Gt(),Ka=class extends pf.ParsedObject{get fullName(){var t;let e=this.parent;if(e===null)throw new Error("Can't get full name without a parent list.");return `${(t=e.identifier)===null||t===void 0?void 0:t.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var t;return ((t=this.indentifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e,n=null){super(),this.indentifier=t,this.inInitialList=e,this.explicitValue=n,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.indentifier,mf.SymbolType.ListItem);}};yr.ListElementDefinition=Ka;});var za=C(br=>{Object.defineProperty(br,"__esModule",{value:true});br.StatementLevel=void 0;var Xu;(function(s){s[s.InnerBlock=0]="InnerBlock",s[s.Stitch=1]="Stitch",s[s.Knot=2]="Knot",s[s.Top=3]="Top";})(Xu||(br.StatementLevel=Xu={}));});var Ya=C(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.Stitch=void 0;var gf=Rt(),Cf=xe(),Xa=class extends gf.FlowBase{get flowLevel(){return Cf.FlowLevel.Stitch}constructor(t,e,n,i){super(t,e,n,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};Ar.Stitch=Xa;});var Fr=C(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.Tag=void 0;var vf=dt(),Qa=class extends vf.InkObject{constructor(t){super(),this.text=t.toString()||"";}toString(){return "# "+this.text}};_r.Tag=Qa;});var to=C(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.Choice=void 0;var Df=ct(),Ef=it(),Sf=dt(),Za=class s extends Sf.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, Ef.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new Df.Path(t);}Clone(){let t=new s;return t.text=this.text,t.sourcePath=this.sourcePath,t.index=this.index,t.targetPath=this.targetPath,t.originalThreadIndex=this.originalThreadIndex,t.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(t.threadAtGeneration=this.threadAtGeneration.Copy()),t}};wr.Choice=Za;});var no=C(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.ListDefinitionsOrigin=void 0;var yf=pt(),bf=$(),Af=it(),eo=class{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let e of t){this._lists.set(e.name,e);for(let[n,i]of e.items){let o=yf.InkListItem.fromSerializedKey(n),r=new bf.ListValue(o,i);if(!o.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(o.itemName,r),this._allUnambiguousListValueCache.set(o.fullName,r);}}}get lists(){let t=[];for(let[,e]of this._lists)t.push(e);return t}TryListGetDefinition(t,e){if(t===null)return {result:e,exists:false};let n=this._lists.get(t);return n?{result:n,exists:true}:{result:e,exists:false}}FindSingleItemListWithName(t){if(t===null)return (0, Af.throwNullException)("name");let e=this._allUnambiguousListValueCache.get(t);return typeof e<"u"?e:null}};xr.ListDefinitionsOrigin=eo;});var Re=C(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.JsonSerialisation=void 0;var Or=K(),gt=$(),Yu=gr(),V=rt(),ke=ue(),Qu=kt(),Zu=li(),io=Ne(),tl=zt(),ro=It(),el=oe(),nl=Fr(),_f=ct(),il=to(),Ff=Fa(),wf=no(),Pr=pt(),J=L(),de=it(),Tr=class s{static JArrayToRuntimeObjList(t,e=false){let n=t.length;e&&n--;let i=[];for(let o=0;o<n;o++){let r=t[o],a=this.JTokenToRuntimeObject(r);if(a===null)return (0, de.throwNullException)("runtimeObj");i.push(a);}return i}static WriteDictionaryRuntimeObjs(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WritePropertyStart(n),this.WriteRuntimeObject(t,i),t.WritePropertyEnd();t.WriteObjectEnd();}static WriteListRuntimeObjs(t,e){t.WriteArrayStart();for(let n of e)this.WriteRuntimeObject(t,n);t.WriteArrayEnd();}static WriteIntDictionary(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WriteIntProperty(n,i);t.WriteObjectEnd();}static WriteRuntimeObject(t,e){let n=(0, J.asOrNull)(e,Or.Container);if(n){this.WriteRuntimeContainer(t,n);return}let i=(0, J.asOrNull)(e,Qu.Divert);if(i){let p="->";i.isExternal?p="x()":i.pushesToStack&&(i.stackPushType==ke.PushPopType.Function?p="f()":i.stackPushType==ke.PushPopType.Tunnel&&(p="->t->"));let E;i.hasVariableTarget?E=i.variableDivertName:E=i.targetPathString,t.WriteObjectStart(),t.WriteProperty(p,E),i.hasVariableTarget&&t.WriteProperty("var",true),i.isConditional&&t.WriteProperty("c",true),i.externalArgs>0&&t.WriteIntProperty("exArgs",i.externalArgs),t.WriteObjectEnd();return}let o=(0, J.asOrNull)(e,Zu.ChoicePoint);if(o){t.WriteObjectStart(),t.WriteProperty("*",o.pathStringOnChoice),t.WriteIntProperty("flg",o.flags),t.WriteObjectEnd();return}let r=(0, J.asOrNull)(e,gt.BoolValue);if(r){t.WriteBool(r.value);return}let a=(0, J.asOrNull)(e,gt.IntValue);if(a){t.WriteInt(a.value);return}let u=(0, J.asOrNull)(e,gt.FloatValue);if(u){t.WriteFloat(u.value);return}let l=(0, J.asOrNull)(e,gt.StringValue);if(l){l.isNewline?t.Write(`
17
- `,false):(t.WriteStringStart(),t.WriteStringInner("^"),t.WriteStringInner(l.value),t.WriteStringEnd());return}let h=(0, J.asOrNull)(e,gt.ListValue);if(h){this.WriteInkList(t,h);return}let c=(0, J.asOrNull)(e,gt.DivertTargetValue);if(c){if(t.WriteObjectStart(),c.value===null)return (0, de.throwNullException)("divTargetVal.value");t.WriteProperty("^->",c.value.componentsString),t.WriteObjectEnd();return}let d=(0, J.asOrNull)(e,gt.VariablePointerValue);if(d){t.WriteObjectStart(),t.WriteProperty("^var",d.value),t.WriteIntProperty("ci",d.contextIndex),t.WriteObjectEnd();return}if((0, J.asOrNull)(e,Yu.Glue)){t.Write("<>");return}let D=(0, J.asOrNull)(e,V.ControlCommand);if(D){t.Write(s._controlCommandNames[D.commandType]);return}let v=(0, J.asOrNull)(e,ro.NativeFunctionCall);if(v){let p=v.name;p=="^"&&(p="L^"),t.Write(p);return}let A=(0, J.asOrNull)(e,io.VariableReference);if(A){t.WriteObjectStart();let p=A.pathStringForCount;p!=null?t.WriteProperty("CNT?",p):t.WriteProperty("VAR?",A.name),t.WriteObjectEnd();return}let S=(0, J.asOrNull)(e,tl.VariableAssignment);if(S){t.WriteObjectStart();let p=S.isGlobal?"VAR=":"temp=";t.WriteProperty(p,S.variableName),S.isNewDeclaration||t.WriteProperty("re",true),t.WriteObjectEnd();return}if((0, J.asOrNull)(e,el.Void)){t.Write("void");return}let f=(0, J.asOrNull)(e,nl.Tag);if(f){t.WriteObjectStart(),t.WriteProperty("#",f.text),t.WriteObjectEnd();return}let y=(0, J.asOrNull)(e,il.Choice);if(y){this.WriteChoice(t,y);return}throw new Error("Failed to convert runtime object to Json token: "+e)}static JObjectToDictionaryRuntimeObjs(t){let e=new Map;for(let n in t)if(t.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(t[n]);if(i===null)return (0, de.throwNullException)("inkObject");e.set(n,i);}return e}static JObjectToIntDictionary(t){let e=new Map;for(let n in t)t.hasOwnProperty(n)&&e.set(n,parseInt(t[n]));return e}static JTokenToRuntimeObject(t){if(typeof t=="number"&&!isNaN(t)||typeof t=="boolean")return gt.Value.Create(t);if(typeof t=="string"){let e=t.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(e);if(n)return new gt.FloatValue(parseFloat(n[0]));let i=e[0];if(i=="^")return new gt.StringValue(e.substring(1));if(i==`
14
+ `.repeat(this.lineIndex-t):null};}PreProcessInputString(t){return t}};Si.CommentEliminator=Us;});var Ai=C(bi=>{Object.defineProperty(bi,"__esModule",{value:true});bi.Conditional=void 0;var rc=J(),Du=rt(),sc=$(),Ks=class extends sc.ParsedObject{constructor(t,e){super(),this.initialCondition=t,this.branches=e,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new rc.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let o=i.runtimeObject;n.AddContent(o);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(Du.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Du.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(t){let e=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=e;}super.ResolveReferences(t);}};bi.Conditional=Ks;});var Yt=C(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.Text=void 0;var ac=$(),oc=H(),Js=class extends ac.ParsedObject{constructor(t){super(),this.text=t,this.GenerateRuntimeObject=()=>new oc.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};_i.Text=Js;});var wi=C(Fi=>{Object.defineProperty(Fi,"__esModule",{value:true});Fi.ConstantDeclaration=void 0;var uc=$(),lc=Gt(),zs=class extends uc.ParsedObject{get constantName(){var t;return (t=this.constantIdentifier)===null||t===void 0?void 0:t.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(t,e){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=t,e&&(this._expression=this.AddContent(e));}get typeName(){return "CONST"}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.constantIdentifier,lc.SymbolType.Var);}};Fi.ConstantDeclaration=zs;});var xe=C(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.FlowLevel=void 0;var Eu;(function(s){s[s.Story=0]="Story",s[s.Knot=1]="Knot",s[s.Stitch=2]="Stitch",s[s.WeavePoint=3]="WeavePoint";})(Eu||(xi.FlowLevel=Eu={}));});var ln=C(Oi=>{Object.defineProperty(Oi,"__esModule",{value:true});Oi.Gather=void 0;var hc=J(),cc=$(),dc=Gt(),Xs=class extends cc.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(t,e){super(),this.indentationDepth=e,this.GenerateRuntimeObject=()=>{let n=new hc.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let i of this.content)n.AddContent(i.runtimeObject);return n},this.toString=()=>{var n,i;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},t&&(this.identifier=t);}get typeName(){return "Gather"}ResolveReferences(t){super.ResolveReferences(t),this.identifier&&(this.identifier.name||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,dc.SymbolType.SubFlowAndWeave);}};Oi.Gather=Xs;});var he=C(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.Path=void 0;var Pi=W(),yu=Rt(),Oe=xe(),fc=ce(),Ys=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Oe.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(t=>t.name).filter(Pi.filterUndef).join(".")),this._dotSeparatedComponents}constructor(t,e){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Oe.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(n);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=n=>{let i=this.firstComponent,o=n;for(;o;){let r=o===n,a=this.GetChildFromContext(o,i,null,r);if(a)return a;o=o.parent;}return null},this.ResolveTailComponents=n=>{let i=n;if(!this.components)return null;for(let o=1;o<this.components.length;++o){let r=this.components[o].name,a,u=(0, Pi.asOrNull)(i,yu.FlowBase);if(u!==null?a=u.flowLevel+1:a=Oe.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,r,a),i===null)break}return i},this.GetChildFromContext=(n,i,o,r=false)=>{let a=o===null,u=(0, Pi.asOrNull)(n,fc.Weave);if(i&&u!==null&&(a||o===Oe.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, Pi.asOrNull)(n,yu.FlowBase);if(i&&l!==null){let h=r||l.flowLevel===Oe.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,o,h)}return null},Object.values(Oe.FlowLevel).includes(t)?(this._baseTargetLevel=t,this.components=e||[]):Array.isArray(t)?(this._baseTargetLevel=null,this.components=t||[]):(this._baseTargetLevel=null,this.components=[t]);}get typeName(){return "Path"}};Ti.Path=Ys;});var ta=C(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.ReturnType=void 0;var pc=$(),mc=J(),Qs=rt(),gc=oe(),Zs=class extends pc.ParsedObject{constructor(t=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let e=new mc.Container;return this.returnedExpression?e.AddContent(this.returnedExpression.runtimeObject):(e.AddContent(Qs.ControlCommand.EvalStart()),e.AddContent(new gc.Void),e.AddContent(Qs.ControlCommand.EvalEnd())),e.AddContent(Qs.ControlCommand.PopFunction()),e},t&&(this.returnedExpression=this.AddContent(t));}get typeName(){return "ReturnType"}};Ni.ReturnType=Zs;});var hn=C(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.ClosestFlowBase=void 0;function Cc(s){let t=s.parent;for(;t;){if(t.hasOwnProperty("iamFlowbase")&&t.iamFlowbase())return t;t=t.parent;}return null}Ii.ClosestFlowBase=Cc;});var Ri=C(ki=>{Object.defineProperty(ki,"__esModule",{value:true});ki.Identifier=void 0;var ea=class s{constructor(t){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=t;}get typeName(){return "Identifier"}static Done(){return new s("DONE")}};ki.Identifier=ea;});var Rt=C(Vi=>{Object.defineProperty(Vi,"__esModule",{value:true});Vi.FlowBase=void 0;var vc=we(),na=Te(),Dc=Pe(),Vt=xe(),Ec=ln(),yc=$(),Sc=he(),bc=ta(),Ac=J(),_c=kt(),Fc=zt(),ia=Gt(),wc=ce(),xc=hn(),Oc=Ri(),Su=W(),ra=class s extends yc.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e=null,n=null,i=false,o=false){super(),this.isFunction=i,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(r,a)=>{var u,l;let h=[],c=[];this._subFlowsByName=new Map;for(let g of r){let E=(0, Su.asOrNull)(g,s);E?(this._firstChildFlow===null&&(this._firstChildFlow=E),c.push(g),!((u=E.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=E.identifier)===null||l===void 0?void 0:l.name,E)):h.push(g);}a&&h.push(new Ec.Gather(null,1),new na.Divert(new Sc.Path(Oc.Identifier.Done())));let m=[];return h.length>0&&(this._rootWeave=new wc.Weave(h,0),m.push(this._rootWeave)),c.length>0&&m.push(...c),m},this.ResolveVariableWithName=(r,a)=>{var u;let l={},h=a===null?this:(0, xc.ClosestFlowBase)(a);if(h){if(h.args!==null){for(let c of h.args)if(((u=c.identifier)===null||u===void 0?void 0:u.name)===r)return l.found=true,l.isArgument=true,l.ownerFlow=h,l}if(h!==this.story&&h.variableDeclarations.has(r))return l.found=true,l.ownerFlow=h,l.isTemporary=true,l}return this.story.variableDeclarations.has(r)?(l.found=true,l.ownerFlow=this.story,l.isGlobal=true,l):(l.found=false,l)},this.AddNewVariableDeclaration=r=>{let a=r.variableName;if(this.variableDeclarations.has(a)){let u=this.variableDeclarations.get(a),l="";u.debugMetadata&&(l=` (${u.debugMetadata})`),this.Error(`found declaration variable '${a}' that was already declared${l}`,r,false);return}this.variableDeclarations.set(r.variableName,r);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,r]of this._subFlowsByName)r.hasOwnProperty("ResolveWeavePointNaming")&&r.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var r;let a=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===Vt.FlowLevel.Knot||this.flowLevel===Vt.FlowLevel.Stitch)&&(a=this.Find(bc.ReturnType)(),a!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,a));let u=new Ac.Container;u.name=(r=this.identifier)===null||r===void 0?void 0:r.name,this.story.countAllVisits&&(u.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(u);let l=0;for(;this.content!==null&&l<this.content.length;){let h=this.content[l];if(h instanceof s){let c=h,m=c.runtimeObject;l===0&&!c.hasParameters&&this.flowLevel===Vt.FlowLevel.Knot&&(this._startingSubFlowDivert=new _c.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=m);let g=m,E=u.namedContent.get(g.name)||null;if(E){let v=`${this.GetType()} already contains flow named '${g.name}' (at ${E.debugMetadata})`;this.Error(v,c);}u.AddToNamedContentOnly(g);}else h&&u.AddContent(h.runtimeObject);l+=1;}return this.flowLevel!==Vt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&a===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),u},this.GenerateArgumentVariableAssignments=r=>{var a;if(!(this.args===null||this.args.length===0))for(let u=this.args.length-1;u>=0;--u){let l=((a=this.args[u].identifier)===null||a===void 0?void 0:a.name)||null,h=new Fc.VariableAssignment(l,true);r.AddContent(h);}},this.ContentWithNameAtLevel=(r,a=null,u=false)=>{var l;if((a===this.flowLevel||a===null)&&r===((l=this.identifier)===null||l===void 0?void 0:l.name))return this;if(a===Vt.FlowLevel.WeavePoint||a===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(r),c))return c;if(a===Vt.FlowLevel.WeavePoint)return u?this.DeepSearchForAnyLevelContent(r):null}if(a!==null&&a<this.flowLevel)return null;let h=this._subFlowsByName.get(r)||null;return h&&(a===null||a===h.flowLevel)?h:u?this.DeepSearchForAnyLevelContent(r):null},this.DeepSearchForAnyLevelContent=r=>{let a=this.ContentWithNameAtLevel(r,Vt.FlowLevel.WeavePoint,false);if(a)return a;for(let[,u]of this._subFlowsByName){let l=u.ContentWithNameAtLevel(r,null,true);if(l)return l}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==Vt.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[u,l]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${u}' within the function '${this.identifier}'`,l);if(!this._rootWeave)throw new Error;let r=this._rootWeave.FindAll(na.Divert)();for(let u of r)!u.isFunctionCall&&!(u.parent instanceof Dc.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let a=this._rootWeave.FindAll(vc.Choice)();for(let u of a)this.Error(`Functions may not contain choices, but saw '${u}'`,u);},this.WarningInTermination=r=>{let a="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";r.parent===this._rootWeave&&this._firstChildFlow&&(a=`${a} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let u=(0, Su.asOrNull)(r,na.Divert);u&&u.isTunnel&&(a+=` When final tunnel to '${u.target} ->' returns it won't have anywhere to go.`),this.Warning(a,r);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=t,this.args=n,e===null&&(e=[]),this.PreProcessTopLevelObjects(e),e=this.SplitWeaveAndSubFlowContent(e,this.GetType()=="Story"&&!o),this.AddContent(e);}PreProcessTopLevelObjects(t){}ResolveReferences(t){var e,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(t),this.args!==null){for(let i of this.args)t.CheckForNamingCollisions(this,i.identifier,ia.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let o=i+1;o<this.args.length;o+=1)((e=this.args[i].identifier)===null||e===void 0?void 0:e.name)==((n=this.args[o].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==Vt.FlowLevel.Story){let i=this.flowLevel===Vt.FlowLevel.Knot?ia.SymbolType.Knot:ia.SymbolType.SubFlowAndWeave;t.CheckForNamingCollisions(this,this.identifier,i);}}};Vi.FlowBase=ra;});var Li=C(Bi=>{Object.defineProperty(Bi,"__esModule",{value:true});Bi.ContentList=void 0;var Pc=J(),Tc=$(),Nc=Yt(),Ic=W(),sa=class extends Tc.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(t,...e){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let i=(0, Ic.asOrNull)(this.content[n],Nc.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new Pc.Container;if(this.content!==null)for(let i of this.content){let o=i.runtimeObject;o&&n.AddContent(o);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,t&&this.AddContent(t),e&&this.AddContent(e);}get typeName(){return "ContentList"}};Bi.ContentList=sa;});var Ne=C(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.VariableReference=void 0;var kc=dt(),Rc=ct(),aa=class extends kc.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(t){t===null?this.pathForCount=null:this.pathForCount=new Rc.Path(t);}constructor(t=null){super(),this.pathForCount=null,this.name=t;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};Wi.VariableReference=aa;});var Ie=C(qi=>{Object.defineProperty(qi,"__esModule",{value:true});qi.VariableReference=void 0;var Vc=Li(),Bc=Et(),bu=Rt(),Lc=he(),Wc=Ne(),qc=ce(),jc=Ri(),Au=W(),oa=class extends Bc.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(t=>t.name).filter(Au.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let t=this.path.join(".");return new jc.Identifier(t)}get runtimeVarRef(){return this._runtimeVarRef}constructor(t){super(),this.pathIdentifiers=t,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=e=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(e),this.isConstantReference=true;return}if(this._runtimeVarRef=new Wc.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",o="";this.path.length===1?i=this.path[0]:(o=this.path[0],i=this.path[1]),this.story.ResolveListItem(o,i,this)&&(this.isListItemReference=true);}e.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(t){if(super.ResolveReferences(t),this.isConstantReference||this.isListItemReference)return;let e=new Lc.Path(this.pathIdentifiers),n=e.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let i=(0, Au.asOrNull)(n,bu.FlowBase);i&&i.isFunction&&(this.parent instanceof qc.Weave||this.parent instanceof Vc.ContentList||this.parent instanceof bu.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${e}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}t.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};qi.VariableReference=oa;});var cn=C($i=>{Object.defineProperty($i,"__esModule",{value:true});$i.FunctionCall=void 0;var Bt=rt(),Mc=Te(),Gc=Pe(),$c=Et(),Hc=pt(),Uc=H(),Mi=It(),_u=ri(),Kc=he(),Jc=H(),zc=Ie(),ji=W(),Gi=class s extends $c.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(t,e){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=n=>{let i=this.story.ResolveList(this.name),o=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),n.AddContent(Bt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(Bt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let r=(0, ji.asOrNull)(this.args[0],Gc.DivertTarget),a=(0, ji.asOrNull)(this.args[0],zc.VariableReference);if(this.args.length!==1||r===null&&a===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}r?(this._divertTargetToCount=r,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):a&&(this._variableReferenceToCount=a,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(Bt.ControlCommand.TurnsSince()):n.AddContent(Bt.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let r=0;r<this.args.length;r+=1){let a=(0, ji.asOrNull)(this.args[r],_u.NumberExpression);if(a&&!a.isInt()){let u=r===0?"minimum":"maximum";this.Error(`RANDOM's ${u} parameter should be an integer`);}this.args[r].GenerateIntoContainer(n);}n.AddContent(Bt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let r=(0, ji.asOrNull)(this.args[0],_u.NumberExpression);r&&!r.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let r=0;r<this.args.length;r+=1)this.args[r].GenerateIntoContainer(n);n.AddContent(Bt.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.ListRandom());else if(Mi.NativeFunctionCall.CallExistsWithName(this.name)){let r=Mi.NativeFunctionCall.CallWithName(this.name);if(r.numberOfParameters!==this.args.length){let a=`${s.name} should take ${r.numberOfParameters} parameter`;r.numberOfParameters>1&&(a+="s"),this.Error(a);}for(let a=0;a<this.args.length;a+=1)this.args[a].GenerateIntoContainer(n);n.AddContent(Mi.NativeFunctionCall.CallWithName(this.name));}else if(i!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)n.AddContent(new Jc.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.ListFromInt());else {let r=new Hc.InkList;r.SetInitialOriginName(this.name),n.AddContent(new Uc.ListValue(r));}else n.AddContent(this._proxyDivert.runtimeObject),o=true;o||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(Bt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new Mc.Divert(new Kc.Path(t),e),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(t){if(super.ResolveReferences(t),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let e of this.args)e.ResolveReferences(t);if(this._divertTargetToCount){let e=this._divertTargetToCount.divert,n=e.runtimeDivert.variableDivertName!=null;if(n){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${e.runtimeDivert.variableDivertName})`);return}let i=e.targetContent;if(i===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${e.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let e=this._variableReferenceToCount.runtimeVarRef;if(!e)throw new Error;e.pathForCount!==null&&this.Error(`Should be '${s.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};$i.FunctionCall=Gi;Gi.IsBuiltIn=s=>Mi.NativeFunctionCall.CallExistsWithName(s)?true:s==="CHOICE_COUNT"||s==="TURNS_SINCE"||s==="TURNS"||s==="RANDOM"||s==="SEED_RANDOM"||s==="LIST_VALUE"||s==="LIST_RANDOM"||s==="READ_COUNT";});var la=C(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.MultipleConditionExpression=void 0;var Xc=Et(),Yc=It(),ua=class extends Xc.Expression{get subExpressions(){return this.content}constructor(t){super(),this.GenerateIntoContainer=e=>{let n=true;for(let i of this.subExpressions)i.GenerateIntoContainer(e),n||e.AddContent(Yc.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(t);}get typeName(){return "MultipleConditionExpression"}};Hi.MultipleConditionExpression=ua;});var Pe=C(Ui=>{Object.defineProperty(Ui,"__esModule",{value:true});Ui.DivertTarget=void 0;var Qc=Is(),Zc=we(),td=Ai(),ed=fa(),nd=H(),ha=Et(),id=Rt(),Fu=cn(),rd=la(),wu=Ie(),ca=W(),da=class s extends ha.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(t){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=e=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new nd.DivertTargetValue,e.AddContent(this.runtimeDivertTargetValue);},this.Equals=e=>{let n=(0, ca.asOrNull)(e,s);if(!n||!this.divert.target||!n.divert.target)return false;let i=this.divert.target.dotSeparatedComponents,o=n.divert.target.dotSeparatedComponents;return i===o},this.divert=this.AddContent(t);}get typeName(){return "DivertTarget"}ResolveReferences(t){if(super.ResolveReferences(t),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let e=this;for(;e&&e instanceof ha.Expression;){let i=false,o=false,r=e.parent;if(r instanceof Qc.BinaryExpression){let a=r;a.opName!=="=="&&a.opName!=="!="?i=true:(a.leftExpression instanceof s||a.leftExpression instanceof wu.VariableReference)&&(a.rightExpression instanceof s||a.rightExpression instanceof wu.VariableReference)||(i=true),o=true;}else if(r instanceof Fu.FunctionCall){let a=r;!a.isTurnsSince&&!a.isReadCount&&(i=true),o=true;}else (r instanceof ha.Expression||r instanceof rd.MultipleConditionExpression||r instanceof Zc.Choice&&r.condition===e||r instanceof td.Conditional||r instanceof ed.ConditionalSingleBranch)&&(i=true,o=true);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),o)break;e=r;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let n=this.divert.targetContent;if(n!==null){let i=n.containerForCounting;if(i!==null){let r=(0, ca.asOrNull)(this.parent,Fu.FunctionCall);r&&r.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let o=(0, ca.asOrNull)(n,id.FlowBase);if(o!=null&&o.args!==null)for(let r of o.args)r.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${o.identifier}' has 'ref ${r.identifier}').`);}}};Ui.DivertTarget=da;});var Te=C(Ki=>{Object.defineProperty(Ki,"__esModule",{value:true});Ki.Divert=void 0;var sd=J(),dn=rt(),ad=kt(),pa=Pe(),ma=Rt(),od=cn(),ud=$(),xu=he(),ld=ct(),Ou=ue(),hd=H(),Pu=Ie(),cd=hn(),fn=W(),ga=class extends ud.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(t){this._runtimeDivert=t;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(t,e){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return dn.ControlCommand.End();if(this.isDone)return dn.ControlCommand.Done();this.runtimeDivert=new ad.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let n=this.args!==null&&this.args.length>0;if(n||this.isFunctionCall||this.isTunnel||this.isThread){let i=new sd.Container;if(n){this.isFunctionCall||i.AddContent(dn.ControlCommand.EvalStart());let o=null;this.targetContent&&(o=this.targetContent.args);for(let r=0;r<this.args.length;++r){let a=this.args[r],u=null;if(o&&r<o.length&&(u=o[r]),u&&u.isByReference){let l=(0, fn.asOrNull)(a,Pu.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${a}`);break}let h=new xu.Path(l.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let m=new hd.VariablePointerValue(l.name);i.AddContent(m);}else a.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(dn.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(dn.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Ou.PushPopType.Function:Ou.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let i=(0, fn.asOrNull)((0, cd.ClosestFlowBase)(this),ma.FlowBase);if(i){let o=i.ResolveVariableWithName(n,this);if(o.found){if(o.isArgument&&o.ownerFlow&&o.ownerFlow.args){let r=o.ownerFlow.args.find(a=>{var u;return ((u=a.identifier)===null||u===void 0?void 0:u.name)==n});r&&!r.isDivertTarget&&this.Error(`Since '${r.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${r.identifier}`,o.ownerFlow);}this.runtimeDivert.variableDivertName=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let i=(0, fn.asOrNull)(this.targetContent,ma.FlowBase);if(n===0&&(i===null||!i.hasParameters))return;if(i===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&n>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof pa.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let o=i.args.length;if(o!==n){let r;n===0?r="but there weren't any passed to it":n<o?r=`but only got ${n}`:r=`but got ${n}`,this.Error(`to '${i.identifier}' requires ${o} arguments, ${r}`);return}for(let r=0;r<o;++r){let a=i.args[r],u=this.args[r];if(a.isDivertTarget){let l=(0, fn.asOrNull)(u,Pu.VariableReference);if(!(u instanceof pa.DivertTarget)&&l===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${a.identifier} but saw ${u}`,u);else if(l){let h=new xu.Path(l.pathIdentifiers);h.ResolveFromContext(l)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let i=this.target?this.target.firstComponent:null,o=n.externals.get(i);if(!o)throw new Error("external not found");let r=o.argumentNames.length,a=0;this.args&&(a=this.args.length),a!==r&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${r} but got ${a}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},t&&(this.target=t),e&&(this.args=e,this.AddContent(e));}get typeName(){return "Divert"}ResolveReferences(t){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(t);let e=(0, fn.asOrNull)(this.targetContent,ma.FlowBase);e&&(!e.isFunction&&this.isFunctionCall?super.Error(`${e.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${e.identifier} =='?`):e.isFunction&&!this.isFunctionCall&&!(this.parent instanceof pa.DivertTarget)&&super.Error(e.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+e.identifier+"(...)'"));let n=this.targetContent!==null,i=false,o=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=od.FunctionCall.IsBuiltIn(this.target.firstComponent),o=t.IsExternal(this.target.firstComponent),i||o){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),o&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new ld.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(t));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!i&&!o&&this.Error(`target not found: '${this.target}'`);}Error(t,e=null,n=false){if(e!==this&&e){super.Error(t,e);return}this.isFunctionCall?super.Error(`Function call ${t}`,e,n):super.Error(`Divert ${t}`,e,n);}};Ki.Divert=ga;});var Tu=C(Ji=>{Object.defineProperty(Ji,"__esModule",{value:true});Ji.GatherPointToResolve=void 0;var Ca=class{constructor(t,e){this.divert=t,this.targetRuntimeObj=e;}};Ji.GatherPointToResolve=Ca;});var Nu=C(zi=>{Object.defineProperty(zi,"__esModule",{value:true});zi.SequenceDivertToResolve=void 0;var va=class{constructor(t,e){this.divert=t,this.targetContent=e;}};zi.SequenceDivertToResolve=va;});var Da=C(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.SequenceType=void 0;var Iu;(function(s){s[s.Stopping=1]="Stopping",s[s.Cycle=2]="Cycle",s[s.Shuffle=4]="Shuffle",s[s.Once=8]="Once";})(Iu||(Xi.SequenceType=Iu={}));});var Sa=C(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.Sequence=void 0;var ku=J(),wt=rt(),Ea=kt(),pn=H(),Yi=It(),dd=$(),fd=Nu(),Qi=Da(),pd=ce(),ya=class extends dd.ParsedObject{constructor(t,e){super(),this.sequenceType=e,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new ku.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(wt.ControlCommand.EvalStart()),n.AddContent(wt.ControlCommand.VisitIndex());let i=(this.sequenceType&Qi.SequenceType.Once)>0,o=(this.sequenceType&Qi.SequenceType.Cycle)>0,r=(this.sequenceType&Qi.SequenceType.Stopping)>0,a=(this.sequenceType&Qi.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),r||i?(n.AddContent(new pn.IntValue(u-1)),n.AddContent(Yi.NativeFunctionCall.CallWithName("MIN"))):o&&(n.AddContent(new pn.IntValue(this.sequenceElements.length)),n.AddContent(Yi.NativeFunctionCall.CallWithName("%"))),a){let h=wt.ControlCommand.NoOp();if(i||r){let m=r?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(wt.ControlCommand.Duplicate()),n.AddContent(new pn.IntValue(m)),n.AddContent(Yi.NativeFunctionCall.CallWithName("=="));let g=new Ea.Divert;g.isConditional=true,n.AddContent(g),this.AddDivertToResolve(g,h);}let c=this.sequenceElements.length;r&&(c-=1),n.AddContent(new pn.IntValue(c)),n.AddContent(wt.ControlCommand.SequenceShuffleIndex()),(i||r)&&n.AddContent(h);}n.AddContent(wt.ControlCommand.EvalEnd());let l=wt.ControlCommand.NoOp();for(let h=0;h<u;h+=1){n.AddContent(wt.ControlCommand.EvalStart()),n.AddContent(wt.ControlCommand.Duplicate()),n.AddContent(new pn.IntValue(h)),n.AddContent(Yi.NativeFunctionCall.CallWithName("==")),n.AddContent(wt.ControlCommand.EvalEnd());let c=new Ea.Divert;c.isConditional=true,n.AddContent(c);let m;h<this.sequenceElements.length?m=this.sequenceElements[h].runtimeObject:m=new ku.Container,m.name=`s${h}`,m.InsertContent(wt.ControlCommand.PopEvaluatedValue(),0);let g=new Ea.Divert;m.AddContent(g),n.AddToNamedContentOnly(m),this.AddDivertToResolve(c,m),this.AddDivertToResolve(g,l);}return n.AddContent(l),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new fd.SequenceDivertToResolve(n,i));},this.sequenceType=e,this.sequenceElements=[];for(let n of t){let i=n.content,o=null;i===null||i.length===0?o=n:o=new pd.Weave(i),this.sequenceElements.push(o),this.AddContent(o);}}get typeName(){return "Sequence"}ResolveReferences(t){super.ResolveReferences(t);for(let e of this._sequenceDivertsToResolve)e.divert.targetPath=e.targetContent.path;}};Zi.Sequence=ya;});var Aa=C(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.TunnelOnwards=void 0;var md=J(),mn=rt(),gd=kt(),Cd=H(),vd=$(),Dd=oe(),Ed=W(),yd=Ne(),ba=class extends vd.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let t=new md.Container;if(t.AddContent(mn.ControlCommand.EvalStart()),this.divertAfter){let e=this.divertAfter.GenerateRuntimeObject(),n=e;if(n){let o=this.divertAfter.args;if(o!==null&&o.length>0){let r=-1,a=-1;for(let u=0;u<n.content.length;u+=1){let l=n.content[u];l&&(r==-1&&l.commandType===mn.ControlCommand.CommandType.EvalStart?r=u:l.commandType===mn.ControlCommand.CommandType.EvalEnd&&(a=u));}for(let u=r+1;u<a;u+=1){let l=n.content[u];l.parent=null,t.AddContent(n.content[u]);}}}let i=(0, Ed.asOrNull)(e,gd.Divert);if(i!=null&&i.hasVariableTarget){let o=new yd.VariableReference(i.variableDivertName);t.AddContent(o);}else this._overrideDivertTarget=new Cd.DivertTargetValue,t.AddContent(this._overrideDivertTarget);}else t.AddContent(new Dd.Void);return t.AddContent(mn.ControlCommand.EvalEnd()),t.AddContent(mn.ControlCommand.PopTunnel()),t},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(t){this._divertAfter=t,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(t){super.ResolveReferences(t),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};tr.TunnelOnwards=ba;});var wa=C(er=>{Object.defineProperty(er,"__esModule",{value:true});er.ListDefinition=void 0;var _a=pt(),Fa=class{constructor(t,e){this._name=t||"",this._items=null,this._itemNameToValues=e||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[t,e]of this._itemNameToValues){let n=new _a.InkListItem(this.name,t);this._items.set(n.serialized(),e);}}return this._items}ValueForItem(t){if(!t.itemName)return 0;let e=this._itemNameToValues.get(t.itemName);return typeof e<"u"?e:0}ContainsItem(t){return !t.itemName||t.originName!=this.name?false:this._itemNameToValues.has(t.itemName)}ContainsItemWithName(t){return this._itemNameToValues.has(t)}TryGetItemWithValue(t,e){for(let[n,i]of this._itemNameToValues)if(i==t)return e=new _a.InkListItem(this.name,n),{result:e,exists:true};return e=_a.InkListItem.Null,{result:e,exists:false}}TryGetValueForItem(t,e){if(!t.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(t.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};er.ListDefinition=Fa;});var ir=C(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.ListDefinition=void 0;var Sd=pt(),bd=pt(),Ad=wa(),_d=H(),Fd=$(),wd=Gt(),xa=class extends Fd.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var t;let e=new Map;for(let n of this.itemDefinitions)e.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):e.set(n.name,n.seriesValue);return new Ad.ListDefinition(((t=this.identifier)===null||t===void 0?void 0:t.name)||"",e)}constructor(t){super(),this.itemDefinitions=t,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let o of this.itemDefinitions)this._elementsByName.set(o.name,o);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,i;let o=new Sd.InkList;for(let r of this.itemDefinitions)if(r.inInitialList){let a=new bd.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,r.name||null);o.Add(a,r.seriesValue);}return o.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new _d.ListValue(o)};let e=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(e=n.explicitValue),n.seriesValue=e,e+=1;this.AddContent(t);}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.identifier,wd.SymbolType.List);}};nr.ListDefinition=xa;});var Pa=C(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.VariableAssignment=void 0;var xd=J(),Od=hn(),Pd=ir(),Td=$(),Ru=Gt(),Nd=zt(),Id=Ie(),kd=W(),Oa=class extends Td.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:t,isGlobalDeclaration:e,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:o}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let r=null;if(this.isGlobalDeclaration?r=this.story:this.isNewTemporaryDeclaration&&(r=(0, Od.ClosestFlowBase)(this)),r&&r.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let a=new xd.Container;return this.expression?a.AddContent(this.expression.runtimeObject):this.listDefinition&&a.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Nd.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),a.AddContent(this._runtimeAssignment),a},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=o,this.isGlobalDeclaration=!!e,this.isNewTemporaryDeclaration=!!n,i instanceof Pd.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):t&&(this.expression=this.AddContent(t));}ResolveReferences(t){if(super.ResolveReferences(t),this.isDeclaration&&this.listDefinition===null&&t.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?Ru.SymbolType.Var:Ru.SymbolType.Temp),this.isGlobalDeclaration){let e=(0, kd.asOrNull)(this.expression,Id.VariableReference);e&&!e.isConstantReference&&!e.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let e=t.ResolveVariableWithName(this.variableName,this);e.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=e.isGlobal);}}};rr.VariableAssignment=Oa;});var ce=C(or=>{Object.defineProperty(or,"__esModule",{value:true});or.Weave=void 0;var Vu=Mn(),St=we(),sr=Ai(),Rd=wi(),Vd=J(),ar=Te(),Bd=kt(),Ld=Pe(),Wd=Rt(),Lt=ln(),qd=Tu(),jd=$(),Ta=Sa(),Md=Yt(),Gd=Aa(),$d=Pa(),bt=W(),Na=class s extends jd.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let t=null;for(let n=this.content.length-1;n>=0;--n){t=this.content[n];let i=(0, bt.asOrNull)(t,Md.Text);if(!(i&&i.text===`
15
+ `)&&!this.IsGlobalDeclaration(t))break}let e=(0, bt.asOrNull)(t,s);return e&&(t=e.lastParsedSignificantObject),t}constructor(t,e=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var n,i,o;let r=[...this.FindAll(Lt.Gather)(a=>!(a.name===null||a.name===void 0)),...this.FindAll(St.Choice)(a=>!(a.name===null||a.name===void 0))];this._namedWeavePoints=new Map;for(let a of r){let u=this.namedWeavePoints.get(((n=a.identifier)===null||n===void 0?void 0:n.name)||"");if(u){let l=u instanceof Lt.Gather?"gather":"choice",h=u;this.Error(`A ${l} with the same label name '${a.name}' already exists in this context on line ${h.debugMetadata?h.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,a);}!((i=a.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((o=a.identifier)===null||o===void 0?void 0:o.name,a);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;n<this.content.length;){let i=this.content[n];if(i instanceof St.Choice||i instanceof Lt.Gather){let r=i.indentationDepth-1;if(r>this.baseIndentIndex){let a=n;for(;n<this.content.length;){let c=(0, bt.asOrNull)(this.content[n],St.Choice)||(0, bt.asOrNull)(this.content[n],Lt.Gather);if(c!==null&&c.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let u=n-a,l=this.content.slice(a,a+u);this.content.splice(a,u);let h=new s(l,r);this.InsertContent(a,h),n=a;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let i of n)if(i instanceof St.Choice||i instanceof Lt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new Vd.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof St.Choice||n instanceof Lt.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof s){let i=n;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let o=n.runtimeContainer;if(n.name||(o.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(o);}else this.rootContainer.AddToNamedContentOnly(o);for(let r of this.looseEnds){let a=r;if(a instanceof Lt.Gather&&a.indentationDepth==n.indentationDepth)continue;let u=null;if(a instanceof ar.Divert)u=a.runtimeObject;else {u=new Bd.Divert;let l=a;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new qd.GatherPointToResolve(u,o));}this.looseEnds=[],this.currentContainer=o;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof Lt.Gather)this.AddRuntimeForGather(n);else if(n instanceof St.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Lt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=n;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, bt.asOrNull)(n,St.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=n;},this.AddRuntimeForNestedWeave=n=>{this.AddGeneralRuntimeContent(n.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=n=>{if(n!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(n);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let n=null,i=null,o=false;for(let r=this.parent;r!==null;r=r.parent){let a=(0, bt.asOrNull)(r,s);a&&(!o&&n===null&&(n=a),o&&i===null&&(i=a)),(r instanceof Ta.Sequence||r instanceof sr.Conditional)&&(o=true);}if(!(n===null&&i===null))for(let r=this.looseEnds.length-1;r>=0;r-=1){let a=this.looseEnds[r],u=false;if(o){if(a instanceof St.Choice&&n!==null)n.ReceiveLooseEnd(a),u=true;else if(!(a instanceof St.Choice)){let l=n||i;l!==null&&(l.ReceiveLooseEnd(a),u=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(a),u=true;u&&this.looseEnds.splice(r,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(n);return i||null},this.IsGlobalDeclaration=n=>{let i=(0, bt.asOrNull)(n,$d.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, bt.asOrNull)(n,Rd.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let i=[],o=n;if(o.content!==null)for(let u of o.content)this.IsGlobalDeclaration(u)||i.push(u);let r=(0, bt.asOrNull)(o.parent,s);if(r===null)throw new Error("Expected weave point parent to be weave?");let a=r.content.indexOf(o);for(let u=a+1;u<r.content.length;u+=1){let l=r.content[u];if(!this.IsGlobalDeclaration(l)){if(l instanceof St.Choice||l instanceof Lt.Gather||l instanceof s)break;i.push(l);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof Vu.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let o of this.looseEnds){let r=this.ContentThatFollowsWeavePoint(o);this.ValidateFlowOfObjectsTerminates(r,o,n);}else {for(let o of this.content)if(o instanceof St.Choice||o instanceof ar.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let i=null;for(let r=n.parent;r!==null;r=r.parent)if(r instanceof Ta.Sequence||r instanceof sr.Conditional){i=(0, bt.asOrNull)(r,sr.Conditional);break}let o="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(St.Choice)().length===1&&(o=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${o.toLowerCase()}`),this.Error(o,n);},this.ValidateFlowOfObjectsTerminates=(n,i,o)=>{let r=false,a=i;for(let u of n){if(u.Find(ar.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof Ld.DivertTarget))!==null&&(r=true),u.Find(Gd.TunnelOnwards)()!=null){r=true;break}a=u;}if(!r){if(a instanceof Vu.AuthorWarning)return;o(a);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return true;for(let i=n.content.length-1;i>=0;--i){let o=(0, bt.asOrNull)(n.content[i],ar.Divert);if(o&&!(o.isThread||o.isTunnel||o.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let i of this.ancestry){let o=(0, bt.asOrNull)(i,Wd.FlowBase);if(o)n.push(o);else break}for(let[i,o]of this.namedWeavePoints)for(let r of n){let a=r.ContentWithNameAtLevel(i);if(a&&a!==o){let u=`${o.GetType()} '${i}' has the same label name as a ${a.GetType()} (on ${a.debugMetadata})`;this.Error(u,o);}}},e==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(t):this.baseIndentIndex=e,this.AddContent(t),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(t){if(super.ResolveReferences(t),this.looseEnds!==null&&this.looseEnds.length>0){let e=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof Ta.Sequence||n instanceof sr.Conditional){e=true;break}e&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let e of this.gatherPointsToResolve)e.divert.targetPath=e.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};or.Weave=Na;});var fa=C(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.ConditionalSingleBranch=void 0;var Bu=J(),ur=rt(),Lu=kt(),Hd=$(),Ud=It(),Kd=H(),Jd=Yt(),zd=ce(),Xd=W(),Ia=class extends Hd.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(t){this._ownExpression=t,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(t){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let o=(0, Xd.asOrNull)(i,Jd.Text);o&&o.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",o);}let e=new Bu.Container,n=this.matchingEquality&&!this.isElse;if(n&&e.AddContent(ur.ControlCommand.Duplicate()),this._conditionalDivert=new Lu.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&e.AddContent(ur.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(e),this.matchingEquality&&e.AddContent(Ud.NativeFunctionCall.CallWithName("==")),i&&e.AddContent(ur.ControlCommand.EvalEnd());}return e.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new Kd.StringValue(`
16
+ `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(ur.ControlCommand.PopEvaluatedValue(),0),e.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Lu.Divert,this._contentContainer.AddContent(this.returnDivert),e},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new Bu.Container:this._innerWeave.rootContainer,t&&(this._innerWeave=new zd.Weave(t),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(t){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(t);}};lr.ConditionalSingleBranch=Ia;});var qu=C(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.CustomFlags=void 0;var Wu;(function(s){s[s.ParsingString=1]="ParsingString",s[s.TagActive=2]="TagActive";})(Wu||(hr.CustomFlags=Wu={}));});var ju=C(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.DebugMetadata=void 0;var ka=class s{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(t){let e=new s;return e.fileName=this.fileName,e.sourceName=this.sourceName,this.startLineNumber<t.startLineNumber?(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>t.startLineNumber?(e.startLineNumber=t.startLineNumber,e.startCharacterNumber=t.startCharacterNumber):(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=Math.min(this.startCharacterNumber,t.startCharacterNumber)),this.endLineNumber>t.endLineNumber?(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<t.endLineNumber?(e.endLineNumber=t.endLineNumber,e.endCharacterNumber=t.endCharacterNumber):(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=Math.max(this.endCharacterNumber,t.endCharacterNumber)),e}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};cr.DebugMetadata=ka;});var Mu=C(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.ExternalDeclaration=void 0;var Yd=$(),Ra=class extends Yd.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e){super(),this.identifier=t,this.argumentNames=e,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var t;return `EXTERNAL ${(t=this.identifier)===null||t===void 0?void 0:t.name}`}};dr.ExternalDeclaration=Ra;});var Gu=C(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.FlowDecl=void 0;var Va=class{constructor(t,e,n){this.name=t,this.args=e,this.isFunction=n;}};fr.FlowDecl=Va;});var La=C(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.Wrap=void 0;var Qd=$(),Ba=class extends Qd.ParsedObject{constructor(t){super(),this._objToWrap=t,this.GenerateRuntimeObject=()=>this._objToWrap;}};pr.Wrap=Ba;});var $u=C(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.Glue=void 0;var Zd=La(),Wa=class extends Zd.Wrap{constructor(t){super(t);}get typeName(){return "Glue"}};mr.Glue=Wa;});var Cr=C(gr=>{Object.defineProperty(gr,"__esModule",{value:true});gr.Glue=void 0;var tf=dt(),qa=class extends tf.InkObject{toString(){return "Glue"}};gr.Glue=qa;});var Uu=C(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.IncDecExpression=void 0;var ef=Li(),Hu=Et(),nf=Rt(),rf=It(),sf=H(),af=zt(),of=Ne(),uf=ce(),ja=class extends Hu.Expression{constructor(t,e,n){super(),this.varIdentifier=t,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var o,r;i.AddContent(new of.VariableReference(((o=this.varIdentifier)===null||o===void 0?void 0:o.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new sf.IntValue(1)),i.AddContent(rf.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new af.VariableAssignment(((r=this.varIdentifier)===null||r===void 0?void 0:r.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,o;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(o=this.varIdentifier)===null||o===void 0?void 0:o.name}`+(this.isInc?"++":"--")},e instanceof Hu.Expression?(this.expression=e,this.AddContent(this.expression),this.isInc=!!n):this.isInc=e;}get typeName(){return "IncDecExpression"}ResolveReferences(t){var e;super.ResolveReferences(t);let n=t.ResolveVariableWithName(((e=this.varIdentifier)===null||e===void 0?void 0:e.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof uf.Weave)&&!(this.parent instanceof nf.FlowBase)&&!(this.parent instanceof ef.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};vr.IncDecExpression=ja;});var Ga=C(Dr=>{Object.defineProperty(Dr,"__esModule",{value:true});Dr.IncludedFile=void 0;var lf=$(),Ma=class extends lf.ParsedObject{constructor(t){super(),this.includedStory=t,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Dr.IncludedFile=Ma;});var Ku=C(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.InfixOperator=void 0;var $a=class{constructor(t,e,n){this.type=t,this.precedence=e,this.requireWhitespace=n,this.toString=()=>this.type;}};Er.InfixOperator=$a;});var Ua=C(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.Knot=void 0;var hf=Rt(),Ju=xe(),Ha=class extends hf.FlowBase{get flowLevel(){return Ju.FlowLevel.Knot}constructor(t,e,n,i){super(t,e,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(t){super.ResolveReferences(t);let e=this.story;for(let n in this.subFlowsByName){let i=e.ContentWithNameAtLevel(n,Ju.FlowLevel.Knot,false);if(i){let o=this.subFlowsByName.get(n),r=`Stitch '${o?o.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(r,o);}}}};yr.Knot=Ha;});var zu=C(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.List=void 0;var cf=Et(),df=pt(),ff=pt(),pf=H(),Ka=class extends cf.Expression{constructor(t){super(),this.itemIdentifierList=t,this.GenerateIntoContainer=e=>{var n,i;let o=new df.InkList;if(this.itemIdentifierList!=null)for(let r of this.itemIdentifierList){let a=((n=r?.name)===null||n===void 0?void 0:n.split("."))||[],u=null,l="";a.length>1?(u=a[0],l=a[1]):l=a[0];let h=this.story.ResolveListItem(u,l,this);if(h===null)u===null?this.Error(`Could not find list definition that contains item '${r}'`):this.Error(`Could not find list item ${r}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${r}`);return}u||(u=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new ff.InkListItem(u,h.name||null);o.has(c.serialized())?this.Warning(`Duplicate of item '${r}' in list.`):o.Add(c,h.seriesValue);}}e.AddContent(new pf.ListValue(o));};}get typeName(){return "List"}};Sr.List=Ka;});var za=C(br=>{Object.defineProperty(br,"__esModule",{value:true});br.ListElementDefinition=void 0;var mf=$(),gf=Gt(),Ja=class extends mf.ParsedObject{get fullName(){var t;let e=this.parent;if(e===null)throw new Error("Can't get full name without a parent list.");return `${(t=e.identifier)===null||t===void 0?void 0:t.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var t;return ((t=this.indentifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e,n=null){super(),this.indentifier=t,this.inInitialList=e,this.explicitValue=n,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.indentifier,gf.SymbolType.ListItem);}};br.ListElementDefinition=Ja;});var Xa=C(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.StatementLevel=void 0;var Xu;(function(s){s[s.InnerBlock=0]="InnerBlock",s[s.Stitch=1]="Stitch",s[s.Knot=2]="Knot",s[s.Top=3]="Top";})(Xu||(Ar.StatementLevel=Xu={}));});var Qa=C(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.Stitch=void 0;var Cf=Rt(),vf=xe(),Ya=class extends Cf.FlowBase{get flowLevel(){return vf.FlowLevel.Stitch}constructor(t,e,n,i){super(t,e,n,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};_r.Stitch=Ya;});var wr=C(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.Tag=void 0;var Df=dt(),Za=class extends Df.InkObject{constructor(t){super(),this.text=t.toString()||"";}toString(){return "# "+this.text}};Fr.Tag=Za;});var eo=C(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.Choice=void 0;var Ef=ct(),yf=it(),Sf=dt(),to=class s extends Sf.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, yf.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new Ef.Path(t);}Clone(){let t=new s;return t.text=this.text,t.sourcePath=this.sourcePath,t.index=this.index,t.targetPath=this.targetPath,t.originalThreadIndex=this.originalThreadIndex,t.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(t.threadAtGeneration=this.threadAtGeneration.Copy()),t}};xr.Choice=to;});var io=C(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.ListDefinitionsOrigin=void 0;var bf=pt(),Af=H(),_f=it(),no=class{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let e of t){this._lists.set(e.name,e);for(let[n,i]of e.items){let o=bf.InkListItem.fromSerializedKey(n),r=new Af.ListValue(o,i);if(!o.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(o.itemName,r),this._allUnambiguousListValueCache.set(o.fullName,r);}}}get lists(){let t=[];for(let[,e]of this._lists)t.push(e);return t}TryListGetDefinition(t,e){if(t===null)return {result:e,exists:false};let n=this._lists.get(t);return n?{result:n,exists:true}:{result:e,exists:false}}FindSingleItemListWithName(t){if(t===null)return (0, _f.throwNullException)("name");let e=this._allUnambiguousListValueCache.get(t);return typeof e<"u"?e:null}};Or.ListDefinitionsOrigin=no;});var Re=C(Ir=>{Object.defineProperty(Ir,"__esModule",{value:true});Ir.JsonSerialisation=void 0;var Pr=J(),gt=H(),Yu=Cr(),B=rt(),ke=ue(),Qu=kt(),Zu=hi(),ro=Ne(),tl=zt(),so=It(),el=oe(),nl=wr(),Ff=ct(),il=eo(),wf=wa(),xf=io(),Tr=pt(),z=W(),de=it(),Nr=class s{static JArrayToRuntimeObjList(t,e=false){let n=t.length;e&&n--;let i=[];for(let o=0;o<n;o++){let r=t[o],a=this.JTokenToRuntimeObject(r);if(a===null)return (0, de.throwNullException)("runtimeObj");i.push(a);}return i}static WriteDictionaryRuntimeObjs(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WritePropertyStart(n),this.WriteRuntimeObject(t,i),t.WritePropertyEnd();t.WriteObjectEnd();}static WriteListRuntimeObjs(t,e){t.WriteArrayStart();for(let n of e)this.WriteRuntimeObject(t,n);t.WriteArrayEnd();}static WriteIntDictionary(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WriteIntProperty(n,i);t.WriteObjectEnd();}static WriteRuntimeObject(t,e){let n=(0, z.asOrNull)(e,Pr.Container);if(n){this.WriteRuntimeContainer(t,n);return}let i=(0, z.asOrNull)(e,Qu.Divert);if(i){let p="->";i.isExternal?p="x()":i.pushesToStack&&(i.stackPushType==ke.PushPopType.Function?p="f()":i.stackPushType==ke.PushPopType.Tunnel&&(p="->t->"));let D;i.hasVariableTarget?D=i.variableDivertName:D=i.targetPathString,t.WriteObjectStart(),t.WriteProperty(p,D),i.hasVariableTarget&&t.WriteProperty("var",true),i.isConditional&&t.WriteProperty("c",true),i.externalArgs>0&&t.WriteIntProperty("exArgs",i.externalArgs),t.WriteObjectEnd();return}let o=(0, z.asOrNull)(e,Zu.ChoicePoint);if(o){t.WriteObjectStart(),t.WriteProperty("*",o.pathStringOnChoice),t.WriteIntProperty("flg",o.flags),t.WriteObjectEnd();return}let r=(0, z.asOrNull)(e,gt.BoolValue);if(r){t.WriteBool(r.value);return}let a=(0, z.asOrNull)(e,gt.IntValue);if(a){t.WriteInt(a.value);return}let u=(0, z.asOrNull)(e,gt.FloatValue);if(u){t.WriteFloat(u.value);return}let l=(0, z.asOrNull)(e,gt.StringValue);if(l){l.isNewline?t.Write(`
17
+ `,false):(t.WriteStringStart(),t.WriteStringInner("^"),t.WriteStringInner(l.value),t.WriteStringEnd());return}let h=(0, z.asOrNull)(e,gt.ListValue);if(h){this.WriteInkList(t,h);return}let c=(0, z.asOrNull)(e,gt.DivertTargetValue);if(c){if(t.WriteObjectStart(),c.value===null)return (0, de.throwNullException)("divTargetVal.value");t.WriteProperty("^->",c.value.componentsString),t.WriteObjectEnd();return}let m=(0, z.asOrNull)(e,gt.VariablePointerValue);if(m){t.WriteObjectStart(),t.WriteProperty("^var",m.value),t.WriteIntProperty("ci",m.contextIndex),t.WriteObjectEnd();return}if((0, z.asOrNull)(e,Yu.Glue)){t.Write("<>");return}let E=(0, z.asOrNull)(e,B.ControlCommand);if(E){t.Write(s._controlCommandNames[E.commandType]);return}let v=(0, z.asOrNull)(e,so.NativeFunctionCall);if(v){let p=v.name;p=="^"&&(p="L^"),t.Write(p);return}let S=(0, z.asOrNull)(e,ro.VariableReference);if(S){t.WriteObjectStart();let p=S.pathStringForCount;p!=null?t.WriteProperty("CNT?",p):t.WriteProperty("VAR?",S.name),t.WriteObjectEnd();return}let y=(0, z.asOrNull)(e,tl.VariableAssignment);if(y){t.WriteObjectStart();let p=y.isGlobal?"VAR=":"temp=";t.WriteProperty(p,y.variableName),y.isNewDeclaration||t.WriteProperty("re",true),t.WriteObjectEnd();return}if((0, z.asOrNull)(e,el.Void)){t.Write("void");return}let R=(0, z.asOrNull)(e,nl.Tag);if(R){t.WriteObjectStart(),t.WriteProperty("#",R.text),t.WriteObjectEnd();return}let d=(0, z.asOrNull)(e,il.Choice);if(d){this.WriteChoice(t,d);return}throw new Error("Failed to convert runtime object to Json token: "+e)}static JObjectToDictionaryRuntimeObjs(t){let e=new Map;for(let n in t)if(t.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(t[n]);if(i===null)return (0, de.throwNullException)("inkObject");e.set(n,i);}return e}static JObjectToIntDictionary(t){let e=new Map;for(let n in t)t.hasOwnProperty(n)&&e.set(n,parseInt(t[n]));return e}static JTokenToRuntimeObject(t){if(typeof t=="number"&&!isNaN(t)||typeof t=="boolean")return gt.Value.Create(t);if(typeof t=="string"){let e=t.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(e);if(n)return new gt.FloatValue(parseFloat(n[0]));let i=e[0];if(i=="^")return new gt.StringValue(e.substring(1));if(i==`
18
18
  `&&e.length==1)return new gt.StringValue(`
19
- `);if(e=="<>")return new Yu.Glue;for(let o=0;o<s._controlCommandNames.length;++o){let r=s._controlCommandNames[o];if(e==r)return new V.ControlCommand(o)}if(e=="L^"&&(e="^"),ro.NativeFunctionCall.CallExistsWithName(e))return ro.NativeFunctionCall.CallWithName(e);if(e=="->->")return V.ControlCommand.PopTunnel();if(e=="~ret")return V.ControlCommand.PopFunction();if(e=="void")return new el.Void}if(typeof t=="object"&&!Array.isArray(t)){let e=t,n;if(e["^->"])return n=e["^->"],new gt.DivertTargetValue(new _f.Path(n.toString()));if(e["^var"]){n=e["^var"];let h=new gt.VariablePointerValue(n.toString());return "ci"in e&&(n=e.ci,h.contextIndex=parseInt(n)),h}let i=false,o=false,r=ke.PushPopType.Function,a=false;if((n=e["->"])?i=true:(n=e["f()"])?(i=true,o=true,r=ke.PushPopType.Function):(n=e["->t->"])?(i=true,o=true,r=ke.PushPopType.Tunnel):(n=e["x()"])&&(i=true,a=true,o=false,r=ke.PushPopType.Function),i){let h=new Qu.Divert;h.pushesToStack=o,h.stackPushType=r,h.isExternal=a;let c=n.toString();return (n=e.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!e.c,a&&(n=e.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=e["*"]){let h=new Zu.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=e.flg)&&(h.flags=parseInt(n)),h}if(n=e["VAR?"])return new io.VariableReference(n.toString());if(n=e["CNT?"]){let h=new io.VariableReference;return h.pathStringForCount=n.toString(),h}let u=false,l=false;if((n=e["VAR="])?(u=true,l=true):(n=e["temp="])&&(u=true,l=false),u){let h=n.toString(),c=!e.re,d=new tl.VariableAssignment(h,c);return d.isGlobal=l,d}if(e["#"]!==void 0)return n=e["#"],new nl.Tag(n.toString());if(n=e.list){let h=n,c=new Pr.InkList;if(n=e.origins){let d=n;c.SetInitialOriginNames(d);}for(let d in h)if(h.hasOwnProperty(d)){let m=h[d],D=new Pr.InkListItem(d),v=parseInt(m);c.Add(D,v);}return new gt.ListValue(c)}if(e.originalChoicePath!=null)return this.JObjectToChoice(e)}if(Array.isArray(t))return this.JArrayToContainer(t);if(t==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(t,["parent"]))}static toJson(t,e,n){return JSON.stringify(t,(i,o)=>e?.some(r=>r===i)?void 0:o,n)}static WriteRuntimeContainer(t,e,n=false){if(t.WriteArrayStart(),e===null)return (0, de.throwNullException)("container");for(let u of e.content)this.WriteRuntimeObject(t,u);let i=e.namedOnlyContent,o=e.countFlags,r=e.name!=null&&!n,a=i!=null||o>0||r;if(a&&t.WriteObjectStart(),i!=null)for(let[u,l]of i){let h=u,c=(0, J.asOrNull)(l,Or.Container);t.WritePropertyStart(h),this.WriteRuntimeContainer(t,c,true),t.WritePropertyEnd();}o>0&&t.WriteIntProperty("#f",o),r&&t.WriteProperty("#n",e.name),a?t.WriteObjectEnd():t.WriteNull(),t.WriteArrayEnd();}static JArrayToContainer(t){let e=new Or.Container;e.content=this.JArrayToRuntimeObjList(t,true);let n=t[t.length-1];if(n!=null){let i=new Map;for(let o in n)if(o=="#f")e.countFlags=parseInt(n[o]);else if(o=="#n")e.name=n[o].toString();else {let r=this.JTokenToRuntimeObject(n[o]),a=(0, J.asOrNull)(r,Or.Container);a&&(a.name=o),i.set(o,r);}e.namedOnlyContent=i;}return e}static JObjectToChoice(t){let e=new il.Choice;return e.text=t.text.toString(),e.index=parseInt(t.index),e.sourcePath=t.originalChoicePath.toString(),e.originalThreadIndex=parseInt(t.originalThreadIndex),e.pathStringOnChoice=t.targetPath.toString(),e.tags=this.JArrayToTags(t),e.isInvisibleDefault=!!t.isInvisibleDefault,e}static JArrayToTags(t){return t.tags?t.tags:null}static WriteChoice(t,e){t.WriteObjectStart(),t.WriteProperty("text",e.text),t.WriteIntProperty("index",e.index),t.WriteProperty("originalChoicePath",e.sourcePath),t.WriteIntProperty("originalThreadIndex",e.originalThreadIndex),t.WriteProperty("targetPath",e.pathStringOnChoice),t.WriteProperty("isInvisibleDefault",e.isInvisibleDefault),this.WriteChoiceTags(t,e),t.WriteObjectEnd();}static WriteChoiceTags(t,e){if(e.tags&&e.tags.length>0){t.WritePropertyStart("tags"),t.WriteArrayStart();for(let n of e.tags)t.Write(n);t.WriteArrayEnd(),t.WritePropertyEnd();}}static WriteInkList(t,e){let n=e.value;if(n===null)return (0, de.throwNullException)("rawList");t.WriteObjectStart(),t.WritePropertyStart("list"),t.WriteObjectStart();for(let[i,o]of n){let r=Pr.InkListItem.fromSerializedKey(i),a=o;if(r.itemName===null)return (0, de.throwNullException)("item.itemName");t.WritePropertyNameStart(),t.WritePropertyNameInner(r.originName?r.originName:"?"),t.WritePropertyNameInner("."),t.WritePropertyNameInner(r.itemName),t.WritePropertyNameEnd(),t.Write(a),t.WritePropertyEnd();}if(t.WriteObjectEnd(),t.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){t.WritePropertyStart("origins"),t.WriteArrayStart();for(let i of n.originNames)t.Write(i);t.WriteArrayEnd(),t.WritePropertyEnd();}t.WriteObjectEnd();}static ListDefinitionsToJToken(t){let e={};for(let n of t.lists){let i={};for(let[o,r]of n.items){let a=Pr.InkListItem.fromSerializedKey(o);if(a.itemName===null)return (0, de.throwNullException)("item.itemName");i[a.itemName]=r;}e[n.name]=i;}return e}static JTokenToListDefinitions(t){let e=t,n=[];for(let i in e)if(e.hasOwnProperty(i)){let o=i.toString(),r=e[i],a=new Map;for(let l in r)if(e.hasOwnProperty(i)){let h=r[l];a.set(l,parseInt(h));}let u=new Ff.ListDefinition(o,a);n.push(u);}return new wf.ListDefinitionsOrigin(n)}};Nr.JsonSerialisation=Tr;Tr._controlCommandNames=(()=>{let s=[];s[V.ControlCommand.CommandType.EvalStart]="ev",s[V.ControlCommand.CommandType.EvalOutput]="out",s[V.ControlCommand.CommandType.EvalEnd]="/ev",s[V.ControlCommand.CommandType.Duplicate]="du",s[V.ControlCommand.CommandType.PopEvaluatedValue]="pop",s[V.ControlCommand.CommandType.PopFunction]="~ret",s[V.ControlCommand.CommandType.PopTunnel]="->->",s[V.ControlCommand.CommandType.BeginString]="str",s[V.ControlCommand.CommandType.EndString]="/str",s[V.ControlCommand.CommandType.NoOp]="nop",s[V.ControlCommand.CommandType.ChoiceCount]="choiceCnt",s[V.ControlCommand.CommandType.Turns]="turn",s[V.ControlCommand.CommandType.TurnsSince]="turns",s[V.ControlCommand.CommandType.ReadCount]="readc",s[V.ControlCommand.CommandType.Random]="rnd",s[V.ControlCommand.CommandType.SeedRandom]="srnd",s[V.ControlCommand.CommandType.VisitIndex]="visit",s[V.ControlCommand.CommandType.SequenceShuffleIndex]="seq",s[V.ControlCommand.CommandType.StartThread]="thread",s[V.ControlCommand.CommandType.Done]="done",s[V.ControlCommand.CommandType.End]="end",s[V.ControlCommand.CommandType.ListFromInt]="listInt",s[V.ControlCommand.CommandType.ListRange]="range",s[V.ControlCommand.CommandType.ListRandom]="lrnd",s[V.ControlCommand.CommandType.BeginTag]="#",s[V.ControlCommand.CommandType.EndTag]="/#";for(let t=0;t<V.ControlCommand.CommandType.TOTAL_VALUES;++t)if(s[t]==null)throw new Error("Control command not accounted for in serialisation");return s})();});var oo=C(Cn=>{Object.defineProperty(Cn,"__esModule",{value:true});Cn.CallStack=void 0;var so=ue(),rl=ct(),xf=vn(),sl=Re(),Of=$(),Pf=se(),mn=an(),Tf=Ue(),al=be(),ao=it(),gn=class s{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let e=this._threads[this._threads.length-1].callstack;return e[e.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(t){Tf.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(t);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=mn.Pointer.Null,arguments[0]instanceof xf.Story){let t=arguments[0];this._startOfRoot=mn.Pointer.StartOf(t.rootContentContainer),this.Reset();}else {let t=arguments[0];this._threads=[];for(let e of t._threads)this._threads.push(e.Copy());this._threadCounter=t._threadCounter,this._startOfRoot=t._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new s.Thread),this._threads[0].callstack.push(new s.Element(so.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(t,e){this._threads.length=0;let n=t.threads;for(let i of n){let o=i,r=new s.Thread(o,e);this._threads.push(r);}this._threadCounter=parseInt(t.threadCounter),this._startOfRoot=mn.Pointer.StartOf(e.rootContentContainer);}WriteJson(t){t.WriteObject(e=>{e.WritePropertyStart("threads"),e.WriteArrayStart();for(let n of this._threads)n.WriteJson(e);e.WriteArrayEnd(),e.WritePropertyEnd(),e.WritePropertyStart("threadCounter"),e.WriteInt(this._threadCounter),e.WritePropertyEnd();});}PushThread(){let t=this.currentThread.Copy();this._threadCounter++,t.threadIndex=this._threadCounter,this._threads.push(t);}ForkThread(){let t=this.currentThread.Copy();return this._threadCounter++,t.threadIndex=this._threadCounter,t}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==so.PushPopType.FunctionEvaluationFromGame}Push(t,e=0,n=0){let i=new s.Element(t,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=e,i.functionStartInOutputStream=n,this.callStack.push(i);}CanPop(t=null){return this.canPop?t==null?true:this.currentElement.type==t:false}Pop(t=null){if(this.CanPop(t)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(t,e=-1){e==-1&&(e=this.currentElementIndex+1);let n=this.callStack[e-1],i=(0, al.tryGetValueFromMap)(n.temporaryVariables,t,null);return i.exists?i.result:null}SetTemporaryVariable(t,e,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let o=this.callStack[i-1];if(!n&&!o.temporaryVariables.get(t))throw new Error("Could not find temporary variable to set: "+t);let r=(0, al.tryGetValueFromMap)(o.temporaryVariables,t,null);r.exists&&Of.ListValue.RetainListOriginsForAssignment(r.result,e),o.temporaryVariables.set(t,e);}ContextForVariableNamed(t){return this.currentElement.temporaryVariables.get(t)?this.currentElementIndex+1:0}ThreadWithIndex(t){let e=this._threads.filter(n=>{if(n.threadIndex==t)return n});return e.length>0?e[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let t=new Pf.StringBuilder;for(let e=0;e<this._threads.length;e++){let n=this._threads[e],i=e==this._threads.length-1;t.AppendFormat(`=== THREAD {0}/{1} {2}===
20
- `,e+1,this._threads.length,i?"(current) ":"");for(let o=0;o<n.callstack.length;o++){n.callstack[o].type==so.PushPopType.Function?t.Append(" [FUNCTION] "):t.Append(" [TUNNEL] ");let r=n.callstack[o].currentPointer;if(!r.isNull){if(t.Append("<SOMEWHERE IN "),r.container===null)return (0, ao.throwNullException)("pointer.container");t.Append(r.container.path.toString()),t.AppendLine(">");}}}return t.toString()}};Cn.CallStack=gn;(function(s){class t{constructor(i,o,r=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=o.copy(),this.inExpressionEvaluation=r,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new t(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}s.Element=t;class e{constructor(){if(this.threadIndex=0,this.previousPointer=mn.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],o=arguments[1];this.threadIndex=parseInt(i.threadIndex);let r=i.callstack;for(let u of r){let l=u,h=parseInt(l.type),c=mn.Pointer.Null,d,m=l.cPath;if(typeof m<"u"){d=m.toString();let S=o.ContentAtPath(new rl.Path(d));if(c.container=S.container,c.index=parseInt(l.idx),S.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+d+". Has the story changed since this save data was created?");S.approximate&&(c.container!==null?o.Warning("When loading state, exact internal story location couldn't be found: '"+d+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):o.Warning("When loading state, exact internal story location couldn't be found: '"+d+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let D=!!l.exp,v=new t(h,c,D),A=l.temp;typeof A<"u"?v.temporaryVariables=sl.JsonSerialisation.JObjectToDictionaryRuntimeObjs(A):v.temporaryVariables.clear(),this.callstack.push(v);}let a=i.previousContentObject;if(typeof a<"u"){let u=new rl.Path(a.toString());this.previousPointer=o.PointerAtPath(u);}}}Copy(){let i=new e;i.threadIndex=this.threadIndex;for(let o of this.callstack)i.callstack.push(o.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let o of this.callstack){if(i.WriteObjectStart(),!o.currentPointer.isNull){if(o.currentPointer.container===null)return (0, ao.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",o.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",o.currentPointer.index);}i.WriteProperty("exp",o.inExpressionEvaluation),i.WriteIntProperty("type",o.type),o.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),sl.JsonSerialisation.WriteDictionaryRuntimeObjs(i,o.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let o=this.previousPointer.Resolve();if(o===null)return (0, ao.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",o.path.toString());}i.WriteObjectEnd();}}s.Thread=e;})(gn||(Cn.CallStack=gn={}));});var ul=C(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.VariablesState=void 0;var nt=$(),Nf=Je(),ol=Re(),st=L(),Dn=be(),Qt=it();function If(){return class{}}var Ir=class s extends If(){variableChangedEvent(t,e){for(let n of this.variableChangedEventCallbacks)n(t,e);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let t=new Map;if(this._changedVariablesForBatchObs!=null)for(let e of this._changedVariablesForBatchObs){let n=this._globalVariables.get(e);this.variableChangedEvent(e,n);}if(this.patch!=null)for(let e of this.patch.changedVariables){let n=this.patch.TryGetGlobal(e,null);n.exists&&t.set(e,n);}return this._changedVariablesForBatchObs=null,t}NotifyObservers(t){for(let[e,n]of t)this.variableChangedEvent(e,n);}get callStack(){return this._callStack}set callStack(t){this._callStack=t;}$(t,e){if(typeof e>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(t),typeof n>"u"&&(n=this._defaultGlobalVariables.get(t)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(t)>"u")throw new Nf.StoryException("Cannot assign to a variable ("+t+") that hasn't been declared in the story");let n=nt.Value.Create(e);if(n==null)throw e==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+e.toString());this.SetGlobal(t,n);}}constructor(t,e){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=t,this._listDefsOrigin=e;try{return new Proxy(this,{get(i,o){return o in i?i[o]:i.$(o)},set(i,o,r){return o in i?i[o]=r:i.$(o,r),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,o){return {enumerable:!0,configurable:!0,value:i.$(o)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Qt.throwNullException)("this.patch");for(let[t,e]of this.patch.globals)this._globalVariables.set(t,e);if(this._changedVariablesForBatchObs!==null)for(let t of this.patch.changedVariables)this._changedVariablesForBatchObs.add(t);this.patch=null;}SetJsonToken(t){this._globalVariables.clear();for(let[e,n]of this._defaultGlobalVariables){let i=t[e];if(typeof i<"u"){let o=ol.JsonSerialisation.JTokenToRuntimeObject(i);if(o===null)return (0, Qt.throwNullException)("tokenInkObject");this._globalVariables.set(e,o);}else this._globalVariables.set(e,n);}}WriteJson(t){t.WriteObjectStart();for(let[e,n]of this._globalVariables){let i=e,o=n;if(s.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let r=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(o,r))continue}t.WritePropertyStart(i),ol.JsonSerialisation.WriteRuntimeObject(t,o),t.WritePropertyEnd();}t.WriteObjectEnd();}RuntimeObjectsEqual(t,e){if(t===null)return (0, Qt.throwNullException)("obj1");if(e===null)return (0, Qt.throwNullException)("obj2");if(t.constructor!==e.constructor)return false;let n=(0, st.asOrNull)(t,nt.BoolValue);if(n!==null)return n.value===(0, st.asOrThrows)(e,nt.BoolValue).value;let i=(0, st.asOrNull)(t,nt.IntValue);if(i!==null)return i.value===(0, st.asOrThrows)(e,nt.IntValue).value;let o=(0, st.asOrNull)(t,nt.FloatValue);if(o!==null)return o.value===(0, st.asOrThrows)(e,nt.FloatValue).value;let r=(0, st.asOrNull)(t,nt.Value),a=(0, st.asOrNull)(e,nt.Value);if(r!==null&&a!==null)return (0, st.isEquatable)(r.valueObject)&&(0, st.isEquatable)(a.valueObject)?r.valueObject.Equals(a.valueObject):r.valueObject===a.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+t.constructor.name)}GetVariableWithName(t,e=-1){let n=this.GetRawVariableWithName(t,e),i=(0, st.asOrNull)(n,nt.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(t){let e=(0, Dn.tryGetValueFromMap)(this._defaultGlobalVariables,t,null);return e.exists?e.result:null}GlobalVariableExistsWithName(t){return this._globalVariables.has(t)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(t)}GetRawVariableWithName(t,e){let n=null;if(e==0||e==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(t,null),i.exists)||(i=(0, Dn.tryGetValueFromMap)(this._globalVariables,t,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Dn.tryGetValueFromMap)(this._defaultGlobalVariables,t,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Qt.throwNullException)("VariablesState._listDefsOrigin");let o=this._listDefsOrigin.FindSingleItemListWithName(t);if(o)return o}return n=this._callStack.GetTemporaryVariableWithName(t,e),n}ValueAtVariablePointer(t){return this.GetVariableWithName(t.variableName,t.contextIndex)}Assign(t,e){let n=t.variableName;if(n===null)return (0, Qt.throwNullException)("name");let i=-1,o=false;if(t.isNewDeclaration?o=t.isGlobal:o=this.GlobalVariableExistsWithName(n),t.isNewDeclaration){let r=(0, st.asOrNull)(e,nt.VariablePointerValue);r!==null&&(e=this.ResolveVariablePointer(r));}else {let r=null;do r=(0, st.asOrNull)(this.GetRawVariableWithName(n,i),nt.VariablePointerValue),r!=null&&(n=r.variableName,i=r.contextIndex,o=i==0);while(r!=null)}o?this.SetGlobal(n,e):this._callStack.SetTemporaryVariable(n,e,t.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(t,e){let n=(0, st.asOrThrows)(t,nt.ListValue),i=(0, st.asOrThrows)(e,nt.ListValue);n.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(t,e){let n=null;if(this.patch===null&&(n=(0, Dn.tryGetValueFromMap)(this._globalVariables,t,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists||(n=(0, Dn.tryGetValueFromMap)(this._globalVariables,t,null))),nt.ListValue.RetainListOriginsForAssignment(n.result,e),t===null)return (0, Qt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(t,e):this._globalVariables.set(t,e),this.variableChangedEvent!==null&&n!==null&&e!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Qt.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(t):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(t);}else this.variableChangedEvent(t,e);}ResolveVariablePointer(t){let e=t.contextIndex;e==-1&&(e=this.GetContextIndexOfVariableNamed(t.variableName));let n=this.GetRawVariableWithName(t.variableName,e),i=(0, st.asOrNull)(n,nt.VariablePointerValue);return i??new nt.VariablePointerValue(t.variableName,e)}GetContextIndexOfVariableNamed(t){return this.GlobalVariableExistsWithName(t)?0:this._callStack.currentElementIndex}ObserveVariableChange(t){this.variableChangedEventCallbacks.push(t);}};kr.VariablesState=Ir;Ir.dontSaveDefaultValues=true;});var lo=C(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.PRNG=void 0;var uo=class{constructor(t){this.seed=t%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};Rr.PRNG=uo;});var ll=C(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.StatePatch=void 0;var ho=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let t=arguments[0];this._globals=new Map(t._globals),this._changedVariables=new Set(t._changedVariables),this._visitCounts=new Map(t._visitCounts),this._turnIndices=new Map(t._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(t,e){return t!==null&&this._globals.has(t)?{result:this._globals.get(t),exists:true}:{result:e,exists:false}}SetGlobal(t,e){this._globals.set(t,e);}AddChangedVariable(t){return this._changedVariables.add(t)}TryGetVisitCount(t,e){return this._visitCounts.has(t)?{result:this._visitCounts.get(t),exists:true}:{result:e,exists:false}}SetVisitCount(t,e){this._visitCounts.set(t,e);}SetTurnIndex(t,e){this._turnIndices.set(t,e);}TryGetTurnIndex(t,e){return this._turnIndices.has(t)?{result:this._turnIndices.get(t),exists:true}:{result:e,exists:false}}};Vr.StatePatch=ho;});var co=C(Sn=>{Object.defineProperty(Sn,"__esModule",{value:true});Sn.SimpleJson=void 0;var En=class s{static TextToDictionary(t){return new s.Reader(t).ToDictionary()}static TextToArray(t){return new s.Reader(t).ToArray()}};Sn.SimpleJson=En;(function(s){class t{constructor(i){if(JSON.parse("0",(r,a,u)=>u!=null)){let r=(a,u,l)=>Number.isInteger(u)&&l.source.endsWith(".0")?l.source+"f":u;this._rootObject=JSON.parse(i,r);}else {let r=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(r);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}s.Reader=t;class e{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let o=this._propertyNameStack.pop();this.currentCollection[o]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===s.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,o){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let r=arguments[1];r(this);}else {let r=arguments[1];this.Write(r);}this.WritePropertyEnd();}WriteIntProperty(i,o){this.WritePropertyStart(i),this.WriteInt(o),this.WritePropertyEnd();}WriteFloatProperty(i,o){this.WritePropertyStart(i),this.WriteFloat(o),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===s.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===s.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===s.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property)),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let o=this._propertyNameStack.pop();this.currentCollection[o]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===s.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,o=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==s.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,o=true){if(this.Assert(this.state===s.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===s.Writer.State.None||this.state===s.Writer.State.Property||this.state===s.Writer.State.Array):this.Assert(this.state===s.Writer.State.Property||this.state===s.Writer.State.Array),this.state===s.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===s.Writer.State.Array||this.state===s.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:s.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===s.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===s.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}s.Writer=e,(function(n){(function(r){r[r.None=0]="None",r[r.Object=1]="Object",r[r.Array=2]="Array",r[r.Property=3]="Property",r[r.PropertyName=4]="PropertyName",r[r.String=5]="String";})(n.State||(n.State={}));class o{constructor(a){this.type=s.Writer.State.None,this.childCount=0,this.type=a;}}n.StateElement=o;})(e=s.Writer||(s.Writer={}));})(En||(Sn.SimpleJson=En={}));});var cl=C(Lr=>{Object.defineProperty(Lr,"__esModule",{value:true});Lr.Flow=void 0;var hl=oo(),Br=Re(),kf=it(),fo=class{constructor(){let t=arguments[0],e=arguments[1];if(this.name=t,this.callStack=new hl.CallStack(e),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,e),this.outputStream=Br.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=Br.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let i=n.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,e);}else this.outputStream=[],this.currentChoices=[];}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),t.WriteProperty("outputStream",n=>Br.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let e=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, kf.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(e||(e=true,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(t),t.WritePropertyEnd());}e&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let i of this.currentChoices)Br.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),t.WriteObjectEnd();}LoadFlowChoiceThreads(t,e){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let o=t[`${n.originalThreadIndex}`];n.threadAtGeneration=new hl.CallStack.Thread(o,e);}}}};Lr.Flow=fo;});var pl=C(qr=>{Object.defineProperty(qr,"__esModule",{value:true});qr.StoryState=void 0;var Rf=oo(),Vf=ul(),Z=$(),Zt=ue(),Bf=Fr(),po=gr(),dl=ct(),lt=rt(),mo=se(),te=Re(),Lf=lo(),Wf=oe(),Ve=an(),yn=be(),z=L(),qf=Ue(),At=it(),jf=vn(),Mf=ll(),fl=co(),Wr=cl(),Gf=pt(),go=class s{ToJson(t=false){let e=new fl.SimpleJson.Writer;return this.WriteJson(e),e.toString()}toJson(t=false){return this.ToJson(t)}LoadJson(t){let e=fl.SimpleJson.TextToDictionary(t);this.LoadJsonObj(e),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(t){let e;if(this._patch!==null){let n=this.story.ContentAtPath(new dl.Path(t)).container;if(n===null)throw new Error("Content at path not found: "+t);if(e=this._patch.TryGetVisitCount(n,0),e.exists)return e.result}return e=(0, yn.tryGetValueFromMap)(this._visitCounts,t,null),e.exists?e.result:0}VisitCountForContainer(t){if(t===null)return (0, At.throwNullException)("container");if(!t.visitsShouldBeCounted)return this.story.Error("Read count for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(t,0);if(i.exists)return i.result}let e=t.path.toString(),n=(0, yn.tryGetValueFromMap)(this._visitCounts,e,null);return n.exists?n.result:0}IncrementVisitCountForContainer(t){if(this._patch!==null){let i=this.VisitCountForContainer(t);i++,this._patch.SetVisitCount(t,i);return}let e=t.path.toString(),n=(0, yn.tryGetValueFromMap)(this._visitCounts,e,null);n.exists?this._visitCounts.set(e,n.result+1):this._visitCounts.set(e,1);}RecordTurnIndexVisitToContainer(t){if(this._patch!==null){this._patch.SetTurnIndex(t,this.currentTurnIndex);return}let e=t.path.toString();this._turnIndices.set(e,this.currentTurnIndex);}TurnsSinceForContainer(t){if(t.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(t,0);if(i.exists)return this.currentTurnIndex-i.result}let e=t.path.toString(),n=(0, yn.tryGetValueFromMap)(this._turnIndices,e,0);return n.exists?this.currentTurnIndex-n.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(t){this._variablesState=t;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(t){this._currentTurnIndex=t;}get currentPathString(){let t=this.currentPointer;return t.isNull?null:t.path===null?(0, At.throwNullException)("pointer.path"):t.path.toString()}get previousPathString(){let t=this.previousPointer;return t.isNull?null:t.path===null?(0, At.throwNullException)("previousPointer.path"):t.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(t){this.callStack.currentElement.currentPointer=t.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(t){this.callStack.currentThread.previousPointer=t.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let t=new mo.StringBuilder,e=false;for(let n of this.outputStream){let i=(0, z.asOrNull)(n,Z.StringValue);if(!e&&i!==null)t.Append(i.value);else {let o=(0, z.asOrNull)(n,lt.ControlCommand);o!==null&&(o.commandType==lt.ControlCommand.CommandType.BeginTag?e=true:o.commandType==lt.ControlCommand.CommandType.EndTag&&(e=false));}}this._currentText=this.CleanOutputWhitespace(t.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(t){let e=new mo.StringBuilder,n=-1,i=0;for(let o=0;o<t.length;o++){let r=t.charAt(o),a=r==" "||r==" ";a&&n==-1&&(n=o),a||(r!=`
19
+ `);if(e=="<>")return new Yu.Glue;for(let o=0;o<s._controlCommandNames.length;++o){let r=s._controlCommandNames[o];if(e==r)return new B.ControlCommand(o)}if(e=="L^"&&(e="^"),so.NativeFunctionCall.CallExistsWithName(e))return so.NativeFunctionCall.CallWithName(e);if(e=="->->")return B.ControlCommand.PopTunnel();if(e=="~ret")return B.ControlCommand.PopFunction();if(e=="void")return new el.Void}if(typeof t=="object"&&!Array.isArray(t)){let e=t,n;if(e["^->"])return n=e["^->"],new gt.DivertTargetValue(new Ff.Path(n.toString()));if(e["^var"]){n=e["^var"];let h=new gt.VariablePointerValue(n.toString());return "ci"in e&&(n=e.ci,h.contextIndex=parseInt(n)),h}let i=false,o=false,r=ke.PushPopType.Function,a=false;if((n=e["->"])?i=true:(n=e["f()"])?(i=true,o=true,r=ke.PushPopType.Function):(n=e["->t->"])?(i=true,o=true,r=ke.PushPopType.Tunnel):(n=e["x()"])&&(i=true,a=true,o=false,r=ke.PushPopType.Function),i){let h=new Qu.Divert;h.pushesToStack=o,h.stackPushType=r,h.isExternal=a;let c=n.toString();return (n=e.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!e.c,a&&(n=e.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=e["*"]){let h=new Zu.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=e.flg)&&(h.flags=parseInt(n)),h}if(n=e["VAR?"])return new ro.VariableReference(n.toString());if(n=e["CNT?"]){let h=new ro.VariableReference;return h.pathStringForCount=n.toString(),h}let u=false,l=false;if((n=e["VAR="])?(u=true,l=true):(n=e["temp="])&&(u=true,l=false),u){let h=n.toString(),c=!e.re,m=new tl.VariableAssignment(h,c);return m.isGlobal=l,m}if(e["#"]!==void 0)return n=e["#"],new nl.Tag(n.toString());if(n=e.list){let h=n,c=new Tr.InkList;if(n=e.origins){let m=n;c.SetInitialOriginNames(m);}for(let m in h)if(h.hasOwnProperty(m)){let g=h[m],E=new Tr.InkListItem(m),v=parseInt(g);c.Add(E,v);}return new gt.ListValue(c)}if(e.originalChoicePath!=null)return this.JObjectToChoice(e)}if(Array.isArray(t))return this.JArrayToContainer(t);if(t==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(t,["parent"]))}static toJson(t,e,n){return JSON.stringify(t,(i,o)=>e?.some(r=>r===i)?void 0:o,n)}static WriteRuntimeContainer(t,e,n=false){if(t.WriteArrayStart(),e===null)return (0, de.throwNullException)("container");for(let u of e.content)this.WriteRuntimeObject(t,u);let i=e.namedOnlyContent,o=e.countFlags,r=e.name!=null&&!n,a=i!=null||o>0||r;if(a&&t.WriteObjectStart(),i!=null)for(let[u,l]of i){let h=u,c=(0, z.asOrNull)(l,Pr.Container);t.WritePropertyStart(h),this.WriteRuntimeContainer(t,c,true),t.WritePropertyEnd();}o>0&&t.WriteIntProperty("#f",o),r&&t.WriteProperty("#n",e.name),a?t.WriteObjectEnd():t.WriteNull(),t.WriteArrayEnd();}static JArrayToContainer(t){let e=new Pr.Container;e.content=this.JArrayToRuntimeObjList(t,true);let n=t[t.length-1];if(n!=null){let i=new Map;for(let o in n)if(o=="#f")e.countFlags=parseInt(n[o]);else if(o=="#n")e.name=n[o].toString();else {let r=this.JTokenToRuntimeObject(n[o]),a=(0, z.asOrNull)(r,Pr.Container);a&&(a.name=o),i.set(o,r);}e.namedOnlyContent=i;}return e}static JObjectToChoice(t){let e=new il.Choice;return e.text=t.text.toString(),e.index=parseInt(t.index),e.sourcePath=t.originalChoicePath.toString(),e.originalThreadIndex=parseInt(t.originalThreadIndex),e.pathStringOnChoice=t.targetPath.toString(),e.tags=this.JArrayToTags(t),e.isInvisibleDefault=!!t.isInvisibleDefault,e}static JArrayToTags(t){return t.tags?t.tags:null}static WriteChoice(t,e){t.WriteObjectStart(),t.WriteProperty("text",e.text),t.WriteIntProperty("index",e.index),t.WriteProperty("originalChoicePath",e.sourcePath),t.WriteIntProperty("originalThreadIndex",e.originalThreadIndex),t.WriteProperty("targetPath",e.pathStringOnChoice),t.WriteProperty("isInvisibleDefault",e.isInvisibleDefault),this.WriteChoiceTags(t,e),t.WriteObjectEnd();}static WriteChoiceTags(t,e){if(e.tags&&e.tags.length>0){t.WritePropertyStart("tags"),t.WriteArrayStart();for(let n of e.tags)t.Write(n);t.WriteArrayEnd(),t.WritePropertyEnd();}}static WriteInkList(t,e){let n=e.value;if(n===null)return (0, de.throwNullException)("rawList");t.WriteObjectStart(),t.WritePropertyStart("list"),t.WriteObjectStart();for(let[i,o]of n){let r=Tr.InkListItem.fromSerializedKey(i),a=o;if(r.itemName===null)return (0, de.throwNullException)("item.itemName");t.WritePropertyNameStart(),t.WritePropertyNameInner(r.originName?r.originName:"?"),t.WritePropertyNameInner("."),t.WritePropertyNameInner(r.itemName),t.WritePropertyNameEnd(),t.Write(a),t.WritePropertyEnd();}if(t.WriteObjectEnd(),t.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){t.WritePropertyStart("origins"),t.WriteArrayStart();for(let i of n.originNames)t.Write(i);t.WriteArrayEnd(),t.WritePropertyEnd();}t.WriteObjectEnd();}static ListDefinitionsToJToken(t){let e={};for(let n of t.lists){let i={};for(let[o,r]of n.items){let a=Tr.InkListItem.fromSerializedKey(o);if(a.itemName===null)return (0, de.throwNullException)("item.itemName");i[a.itemName]=r;}e[n.name]=i;}return e}static JTokenToListDefinitions(t){let e=t,n=[];for(let i in e)if(e.hasOwnProperty(i)){let o=i.toString(),r=e[i],a=new Map;for(let l in r)if(e.hasOwnProperty(i)){let h=r[l];a.set(l,parseInt(h));}let u=new wf.ListDefinition(o,a);n.push(u);}return new xf.ListDefinitionsOrigin(n)}};Ir.JsonSerialisation=Nr;Nr._controlCommandNames=(()=>{let s=[];s[B.ControlCommand.CommandType.EvalStart]="ev",s[B.ControlCommand.CommandType.EvalOutput]="out",s[B.ControlCommand.CommandType.EvalEnd]="/ev",s[B.ControlCommand.CommandType.Duplicate]="du",s[B.ControlCommand.CommandType.PopEvaluatedValue]="pop",s[B.ControlCommand.CommandType.PopFunction]="~ret",s[B.ControlCommand.CommandType.PopTunnel]="->->",s[B.ControlCommand.CommandType.BeginString]="str",s[B.ControlCommand.CommandType.EndString]="/str",s[B.ControlCommand.CommandType.NoOp]="nop",s[B.ControlCommand.CommandType.ChoiceCount]="choiceCnt",s[B.ControlCommand.CommandType.Turns]="turn",s[B.ControlCommand.CommandType.TurnsSince]="turns",s[B.ControlCommand.CommandType.ReadCount]="readc",s[B.ControlCommand.CommandType.Random]="rnd",s[B.ControlCommand.CommandType.SeedRandom]="srnd",s[B.ControlCommand.CommandType.VisitIndex]="visit",s[B.ControlCommand.CommandType.SequenceShuffleIndex]="seq",s[B.ControlCommand.CommandType.StartThread]="thread",s[B.ControlCommand.CommandType.Done]="done",s[B.ControlCommand.CommandType.End]="end",s[B.ControlCommand.CommandType.ListFromInt]="listInt",s[B.ControlCommand.CommandType.ListRange]="range",s[B.ControlCommand.CommandType.ListRandom]="lrnd",s[B.ControlCommand.CommandType.BeginTag]="#",s[B.ControlCommand.CommandType.EndTag]="/#";for(let t=0;t<B.ControlCommand.CommandType.TOTAL_VALUES;++t)if(s[t]==null)throw new Error("Control command not accounted for in serialisation");return s})();});var uo=C(vn=>{Object.defineProperty(vn,"__esModule",{value:true});vn.CallStack=void 0;var ao=ue(),rl=ct(),Of=Dn(),sl=Re(),Pf=H(),Tf=se(),gn=on(),Nf=Ke(),al=be(),oo=it(),Cn=class s{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let e=this._threads[this._threads.length-1].callstack;return e[e.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(t){Nf.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(t);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=gn.Pointer.Null,arguments[0]instanceof Of.Story){let t=arguments[0];this._startOfRoot=gn.Pointer.StartOf(t.rootContentContainer),this.Reset();}else {let t=arguments[0];this._threads=[];for(let e of t._threads)this._threads.push(e.Copy());this._threadCounter=t._threadCounter,this._startOfRoot=t._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new s.Thread),this._threads[0].callstack.push(new s.Element(ao.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(t,e){this._threads.length=0;let n=t.threads;for(let i of n){let o=i,r=new s.Thread(o,e);this._threads.push(r);}this._threadCounter=parseInt(t.threadCounter),this._startOfRoot=gn.Pointer.StartOf(e.rootContentContainer);}WriteJson(t){t.WriteObject(e=>{e.WritePropertyStart("threads"),e.WriteArrayStart();for(let n of this._threads)n.WriteJson(e);e.WriteArrayEnd(),e.WritePropertyEnd(),e.WritePropertyStart("threadCounter"),e.WriteInt(this._threadCounter),e.WritePropertyEnd();});}PushThread(){let t=this.currentThread.Copy();this._threadCounter++,t.threadIndex=this._threadCounter,this._threads.push(t);}ForkThread(){let t=this.currentThread.Copy();return this._threadCounter++,t.threadIndex=this._threadCounter,t}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==ao.PushPopType.FunctionEvaluationFromGame}Push(t,e=0,n=0){let i=new s.Element(t,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=e,i.functionStartInOutputStream=n,this.callStack.push(i);}CanPop(t=null){return this.canPop?t==null?true:this.currentElement.type==t:false}Pop(t=null){if(this.CanPop(t)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(t,e=-1){e==-1&&(e=this.currentElementIndex+1);let n=this.callStack[e-1],i=(0, al.tryGetValueFromMap)(n.temporaryVariables,t,null);return i.exists?i.result:null}SetTemporaryVariable(t,e,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let o=this.callStack[i-1];if(!n&&!o.temporaryVariables.get(t))throw new Error("Could not find temporary variable to set: "+t);let r=(0, al.tryGetValueFromMap)(o.temporaryVariables,t,null);r.exists&&Pf.ListValue.RetainListOriginsForAssignment(r.result,e),o.temporaryVariables.set(t,e);}ContextForVariableNamed(t){return this.currentElement.temporaryVariables.get(t)?this.currentElementIndex+1:0}ThreadWithIndex(t){let e=this._threads.filter(n=>{if(n.threadIndex==t)return n});return e.length>0?e[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let t=new Tf.StringBuilder;for(let e=0;e<this._threads.length;e++){let n=this._threads[e],i=e==this._threads.length-1;t.AppendFormat(`=== THREAD {0}/{1} {2}===
20
+ `,e+1,this._threads.length,i?"(current) ":"");for(let o=0;o<n.callstack.length;o++){n.callstack[o].type==ao.PushPopType.Function?t.Append(" [FUNCTION] "):t.Append(" [TUNNEL] ");let r=n.callstack[o].currentPointer;if(!r.isNull){if(t.Append("<SOMEWHERE IN "),r.container===null)return (0, oo.throwNullException)("pointer.container");t.Append(r.container.path.toString()),t.AppendLine(">");}}}return t.toString()}};vn.CallStack=Cn;(function(s){class t{constructor(i,o,r=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=o.copy(),this.inExpressionEvaluation=r,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new t(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}s.Element=t;class e{constructor(){if(this.threadIndex=0,this.previousPointer=gn.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],o=arguments[1];this.threadIndex=parseInt(i.threadIndex);let r=i.callstack;for(let u of r){let l=u,h=parseInt(l.type),c=gn.Pointer.Null,m,g=l.cPath;if(typeof g<"u"){m=g.toString();let y=o.ContentAtPath(new rl.Path(m));if(c.container=y.container,c.index=parseInt(l.idx),y.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+m+". Has the story changed since this save data was created?");y.approximate&&(c.container!==null?o.Warning("When loading state, exact internal story location couldn't be found: '"+m+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):o.Warning("When loading state, exact internal story location couldn't be found: '"+m+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let E=!!l.exp,v=new t(h,c,E),S=l.temp;typeof S<"u"?v.temporaryVariables=sl.JsonSerialisation.JObjectToDictionaryRuntimeObjs(S):v.temporaryVariables.clear(),this.callstack.push(v);}let a=i.previousContentObject;if(typeof a<"u"){let u=new rl.Path(a.toString());this.previousPointer=o.PointerAtPath(u);}}}Copy(){let i=new e;i.threadIndex=this.threadIndex;for(let o of this.callstack)i.callstack.push(o.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let o of this.callstack){if(i.WriteObjectStart(),!o.currentPointer.isNull){if(o.currentPointer.container===null)return (0, oo.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",o.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",o.currentPointer.index);}i.WriteProperty("exp",o.inExpressionEvaluation),i.WriteIntProperty("type",o.type),o.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),sl.JsonSerialisation.WriteDictionaryRuntimeObjs(i,o.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let o=this.previousPointer.Resolve();if(o===null)return (0, oo.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",o.path.toString());}i.WriteObjectEnd();}}s.Thread=e;})(Cn||(vn.CallStack=Cn={}));});var ul=C(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.VariablesState=void 0;var nt=H(),If=ze(),ol=Re(),st=W(),En=be(),Qt=it();function kf(){return class{}}var kr=class s extends kf(){variableChangedEvent(t,e){for(let n of this.variableChangedEventCallbacks)n(t,e);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let t=new Map;if(this._changedVariablesForBatchObs!=null)for(let e of this._changedVariablesForBatchObs){let n=this._globalVariables.get(e);this.variableChangedEvent(e,n);}if(this.patch!=null)for(let e of this.patch.changedVariables){let n=this.patch.TryGetGlobal(e,null);n.exists&&t.set(e,n);}return this._changedVariablesForBatchObs=null,t}NotifyObservers(t){for(let[e,n]of t)this.variableChangedEvent(e,n);}get callStack(){return this._callStack}set callStack(t){this._callStack=t;}$(t,e){if(typeof e>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(t),typeof n>"u"&&(n=this._defaultGlobalVariables.get(t)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(t)>"u")throw new If.StoryException("Cannot assign to a variable ("+t+") that hasn't been declared in the story");let n=nt.Value.Create(e);if(n==null)throw e==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+e.toString());this.SetGlobal(t,n);}}constructor(t,e){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=t,this._listDefsOrigin=e;try{return new Proxy(this,{get(i,o){return o in i?i[o]:i.$(o)},set(i,o,r){return o in i?i[o]=r:i.$(o,r),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,o){return {enumerable:!0,configurable:!0,value:i.$(o)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Qt.throwNullException)("this.patch");for(let[t,e]of this.patch.globals)this._globalVariables.set(t,e);if(this._changedVariablesForBatchObs!==null)for(let t of this.patch.changedVariables)this._changedVariablesForBatchObs.add(t);this.patch=null;}SetJsonToken(t){this._globalVariables.clear();for(let[e,n]of this._defaultGlobalVariables){let i=t[e];if(typeof i<"u"){let o=ol.JsonSerialisation.JTokenToRuntimeObject(i);if(o===null)return (0, Qt.throwNullException)("tokenInkObject");this._globalVariables.set(e,o);}else this._globalVariables.set(e,n);}}WriteJson(t){t.WriteObjectStart();for(let[e,n]of this._globalVariables){let i=e,o=n;if(s.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let r=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(o,r))continue}t.WritePropertyStart(i),ol.JsonSerialisation.WriteRuntimeObject(t,o),t.WritePropertyEnd();}t.WriteObjectEnd();}RuntimeObjectsEqual(t,e){if(t===null)return (0, Qt.throwNullException)("obj1");if(e===null)return (0, Qt.throwNullException)("obj2");if(t.constructor!==e.constructor)return false;let n=(0, st.asOrNull)(t,nt.BoolValue);if(n!==null)return n.value===(0, st.asOrThrows)(e,nt.BoolValue).value;let i=(0, st.asOrNull)(t,nt.IntValue);if(i!==null)return i.value===(0, st.asOrThrows)(e,nt.IntValue).value;let o=(0, st.asOrNull)(t,nt.FloatValue);if(o!==null)return o.value===(0, st.asOrThrows)(e,nt.FloatValue).value;let r=(0, st.asOrNull)(t,nt.Value),a=(0, st.asOrNull)(e,nt.Value);if(r!==null&&a!==null)return (0, st.isEquatable)(r.valueObject)&&(0, st.isEquatable)(a.valueObject)?r.valueObject.Equals(a.valueObject):r.valueObject===a.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+t.constructor.name)}GetVariableWithName(t,e=-1){let n=this.GetRawVariableWithName(t,e),i=(0, st.asOrNull)(n,nt.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(t){let e=(0, En.tryGetValueFromMap)(this._defaultGlobalVariables,t,null);return e.exists?e.result:null}GlobalVariableExistsWithName(t){return this._globalVariables.has(t)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(t)}GetRawVariableWithName(t,e){let n=null;if(e==0||e==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(t,null),i.exists)||(i=(0, En.tryGetValueFromMap)(this._globalVariables,t,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, En.tryGetValueFromMap)(this._defaultGlobalVariables,t,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Qt.throwNullException)("VariablesState._listDefsOrigin");let o=this._listDefsOrigin.FindSingleItemListWithName(t);if(o)return o}return n=this._callStack.GetTemporaryVariableWithName(t,e),n}ValueAtVariablePointer(t){return this.GetVariableWithName(t.variableName,t.contextIndex)}Assign(t,e){let n=t.variableName;if(n===null)return (0, Qt.throwNullException)("name");let i=-1,o=false;if(t.isNewDeclaration?o=t.isGlobal:o=this.GlobalVariableExistsWithName(n),t.isNewDeclaration){let r=(0, st.asOrNull)(e,nt.VariablePointerValue);r!==null&&(e=this.ResolveVariablePointer(r));}else {let r=null;do r=(0, st.asOrNull)(this.GetRawVariableWithName(n,i),nt.VariablePointerValue),r!=null&&(n=r.variableName,i=r.contextIndex,o=i==0);while(r!=null)}o?this.SetGlobal(n,e):this._callStack.SetTemporaryVariable(n,e,t.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(t,e){let n=(0, st.asOrThrows)(t,nt.ListValue),i=(0, st.asOrThrows)(e,nt.ListValue);n.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(t,e){let n=null;if(this.patch===null&&(n=(0, En.tryGetValueFromMap)(this._globalVariables,t,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists||(n=(0, En.tryGetValueFromMap)(this._globalVariables,t,null))),nt.ListValue.RetainListOriginsForAssignment(n.result,e),t===null)return (0, Qt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(t,e):this._globalVariables.set(t,e),this.variableChangedEvent!==null&&n!==null&&e!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Qt.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(t):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(t);}else this.variableChangedEvent(t,e);}ResolveVariablePointer(t){let e=t.contextIndex;e==-1&&(e=this.GetContextIndexOfVariableNamed(t.variableName));let n=this.GetRawVariableWithName(t.variableName,e),i=(0, st.asOrNull)(n,nt.VariablePointerValue);return i??new nt.VariablePointerValue(t.variableName,e)}GetContextIndexOfVariableNamed(t){return this.GlobalVariableExistsWithName(t)?0:this._callStack.currentElementIndex}ObserveVariableChange(t){this.variableChangedEventCallbacks.push(t);}};Rr.VariablesState=kr;kr.dontSaveDefaultValues=true;});var ho=C(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.PRNG=void 0;var lo=class{constructor(t){this.seed=t%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};Vr.PRNG=lo;});var ll=C(Br=>{Object.defineProperty(Br,"__esModule",{value:true});Br.StatePatch=void 0;var co=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let t=arguments[0];this._globals=new Map(t._globals),this._changedVariables=new Set(t._changedVariables),this._visitCounts=new Map(t._visitCounts),this._turnIndices=new Map(t._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(t,e){return t!==null&&this._globals.has(t)?{result:this._globals.get(t),exists:true}:{result:e,exists:false}}SetGlobal(t,e){this._globals.set(t,e);}AddChangedVariable(t){return this._changedVariables.add(t)}TryGetVisitCount(t,e){return this._visitCounts.has(t)?{result:this._visitCounts.get(t),exists:true}:{result:e,exists:false}}SetVisitCount(t,e){this._visitCounts.set(t,e);}SetTurnIndex(t,e){this._turnIndices.set(t,e);}TryGetTurnIndex(t,e){return this._turnIndices.has(t)?{result:this._turnIndices.get(t),exists:true}:{result:e,exists:false}}};Br.StatePatch=co;});var fo=C(Sn=>{Object.defineProperty(Sn,"__esModule",{value:true});Sn.SimpleJson=void 0;var yn=class s{static TextToDictionary(t){return new s.Reader(t).ToDictionary()}static TextToArray(t){return new s.Reader(t).ToArray()}};Sn.SimpleJson=yn;(function(s){class t{constructor(i){if(JSON.parse("0",(r,a,u)=>u!=null)){let r=(a,u,l)=>Number.isInteger(u)&&l.source.endsWith(".0")?l.source+"f":u;this._rootObject=JSON.parse(i,r);}else {let r=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(r);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}s.Reader=t;class e{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let o=this._propertyNameStack.pop();this.currentCollection[o]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===s.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,o){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let r=arguments[1];r(this);}else {let r=arguments[1];this.Write(r);}this.WritePropertyEnd();}WriteIntProperty(i,o){this.WritePropertyStart(i),this.WriteInt(o),this.WritePropertyEnd();}WriteFloatProperty(i,o){this.WritePropertyStart(i),this.WriteFloat(o),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===s.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===s.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===s.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property)),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let o=this._propertyNameStack.pop();this.currentCollection[o]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===s.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,o=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==s.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,o=true){if(this.Assert(this.state===s.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===s.Writer.State.None||this.state===s.Writer.State.Property||this.state===s.Writer.State.Array):this.Assert(this.state===s.Writer.State.Property||this.state===s.Writer.State.Array),this.state===s.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===s.Writer.State.Array||this.state===s.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:s.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===s.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===s.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}s.Writer=e,(function(n){(function(r){r[r.None=0]="None",r[r.Object=1]="Object",r[r.Array=2]="Array",r[r.Property=3]="Property",r[r.PropertyName=4]="PropertyName",r[r.String=5]="String";})(n.State||(n.State={}));class o{constructor(a){this.type=s.Writer.State.None,this.childCount=0,this.type=a;}}n.StateElement=o;})(e=s.Writer||(s.Writer={}));})(yn||(Sn.SimpleJson=yn={}));});var cl=C(Wr=>{Object.defineProperty(Wr,"__esModule",{value:true});Wr.Flow=void 0;var hl=uo(),Lr=Re(),Rf=it(),po=class{constructor(){let t=arguments[0],e=arguments[1];if(this.name=t,this.callStack=new hl.CallStack(e),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,e),this.outputStream=Lr.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=Lr.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let i=n.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,e);}else this.outputStream=[],this.currentChoices=[];}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),t.WriteProperty("outputStream",n=>Lr.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let e=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, Rf.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(e||(e=true,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(t),t.WritePropertyEnd());}e&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let i of this.currentChoices)Lr.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),t.WriteObjectEnd();}LoadFlowChoiceThreads(t,e){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let o=t[`${n.originalThreadIndex}`];n.threadAtGeneration=new hl.CallStack.Thread(o,e);}}}};Wr.Flow=po;});var pl=C(jr=>{Object.defineProperty(jr,"__esModule",{value:true});jr.StoryState=void 0;var Vf=uo(),Bf=ul(),Z=H(),Zt=ue(),Lf=wr(),mo=Cr(),dl=ct(),lt=rt(),go=se(),te=Re(),Wf=ho(),qf=oe(),Ve=on(),bn=be(),X=W(),jf=Ke(),At=it(),Mf=Dn(),Gf=ll(),fl=fo(),qr=cl(),$f=pt(),Co=class s{ToJson(t=false){let e=new fl.SimpleJson.Writer;return this.WriteJson(e),e.toString()}toJson(t=false){return this.ToJson(t)}LoadJson(t){let e=fl.SimpleJson.TextToDictionary(t);this.LoadJsonObj(e),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(t){let e;if(this._patch!==null){let n=this.story.ContentAtPath(new dl.Path(t)).container;if(n===null)throw new Error("Content at path not found: "+t);if(e=this._patch.TryGetVisitCount(n,0),e.exists)return e.result}return e=(0, bn.tryGetValueFromMap)(this._visitCounts,t,null),e.exists?e.result:0}VisitCountForContainer(t){if(t===null)return (0, At.throwNullException)("container");if(!t.visitsShouldBeCounted)return this.story.Error("Read count for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(t,0);if(i.exists)return i.result}let e=t.path.toString(),n=(0, bn.tryGetValueFromMap)(this._visitCounts,e,null);return n.exists?n.result:0}IncrementVisitCountForContainer(t){if(this._patch!==null){let i=this.VisitCountForContainer(t);i++,this._patch.SetVisitCount(t,i);return}let e=t.path.toString(),n=(0, bn.tryGetValueFromMap)(this._visitCounts,e,null);n.exists?this._visitCounts.set(e,n.result+1):this._visitCounts.set(e,1);}RecordTurnIndexVisitToContainer(t){if(this._patch!==null){this._patch.SetTurnIndex(t,this.currentTurnIndex);return}let e=t.path.toString();this._turnIndices.set(e,this.currentTurnIndex);}TurnsSinceForContainer(t){if(t.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(t,0);if(i.exists)return this.currentTurnIndex-i.result}let e=t.path.toString(),n=(0, bn.tryGetValueFromMap)(this._turnIndices,e,0);return n.exists?this.currentTurnIndex-n.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(t){this._variablesState=t;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(t){this._currentTurnIndex=t;}get currentPathString(){let t=this.currentPointer;return t.isNull?null:t.path===null?(0, At.throwNullException)("pointer.path"):t.path.toString()}get previousPathString(){let t=this.previousPointer;return t.isNull?null:t.path===null?(0, At.throwNullException)("previousPointer.path"):t.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(t){this.callStack.currentElement.currentPointer=t.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(t){this.callStack.currentThread.previousPointer=t.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let t=new go.StringBuilder,e=false;for(let n of this.outputStream){let i=(0, X.asOrNull)(n,Z.StringValue);if(!e&&i!==null)t.Append(i.value);else {let o=(0, X.asOrNull)(n,lt.ControlCommand);o!==null&&(o.commandType==lt.ControlCommand.CommandType.BeginTag?e=true:o.commandType==lt.ControlCommand.CommandType.EndTag&&(e=false));}}this._currentText=this.CleanOutputWhitespace(t.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(t){let e=new go.StringBuilder,n=-1,i=0;for(let o=0;o<t.length;o++){let r=t.charAt(o),a=r==" "||r==" ";a&&n==-1&&(n=o),a||(r!=`
21
21
  `&&n>0&&n!=i&&e.Append(" "),n=-1),r==`
22
- `&&(i=o+1),a||e.Append(r);}return e.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let t=false,e=new mo.StringBuilder;for(let n of this.outputStream){let i=(0, z.asOrNull)(n,lt.ControlCommand);if(i!=null){if(i.commandType==lt.ControlCommand.CommandType.BeginTag){if(t&&e.Length>0){let o=this.CleanOutputWhitespace(e.toString());this._currentTags.push(o),e.Clear();}t=true;}else if(i.commandType==lt.ControlCommand.CommandType.EndTag){if(e.Length>0){let o=this.CleanOutputWhitespace(e.toString());this._currentTags.push(o),e.Clear();}t=false;}}else if(t){let o=(0, z.asOrNull)(n,Z.StringValue);o!==null&&e.Append(o.value);}else {let o=(0, z.asOrNull)(n,Bf.Tag);o!=null&&o.text!=null&&o.text.length>0&&this._currentTags.push(o.text);}}if(e.Length>0){let n=this.CleanOutputWhitespace(e.toString());this._currentTags.push(n),e.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let t of this._namedFlows.keys())t!=this.kDefaultFlowName&&this._aliveFlowNames.push(t);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(t){this.callStack.currentElement.inExpressionEvaluation=t;}constructor(t){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=Ve.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=t,this._currentFlow=new Wr.Flow(this.kDefaultFlowName,t),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new Vf.VariablesState(this.callStack,t.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let e=new Date().getTime();this.storySeed=new Lf.PRNG(e).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Ve.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(t){if(t===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),t===this._currentFlow.name)return;let e,n=(0, yn.tryGetValueFromMap)(this._namedFlows,t,null);n.exists?e=n.result:(e=new Wr.Flow(t,this.story),this._namedFlows.set(t,e),this._aliveFlowNamesDirty=true),this._currentFlow=e,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(t){if(t===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(t===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===t&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, At.throwNullException)("this._namedFlows");this._namedFlows.delete(t),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(t){let e=new s(this.story);if(e._patch=new Mf.StatePatch(this._patch),e._currentFlow.name=this._currentFlow.name,e._currentFlow.callStack=new Rf.CallStack(this._currentFlow.callStack),e._currentFlow.outputStream.push(...this._currentFlow.outputStream),e.OutputStreamDirty(),t)for(let n of this._currentFlow.currentChoices)e._currentFlow.currentChoices.push(n.Clone());else e._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){e._namedFlows=new Map;for(let[n,i]of this._namedFlows)e._namedFlows.set(n,i),e._aliveFlowNamesDirty=true;e._namedFlows.set(this._currentFlow.name,e._currentFlow);}return this.hasError&&(e._currentErrors=[],e._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(e._currentWarnings=[],e._currentWarnings.push(...this.currentWarnings||[])),e.variablesState=this.variablesState,e.variablesState.callStack=e.callStack,e.variablesState.patch=e._patch,e.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(e.divertedPointer=this.divertedPointer.copy()),e.previousPointer=this.previousPointer.copy(),e._visitCounts=this._visitCounts,e._turnIndices=this._turnIndices,e.currentTurnIndex=this.currentTurnIndex,e.storySeed=this.storySeed,e.previousRandom=this.previousRandom,e.didSafeExit=this.didSafeExit,e}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[t,e]of this._patch.visitCounts)this.ApplyCountChanges(t,e,true);for(let[t,e]of this._patch.turnIndices)this.ApplyCountChanges(t,e,false);this._patch=null;}}ApplyCountChanges(t,e,n){(n?this._visitCounts:this._turnIndices).set(t.path.toString(),e);}WriteJson(t){if(t.WriteObjectStart(),t.WritePropertyStart("flows"),t.WriteObjectStart(),this._namedFlows!==null)for(let[e,n]of this._namedFlows)t.WriteProperty(e,i=>n.WriteJson(i));else t.WriteProperty(this._currentFlow.name,e=>this._currentFlow.WriteJson(e));if(t.WriteObjectEnd(),t.WritePropertyEnd(),t.WriteProperty("currentFlowName",this._currentFlow.name),t.WriteProperty("variablesState",e=>this.variablesState.WriteJson(e)),t.WriteProperty("evalStack",e=>te.JsonSerialisation.WriteListRuntimeObjs(e,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, At.throwNullException)("divertedPointer");t.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}t.WriteProperty("visitCounts",e=>te.JsonSerialisation.WriteIntDictionary(e,this._visitCounts)),t.WriteProperty("turnIndices",e=>te.JsonSerialisation.WriteIntDictionary(e,this._turnIndices)),t.WriteIntProperty("turnIdx",this.currentTurnIndex),t.WriteIntProperty("storySeed",this.storySeed),t.WriteIntProperty("previousRandom",this.previousRandom),t.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),t.WriteIntProperty("inkFormatVersion",jf.Story.inkVersionCurrent),t.WriteObjectEnd();}LoadJsonObj(t){let e=t,n=e.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+n+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let i=e.flows;if(i!=null){let r=i;Object.keys(r).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let a=Object.entries(r);for(let[u,l]of a){let h=u,c=l,d=new Wr.Flow(h,this.story,c);if(Object.keys(r).length===1)this._currentFlow=new Wr.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, At.throwNullException)("this._namedFlows");this._namedFlows.set(h,d);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let u=e.currentFlowName;this._currentFlow=this._namedFlows.get(u);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(e.callstackThreads,this.story),this._currentFlow.outputStream=te.JsonSerialisation.JArrayToRuntimeObjList(e.outputStream),this._currentFlow.currentChoices=te.JsonSerialisation.JArrayToRuntimeObjList(e.currentChoices);let r=e.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(r,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(e.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=te.JsonSerialisation.JArrayToRuntimeObjList(e.evalStack);let o=e.currentDivertTarget;if(o!=null){let r=new dl.Path(o.toString());this.divertedPointer=this.story.PointerAtPath(r);}this._visitCounts=te.JsonSerialisation.JObjectToIntDictionary(e.visitCounts),this._turnIndices=te.JsonSerialisation.JObjectToIntDictionary(e.turnIndices),this.currentTurnIndex=parseInt(e.turnIdx),this.storySeed=parseInt(e.storySeed),this.previousRandom=parseInt(e.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(t=null){this.outputStream.length=0,t!==null&&this.outputStream.push(...t),this.OutputStreamDirty();}PushToOutputStream(t){let e=(0, z.asOrNull)(t,Z.StringValue);if(e!==null){let n=this.TrySplittingHeadTailWhitespace(e);if(n!==null){for(let i of n)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(t),this.OutputStreamDirty();}PopFromOutputStream(t){this.outputStream.splice(this.outputStream.length-t,t),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(t){let e=t.value;if(e===null)return (0, At.throwNullException)("single.value");let n=-1,i=-1;for(let h=0;h<e.length;h++){let c=e[h];if(c==`
22
+ `&&(i=o+1),a||e.Append(r);}return e.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let t=false,e=new go.StringBuilder;for(let n of this.outputStream){let i=(0, X.asOrNull)(n,lt.ControlCommand);if(i!=null){if(i.commandType==lt.ControlCommand.CommandType.BeginTag){if(t&&e.Length>0){let o=this.CleanOutputWhitespace(e.toString());this._currentTags.push(o),e.Clear();}t=true;}else if(i.commandType==lt.ControlCommand.CommandType.EndTag){if(e.Length>0){let o=this.CleanOutputWhitespace(e.toString());this._currentTags.push(o),e.Clear();}t=false;}}else if(t){let o=(0, X.asOrNull)(n,Z.StringValue);o!==null&&e.Append(o.value);}else {let o=(0, X.asOrNull)(n,Lf.Tag);o!=null&&o.text!=null&&o.text.length>0&&this._currentTags.push(o.text);}}if(e.Length>0){let n=this.CleanOutputWhitespace(e.toString());this._currentTags.push(n),e.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let t of this._namedFlows.keys())t!=this.kDefaultFlowName&&this._aliveFlowNames.push(t);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(t){this.callStack.currentElement.inExpressionEvaluation=t;}constructor(t){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=Ve.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=t,this._currentFlow=new qr.Flow(this.kDefaultFlowName,t),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new Bf.VariablesState(this.callStack,t.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let e=new Date().getTime();this.storySeed=new Wf.PRNG(e).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Ve.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(t){if(t===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),t===this._currentFlow.name)return;let e,n=(0, bn.tryGetValueFromMap)(this._namedFlows,t,null);n.exists?e=n.result:(e=new qr.Flow(t,this.story),this._namedFlows.set(t,e),this._aliveFlowNamesDirty=true),this._currentFlow=e,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(t){if(t===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(t===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===t&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, At.throwNullException)("this._namedFlows");this._namedFlows.delete(t),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(t){let e=new s(this.story);if(e._patch=new Gf.StatePatch(this._patch),e._currentFlow.name=this._currentFlow.name,e._currentFlow.callStack=new Vf.CallStack(this._currentFlow.callStack),e._currentFlow.outputStream.push(...this._currentFlow.outputStream),e.OutputStreamDirty(),t)for(let n of this._currentFlow.currentChoices)e._currentFlow.currentChoices.push(n.Clone());else e._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){e._namedFlows=new Map;for(let[n,i]of this._namedFlows)e._namedFlows.set(n,i),e._aliveFlowNamesDirty=true;e._namedFlows.set(this._currentFlow.name,e._currentFlow);}return this.hasError&&(e._currentErrors=[],e._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(e._currentWarnings=[],e._currentWarnings.push(...this.currentWarnings||[])),e.variablesState=this.variablesState,e.variablesState.callStack=e.callStack,e.variablesState.patch=e._patch,e.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(e.divertedPointer=this.divertedPointer.copy()),e.previousPointer=this.previousPointer.copy(),e._visitCounts=this._visitCounts,e._turnIndices=this._turnIndices,e.currentTurnIndex=this.currentTurnIndex,e.storySeed=this.storySeed,e.previousRandom=this.previousRandom,e.didSafeExit=this.didSafeExit,e}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[t,e]of this._patch.visitCounts)this.ApplyCountChanges(t,e,true);for(let[t,e]of this._patch.turnIndices)this.ApplyCountChanges(t,e,false);this._patch=null;}}ApplyCountChanges(t,e,n){(n?this._visitCounts:this._turnIndices).set(t.path.toString(),e);}WriteJson(t){if(t.WriteObjectStart(),t.WritePropertyStart("flows"),t.WriteObjectStart(),this._namedFlows!==null)for(let[e,n]of this._namedFlows)t.WriteProperty(e,i=>n.WriteJson(i));else t.WriteProperty(this._currentFlow.name,e=>this._currentFlow.WriteJson(e));if(t.WriteObjectEnd(),t.WritePropertyEnd(),t.WriteProperty("currentFlowName",this._currentFlow.name),t.WriteProperty("variablesState",e=>this.variablesState.WriteJson(e)),t.WriteProperty("evalStack",e=>te.JsonSerialisation.WriteListRuntimeObjs(e,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, At.throwNullException)("divertedPointer");t.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}t.WriteProperty("visitCounts",e=>te.JsonSerialisation.WriteIntDictionary(e,this._visitCounts)),t.WriteProperty("turnIndices",e=>te.JsonSerialisation.WriteIntDictionary(e,this._turnIndices)),t.WriteIntProperty("turnIdx",this.currentTurnIndex),t.WriteIntProperty("storySeed",this.storySeed),t.WriteIntProperty("previousRandom",this.previousRandom),t.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),t.WriteIntProperty("inkFormatVersion",Mf.Story.inkVersionCurrent),t.WriteObjectEnd();}LoadJsonObj(t){let e=t,n=e.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+n+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let i=e.flows;if(i!=null){let r=i;Object.keys(r).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let a=Object.entries(r);for(let[u,l]of a){let h=u,c=l,m=new qr.Flow(h,this.story,c);if(Object.keys(r).length===1)this._currentFlow=new qr.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, At.throwNullException)("this._namedFlows");this._namedFlows.set(h,m);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let u=e.currentFlowName;this._currentFlow=this._namedFlows.get(u);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(e.callstackThreads,this.story),this._currentFlow.outputStream=te.JsonSerialisation.JArrayToRuntimeObjList(e.outputStream),this._currentFlow.currentChoices=te.JsonSerialisation.JArrayToRuntimeObjList(e.currentChoices);let r=e.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(r,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(e.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=te.JsonSerialisation.JArrayToRuntimeObjList(e.evalStack);let o=e.currentDivertTarget;if(o!=null){let r=new dl.Path(o.toString());this.divertedPointer=this.story.PointerAtPath(r);}this._visitCounts=te.JsonSerialisation.JObjectToIntDictionary(e.visitCounts),this._turnIndices=te.JsonSerialisation.JObjectToIntDictionary(e.turnIndices),this.currentTurnIndex=parseInt(e.turnIdx),this.storySeed=parseInt(e.storySeed),this.previousRandom=parseInt(e.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(t=null){this.outputStream.length=0,t!==null&&this.outputStream.push(...t),this.OutputStreamDirty();}PushToOutputStream(t){let e=(0, X.asOrNull)(t,Z.StringValue);if(e!==null){let n=this.TrySplittingHeadTailWhitespace(e);if(n!==null){for(let i of n)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(t),this.OutputStreamDirty();}PopFromOutputStream(t){this.outputStream.splice(this.outputStream.length-t,t),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(t){let e=t.value;if(e===null)return (0, At.throwNullException)("single.value");let n=-1,i=-1;for(let h=0;h<e.length;h++){let c=e[h];if(c==`
23
23
  `)n==-1&&(n=h),i=h;else {if(c==" "||c==" ")continue;break}}let o=-1,r=-1;for(let h=e.length-1;h>=0;h--){let c=e[h];if(c==`
24
24
  `)o==-1&&(o=h),r=h;else {if(c==" "||c==" ")continue;break}}if(n==-1&&o==-1)return null;let a=[],u=0,l=e.length;if(n!=-1){if(n>0){let h=new Z.StringValue(e.substring(0,n));a.push(h);}a.push(new Z.StringValue(`
25
25
  `)),u=i+1;}if(o!=-1&&(l=r),l>u){let h=e.substring(u,l);a.push(new Z.StringValue(h));}if(o!=-1&&r>i&&(a.push(new Z.StringValue(`
26
- `)),o<e.length-1)){let h=e.length-o-1,c=new Z.StringValue(e.substring(o+1,o+1+h));a.push(c);}return a}PushToOutputStreamIndividual(t){let e=(0, z.asOrNull)(t,po.Glue),n=(0, z.asOrNull)(t,Z.StringValue),i=true;if(e)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let o=-1,r=this.callStack.currentElement;r.type==Zt.PushPopType.Function&&(o=r.functionStartInOutputStream);let a=-1;for(let l=this.outputStream.length-1;l>=0;l--){let h=this.outputStream[l],c=h instanceof lt.ControlCommand?h:null;if((h instanceof po.Glue?h:null)!=null){a=l;break}else if(c!=null&&c.commandType==lt.ControlCommand.CommandType.BeginString){l>=o&&(o=-1);break}}let u=-1;if(a!=-1&&o!=-1?u=Math.min(o,a):a!=-1?u=a:u=o,u!=-1){if(n.isNewline)i=false;else if(n.isNonWhitespace&&(a>-1&&this.RemoveExistingGlue(),o>-1)){let l=this.callStack.elements;for(let h=l.length-1;h>=0;h--){let c=l[h];if(c.type==Zt.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(t===null)return (0, At.throwNullException)("obj");this.outputStream.push(t),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let t=-1,e=this.outputStream.length-1;for(;e>=0;){let n=this.outputStream[e],i=(0, z.asOrNull)(n,lt.ControlCommand),o=(0, z.asOrNull)(n,Z.StringValue);if(i!=null||o!=null&&o.isNonWhitespace)break;o!=null&&o.isNewline&&(t=e),e--;}if(t>=0)for(e=t;e<this.outputStream.length;)(0, z.asOrNull)(this.outputStream[e],Z.StringValue)?this.outputStream.splice(e,1):e++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let t=this.outputStream.length-1;t>=0;t--){let e=this.outputStream[t];if(e instanceof po.Glue)this.outputStream.splice(t,1);else if(e instanceof lt.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let t=this.outputStream.length-1;t>=0&&!(this.outputStream[t]instanceof lt.ControlCommand);t--){let n=this.outputStream[t];if(n instanceof Z.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let t of this.outputStream)if(t instanceof Z.StringValue)return true;return false}get inStringEvaluation(){for(let t=this.outputStream.length-1;t>=0;t--){let e=(0, z.asOrNull)(this.outputStream[t],lt.ControlCommand);if(e instanceof lt.ControlCommand&&e.commandType==lt.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(t){let e=(0, z.asOrNull)(t,Z.ListValue);if(e){let n=e.value;if(n===null)return (0, At.throwNullException)("rawList");if(n.originNames!=null){n.origins||(n.origins=[]),n.origins.length=0;for(let i of n.originNames){if(this.story.listDefinitions===null)return (0, At.throwNullException)("StoryState.story.listDefinitions");let o=this.story.listDefinitions.TryListGetDefinition(i,null);if(o.result===null)return (0, At.throwNullException)("StoryState def.result");n.origins.indexOf(o.result)<0&&n.origins.push(o.result);}}}if(t===null)return (0, At.throwNullException)("obj");this.evaluationStack.push(t);}PopEvaluationStack(t){if(typeof t>"u"){let e=this.evaluationStack.pop();return (0, z.nullIfUndefined)(e)}else {if(t>this.evaluationStack.length)throw new Error("trying to pop too many objects");let e=this.evaluationStack.splice(this.evaluationStack.length-t,t);return (0, z.nullIfUndefined)(e)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Ve.Pointer.Null,this.previousPointer=Ve.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){qf.Debug.Assert(this.callStack.currentElement.type==Zt.PushPopType.Function);let t=this.callStack.currentElement.functionStartInOutputStream;t==-1&&(t=0);for(let e=this.outputStream.length-1;e>=t;e--){let n=this.outputStream[e],i=(0, z.asOrNull)(n,Z.StringValue),o=(0, z.asOrNull)(n,lt.ControlCommand);if(i!=null){if(o)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(e,1),this.OutputStreamDirty();else break}}}PopCallStack(t=null){this.callStack.currentElement.type==Zt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(t);}SetChosenPath(t,e){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(t);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,e&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(t,e){this.callStack.Push(Zt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Ve.Pointer.StartOf(t),this.PassArgumentsToEvaluationStack(e);}PassArgumentsToEvaluationStack(t){if(t!==null)for(let e=0;e<t.length;e++){if(!(typeof t[e]=="number"||typeof t[e]=="string"||typeof t[e]=="boolean"||t[e]instanceof Gf.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, z.nullIfUndefined)(t[e])===null?"null":t[e].constructor.name));this.PushEvaluationStack(Z.Value.Create(t[e]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Zt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Ve.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Zt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let t=this.callStack.currentElement.evaluationStackHeightWhenPushed,e=null;for(;this.evaluationStack.length>t;){let n=this.PopEvaluationStack();e===null&&(e=n);}if(this.PopCallStack(Zt.PushPopType.FunctionEvaluationFromGame),e){if(e instanceof Wf.Void)return null;let n=(0, z.asOrThrows)(e,Z.Value);return n.valueType==Z.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(t,e){e?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(t)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(t));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};qr.StoryState=go;});var ml=C(jr=>{Object.defineProperty(jr,"__esModule",{value:true});jr.Stopwatch=void 0;var Co=class{constructor(){this.startTime=void 0;}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime();}Stop(){this.startTime=void 0;}};jr.Stopwatch=Co;});var Cl=C(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.ErrorType=void 0;var gl;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(gl||(Mr.ErrorType=gl={}));});var vn=C(me=>{Object.defineProperty(me,"__esModule",{value:true});me.Story=me.InkList=void 0;var at=K(),vo=dt(),Do=Re(),$f=pl(),P=rt(),_t=ue(),Hf=li(),Uf=to(),vl=kt(),F=$(),Eo=ct(),bn=oe(),Gr=Fr(),Kf=zt(),Jf=Ne(),zf=It(),fe=Je(),So=lo(),pe=se(),Xf=no(),Yf=ml(),ee=an(),An=pt(),T=L(),B=it(),Dl=co(),El=Cl(),Qf=pt();Object.defineProperty(me,"InkList",{enumerable:true,get:function(){return Qf.InkList}});Number.isInteger||(Number.isInteger=function(t){return typeof t=="number"&&isFinite(t)&&t>-9007199254740992&&t<9007199254740992&&Math.floor(t)===t});var Be=class s extends vo.InkObject{get currentChoices(){let t=[];if(this._state===null)return (0, B.throwNullException)("this._state");for(let e of this._state.currentChoices)e.isInvisibleDefault||(e.index=t.length,t.push(e));return t}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=false,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=false,this._temporaryEvaluationContainer=null,this._asyncContinueActive=false,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount=0,this._asyncSaving=false,this._profiler=null;let t,e=null,n=null;if(arguments[0]instanceof at.Container)t=arguments[0],typeof arguments[1]<"u"&&(e=arguments[1]),this._mainContentContainer=t;else if(typeof arguments[0]=="string"){let i=arguments[0];n=Dl.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(e!=null&&(this._listDefinitions=new Xf.ListDefinitionsOrigin(e)),this._externals=new Map,n!==null){let i=n,o=i.inkVersion;if(o==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let r=parseInt(o);if(r>s.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!=s.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${s.inkVersionCurrent} used to build story doesn't match current version of engine (${r}). Non-critical, but recommend synchronising.`);let a=i.root;if(a==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let u;(u=i.listDefs)&&(this._listDefinitions=Do.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, T.asOrThrows)(Do.JsonSerialisation.JTokenToRuntimeObject(a),at.Container),this.ResetState();}}ToJson(t){let e=false;if(t||(e=true,t=new Dl.SimpleJson.Writer),t.WriteObjectStart(),t.WriteIntProperty("inkVersion",s.inkVersionCurrent),t.WriteProperty("root",n=>Do.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){t.WritePropertyStart("listDefs"),t.WriteObjectStart();for(let n of this._listDefinitions.lists){t.WritePropertyStart(n.name),t.WriteObjectStart();for(let[i,o]of n.items){let r=An.InkListItem.fromSerializedKey(i),a=o;t.WriteIntProperty(r.itemName,a);}t.WriteObjectEnd(),t.WritePropertyEnd();}t.WriteObjectEnd(),t.WritePropertyEnd();}if(t.WriteObjectEnd(),e)return t.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new $f.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, B.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, B.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let t=this.state.currentPointer.copy();this.ChoosePath(new Eo.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=t;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(t){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+t);this.state.SwitchFlow_Internal(t);}RemoveFlow(t){this.state.RemoveFlow_Internal(t);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(t){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(t);}ContinueInternal(t=0){this._profiler!=null&&this._profiler.PreContinue();let e=t>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!e&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=e,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=false,this._state.ResetOutput(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation();}let n=new Yf.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(r){if(!(r instanceof fe.StoryException))throw r;this.AddError(r.message,void 0,r.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>t)break}while(this.canContinue);n.Stop();let o=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(_t.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(_t.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(o=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let r of this.state.currentErrors)this.onError(r,El.ErrorType.Error);if(this.state.hasWarning)for(let r of this.state.currentWarnings)this.onError(r,El.ErrorType.Warning);this.ResetErrors();}else {let r=new pe.StringBuilder;throw r.Append("Ink had "),this.state.hasError&&(r.Append(`${this.state.currentErrors.length}`),r.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&r.Append(" and ")),this.state.hasWarning&&(r.Append(`${this.state.currentWarnings.length}`),r.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&r.Append(" and ")),r.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),r.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new fe.StoryException(r.toString())}o!=null&&Object.keys(o).length>0&&this._state.variablesState.NotifyObservers(o);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, B.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, B.throwNullException)("this.state.currentTags");let t=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(t==s.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;t==s.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(t,e,n,i){if(t===null)return (0, B.throwNullException)("prevText");if(e===null)return (0, B.throwNullException)("currText");let o=e.length>=t.length&&t.length>0&&e.charAt(t.length-1)==`
27
- `;if(n==i&&t.length==e.length&&o)return s.OutputStateChange.NoChange;if(!o)return s.OutputStateChange.NewlineRemoved;if(i>n)return s.OutputStateChange.ExtendedBeyondNewline;for(let r=t.length;r<e.length;r++){let a=e.charAt(r);if(a!=" "&&a!=" ")return s.OutputStateChange.ExtendedBeyondNewline}return s.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let t=new pe.StringBuilder;for(;this.canContinue;)t.Append(this.Continue());return t.toString()}ContentAtPath(t){return this.mainContentContainer.ContentAtPath(t)}KnotContainerWithName(t){let e=this.mainContentContainer.namedContent.get(t);return e instanceof at.Container?e:null}PointerAtPath(t){if(t.length==0)return ee.Pointer.Null;let e=new ee.Pointer,n=t.length,i=null;return t.lastComponent===null?(0, B.throwNullException)("path.lastComponent"):(t.lastComponent.isIndex?(n=t.length-1,i=this.mainContentContainer.ContentAtPath(t,void 0,n),e.container=i.container,e.index=t.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(t),e.container=i.container,e.index=-1),i.obj==null||i.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+t+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+t+"', so it was approximated to: '"+i.obj.path+"'."),e)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, B.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let t=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,t}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let t=true,e=this.state.currentPointer.copy();if(e.isNull)return;let n=(0, T.asOrNull)(e.Resolve(),at.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)e=ee.Pointer.StartOf(n),n=(0, T.asOrNull)(e.Resolve(),at.Container);this.state.currentPointer=e.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=e.Resolve(),o=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;o&&(t=false);let r=(0, T.asOrNull)(i,Hf.ChoicePoint);if(r){let u=this.ProcessChoice(r);u&&this.state.generatedChoices.push(u),i=null,t=false;}if(i instanceof at.Container&&(t=false),t){let u=(0, T.asOrNull)(i,F.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new F.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let a=(0, T.asOrNull)(i,P.ControlCommand);a&&a.commandType==P.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(t,e){(!t.countingAtStartOnly||e)&&(t.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(t),t.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(t));}VisitChangedContainersDueToDivert(){let t=this.state.previousPointer.copy(),e=this.state.currentPointer.copy();if(e.isNull||e.index==-1)return;if(this._prevContainers.length=0,!t.isNull){let r=t.Resolve(),a=(0, T.asOrNull)(r,at.Container)||(0, T.asOrNull)(t.container,at.Container);for(;a;)this._prevContainers.push(a),a=(0, T.asOrNull)(a.parent,at.Container);}let n=e.Resolve();if(n==null)return;let i=(0, T.asOrNull)(n.parent,at.Container),o=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let r=i.content.length>0&&n==i.content[0]&&o;r||(o=false),this.VisitContainer(i,r),n=i,i=(0, T.asOrNull)(i.parent,at.Container);}}PopChoiceStringAndTags(t){let e=(0, T.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);for(;this.state.evaluationStack.length>0&&(0, T.asOrNull)(this.state.PeekEvaluationStack(),Gr.Tag)!=null;){let n=(0, T.asOrNull)(this.state.PopEvaluationStack(),Gr.Tag);n&&t.push(n.text);}return e.value}ProcessChoice(t){let e=true;if(t.hasCondition){let a=this.state.PopEvaluationStack();this.IsTruthy(a)||(e=false);}let n="",i="",o=[];if(t.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(o)||""),t.hasStartContent&&(n=this.PopChoiceStringAndTags(o)||""),t.onceOnly&&this.state.VisitCountForContainer(t.choiceTarget)>0&&(e=false),!e)return null;let r=new Uf.Choice;return r.targetPath=t.pathOnChoice,r.sourcePath=t.path.toString(),r.isInvisibleDefault=t.isInvisibleDefault,r.threadAtGeneration=this.state.callStack.ForkThread(),r.tags=o.reverse(),r.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),r}IsTruthy(t){let e=false;if(t instanceof F.Value){let n=t;if(n instanceof F.DivertTargetValue){let i=n;return this.Error("Shouldn't use a divert target (to "+i.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return e}PerformLogicAndFlowControl(t){if(t==null)return false;if(t instanceof vl.Divert){let e=t;if(e.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(e.hasVariableTarget){let n=e.variableDivertName,i=this.state.variablesState.GetVariableWithName(n);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(i instanceof F.DivertTargetValue)){let r=(0, T.asOrNull)(i,F.IntValue),a="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";r instanceof F.IntValue&&r.value==0?a+="was empty/null (the value 0).":a+="contained '"+i+"'.",this.Error(a);}let o=(0, T.asOrThrows)(i,F.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(o.targetPath);}else {if(e.isExternal)return this.CallExternalFunction(e.targetPathString,e.externalArgs),true;this.state.divertedPointer=e.targetPointer.copy();}return e.pushesToStack&&this.state.callStack.Push(e.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!e.isExternal&&(e&&e.debugMetadata&&e.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+e.debugMetadata.sourceName):this.Error("Divert resolution failed: "+e)),true}else if(t instanceof P.ControlCommand){let e=t;switch(e.commandType){case P.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case P.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case P.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let p=this.state.PopEvaluationStack();if(!(p instanceof bn.Void)){let E=new F.StringValue(p.toString());this.state.PushToOutputStream(E);}}break;case P.ControlCommand.CommandType.NoOp:break;case P.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case P.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case P.ControlCommand.CommandType.PopFunction:case P.ControlCommand.CommandType.PopTunnel:let n=e.commandType==P.ControlCommand.CommandType.PopFunction?_t.PushPopType.Function:_t.PushPopType.Tunnel,i=null;if(n==_t.PushPopType.Tunnel){let p=this.state.PopEvaluationStack();i=(0, T.asOrNull)(p,F.DivertTargetValue),i===null&&this.Assert(p instanceof bn.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let p=new Map;p.set(_t.PushPopType.Function,"function return statement (~ return)"),p.set(_t.PushPopType.Tunnel,"tunnel onwards statement (->->)");let E=p.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(E="end of flow (-> END or choice)");let _="Found "+p.get(n)+", when expected "+E;this.Error(_);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case P.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(e),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case P.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(e);break;case P.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let p=[],E=0;for(let R=this.state.outputStream.length-1;R>=0;--R){let X=this.state.outputStream[R];E++;let vt=(0, T.asOrNull)(X,P.ControlCommand);if(vt!=null){if(vt.commandType==P.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}X instanceof F.StringValue&&p.push(X);}this.state.PopFromOutputStream(E);let _=new pe.StringBuilder;for(let R of p.reverse())_.Append(R.toString());let x=new Gr.Tag(this.state.CleanOutputWhitespace(_.toString()));this.state.PushEvaluationStack(x);}else this.state.PushToOutputStream(e);break}case P.ControlCommand.CommandType.EndString:{let p=[],E=[],_=0;for(let R=this.state.outputStream.length-1;R>=0;--R){let X=this.state.outputStream[R];_++;let vt=(0, T.asOrNull)(X,P.ControlCommand);if(vt&&vt.commandType==P.ControlCommand.CommandType.BeginString)break;X instanceof Gr.Tag&&E.push(X),X instanceof F.StringValue&&p.push(X);}this.state.PopFromOutputStream(_);for(let R of E)this.state.PushToOutputStream(R);p=p.reverse();let x=new pe.StringBuilder;for(let R of p)x.Append(R.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new F.StringValue(x.toString()));break}case P.ControlCommand.CommandType.ChoiceCount:let o=this.state.generatedChoices.length;this.state.PushEvaluationStack(new F.IntValue(o));break;case P.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new F.IntValue(this.state.currentTurnIndex+1));break;case P.ControlCommand.CommandType.TurnsSince:case P.ControlCommand.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof F.DivertTargetValue)){let p="";r instanceof F.IntValue&&(p=". 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+p);break}let a=(0, T.asOrThrows)(r,F.DivertTargetValue),u=(0, T.asOrNull)(this.ContentAtPath(a.targetPath).correctObj,at.Container),l;u!=null?e.commandType==P.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(e.commandType==P.ControlCommand.CommandType.TurnsSince?l=-1:l=0,this.Warning("Failed to find container for "+e.toString()+" lookup at "+a.targetPath.toString())),this.state.PushEvaluationStack(new F.IntValue(l));break;case P.ControlCommand.CommandType.Random:{let p=(0, T.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),E=(0, T.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(E==null||!(E instanceof F.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(p==null||!(p instanceof F.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(p.value===null)return (0, B.throwNullException)("maxInt.value");if(E.value===null)return (0, B.throwNullException)("minInt.value");let _=p.value-E.value+1;(!isFinite(_)||_>Number.MAX_SAFE_INTEGER)&&(_=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),_<=0&&this.Error("RANDOM was called with minimum as "+E.value+" and maximum as "+p.value+". The maximum must be larger");let x=this.state.storySeed+this.state.previousRandom,X=new So.PRNG(x).next(),vt=X%_+E.value;this.state.PushEvaluationStack(new F.IntValue(vt)),this.state.previousRandom=X;break}case P.ControlCommand.CommandType.SeedRandom:let h=(0, T.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(h==null||!(h instanceof F.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, B.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new bn.Void);break;case P.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new F.IntValue(c));break;case P.ControlCommand.CommandType.SequenceShuffleIndex:let d=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new F.IntValue(d));break;case P.ControlCommand.CommandType.StartThread:break;case P.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=ee.Pointer.Null);break;case P.ControlCommand.CommandType.End:this.state.ForceEnd();break;case P.ControlCommand.CommandType.ListFromInt:let m=(0, T.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),D=(0, T.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);if(m===null)throw new fe.StoryException("Passed non-integer when creating a list element from a numerical value.");let v=null;if(this.listDefinitions===null)return (0, B.throwNullException)("this.listDefinitions");let A=this.listDefinitions.TryListGetDefinition(D.value,null);if(A.exists){if(m.value===null)return (0, B.throwNullException)("minInt.value");let p=A.result.TryGetItemWithValue(m.value,An.InkListItem.Null);p.exists&&(v=new F.ListValue(p.result,m.value));}else throw new fe.StoryException("Failed to find LIST called "+D.value);v==null&&(v=new F.ListValue),this.state.PushEvaluationStack(v);break;case P.ControlCommand.CommandType.ListRange:let S=(0, T.asOrNull)(this.state.PopEvaluationStack(),F.Value),k=(0, T.asOrNull)(this.state.PopEvaluationStack(),F.Value),f=(0, T.asOrNull)(this.state.PopEvaluationStack(),F.ListValue);if(f===null||k===null||S===null)throw new fe.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(f.value===null)return (0, B.throwNullException)("targetList.value");let y=f.value.ListWithSubRange(k.valueObject,S.valueObject);this.state.PushEvaluationStack(new F.ListValue(y));break;case P.ControlCommand.CommandType.ListRandom:{let p=this.state.PopEvaluationStack();if(p===null)throw new fe.StoryException("Expected list for LIST_RANDOM");let E=p.value,_=null;if(E===null)throw (0, B.throwNullException)("list");if(E.Count==0)_=new An.InkList;else {let x=this.state.storySeed+this.state.previousRandom,X=new So.PRNG(x).next(),vt=X%E.Count,Io=E.entries();for(let Ro=0;Ro<=vt-1;Ro++)Io.next();let ko=Io.next().value,Tn={Key:An.InkListItem.fromSerializedKey(ko[0]),Value:ko[1]};if(Tn.Key.originName===null)return (0, B.throwNullException)("randomItem.Key.originName");_=new An.InkList(Tn.Key.originName,this),_.Add(Tn.Key,Tn.Value),this.state.previousRandom=X;}this.state.PushEvaluationStack(new F.ListValue(_));break}default:this.Error("unhandled ControlCommand: "+e);break}return true}else if(t instanceof Kf.VariableAssignment){let e=t,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(e,n),true}else if(t instanceof Jf.VariableReference){let e=t,n=null;if(e.pathForCount!=null){let i=e.containerForCount,o=this.state.VisitCountForContainer(i);n=new F.IntValue(o);}else n=this.state.variablesState.GetVariableWithName(e.name),n==null&&(this.Warning("Variable not found: '"+e.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),n=new F.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(t instanceof zf.NativeFunctionCall){let e=t,n=this.state.PopEvaluationStack(e.numberOfParameters),i=e.Call(n);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(t,e=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(t,n),e)this.ResetCallstack();else if(this.state.callStack.currentElement.type==_t.PushPopType.Function){let i="",o=this.state.callStack.currentElement.currentPointer.container;throw o!=null&&(i="("+o.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+t+`) - this is almost certainly not not what you want! Full stack trace:
28
- `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new Eo.Path(t));}IfAsyncWeCant(t){if(this._asyncContinueActive)throw new Error("Can't "+t+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(t,e=true){this.state.SetChosenPath(t,e),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(t){t=t;let e=this.currentChoices;this.Assert(t>=0&&t<e.length,"choice out of range");let n=e[t];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, B.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, B.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(t){try{return this.KnotContainerWithName(t)!=null}catch{return false}}EvaluateFunction(t,e=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(t,e),this.IfAsyncWeCant("evaluate a function"),t==null)throw new Error("Function is null");if(t==""||t.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(t);if(i==null)throw new Error("Function doesn't exist: '"+t+"'");let o=[];o.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,e);let r=new pe.StringBuilder;for(;this.canContinue;)r.Append(this.Continue());let a=r.toString();this._state.ResetOutput(o);let u=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(t,e,a,u),n?{returned:u,output:a}:u}EvaluateExpression(t){let e=this.state.callStack.elements.length;this.state.callStack.Push(_t.PushPopType.Tunnel),this._temporaryEvaluationContainer=t,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>e&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(t,e){if(t===null)return (0, B.throwNullException)("funcName");let n=this._externals.get(t),i=null,o=typeof n<"u";if(o&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+t+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+t+"()"),o&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!o)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(t),this.Assert(i!==null,"Trying to call EXTERNAL function '"+t+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(_t.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=ee.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+t+"' which has not been bound (and ink fallbacks disabled).");let r=[];for(let l=0;l<e;++l){let c=(0, T.asOrThrows)(this.state.PopEvaluationStack(),F.Value).valueObject;r.push(c);}r.reverse();let a=n.function(r),u=null;a!=null?(u=F.Value.Create(a),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof a)):u=new bn.Void,this.state.PushEvaluationStack(u);}BindExternalFunctionGeneral(t,e,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(t),"Function '"+t+"' has already been bound."),this._externals.set(t,{function:e,lookAheadSafe:n});}TryCoerce(t){return t}BindExternalFunction(t,e,n=false){this.Assert(e!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(t,i=>{this.Assert(i.length>=e.length,"External function expected "+e.length+" arguments");let o=[];for(let r=0,a=i.length;r<a;r++)o[r]=this.TryCoerce(i[r]);return e.apply(null,o)},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 at.Container&&(t=arguments[0]),arguments[0]instanceof vo.InkObject&&(e=arguments[0]),t===null&&e===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=n.size>1?"s":"",i+=": '",i+=Array.from(n).join("', '"),i+="' ",i+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(i);}else if(t!=null){for(let i of t.content){let o=i;(o==null||!o.hasValidName)&&this.ValidateExternalBindings(i,n);}for(let[,i]of t.namedContent)this.ValidateExternalBindings((0, T.asOrNull)(i,vo.InkObject),n);}else if(e!=null){let i=(0, T.asOrNull)(e,vl.Divert);if(i&&i.isExternal){let o=i.targetPathString;if(o===null)return (0, B.throwNullException)("name");this._externals.has(o)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(o)||n.add(o);}}}ObserveVariable(t,e){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(t))throw new Error("Cannot observe variable '"+t+"' because it wasn't declared in the ink story.");this._variableObservers.has(t)?this._variableObservers.get(t).push(e):this._variableObservers.set(t,[e]);}ObserveVariables(t,e){for(let n=0,i=t.length;n<i;n++)this.ObserveVariable(t[n],e[n]);}RemoveVariableObserver(t,e){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(e!=null){if(this._variableObservers.has(e))if(t!=null){let n=this._variableObservers.get(e);n!=null&&(n.splice(n.indexOf(t),1),n.length===0&&this._variableObservers.delete(e));}else this._variableObservers.delete(e);}else if(t!=null){let n=this._variableObservers.keys();for(let i of n){let o=this._variableObservers.get(i);o!=null&&(o.splice(o.indexOf(t),1),o.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(t,e){if(this._variableObservers===null)return;let n=this._variableObservers.get(t);if(typeof n<"u"){if(!(e instanceof F.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, T.asOrThrows)(e,F.Value);for(let o of n)o(t,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(t){return this.TagsAtStartOfFlowContainerWithPathString(t)}TagsAtStartOfFlowContainerWithPathString(t){let e=new Eo.Path(t),n=this.ContentAtPath(e).container;if(n===null)return (0, B.throwNullException)("flowContainer");for(;;){let r=n.content[0];if(r instanceof at.Container)n=r;else break}let i=false,o=null;for(let r of n.content){let a=(0, T.asOrNull)(r,P.ControlCommand);if(a!=null)a.commandType==P.ControlCommand.CommandType.BeginTag?i=true:a.commandType==P.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, T.asOrNull)(r,F.StringValue);u!==null?(o===null&&(o=[]),u.value!==null&&o.push(u.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return o}BuildStringOfHierarchy(){let t=new pe.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}BuildStringOfContainer(t){let e=new pe.StringBuilder;return t.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=ee.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let e=false;this.state.callStack.CanPop(_t.PushPopType.Function)?(this.state.PopCallStack(_t.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new bn.Void),e=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),e=true):this.state.TryExitFunctionEvaluationFromGame(),e&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let t=true,e=this.state.callStack.currentElement.currentPointer.copy();if(e.index++,e.container===null)return (0, B.throwNullException)("pointer.container");for(;e.index>=e.container.content.length;){t=false;let n=(0, T.asOrNull)(e.container.parent,at.Container);if(!(n instanceof at.Container))break;let i=n.content.indexOf(e.container);if(i==-1)break;if(e=new ee.Pointer(n,i),e.index++,t=true,e.container===null)return (0, B.throwNullException)("pointer.container")}return t||(e=ee.Pointer.Null),this.state.callStack.currentElement.currentPointer=e.copy(),t}TryFollowDefaultInvisibleChoice(){let t=this._state.currentChoices,e=t.filter(i=>i.isInvisibleDefault);if(e.length==0||t.length>e.length)return false;let n=e[0];return n.targetPath===null?(0, B.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, B.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,false),true)}NextSequenceShuffleIndex(){let t=(0, T.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(!(t instanceof F.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let e=this.state.currentPointer.container;if(e===null)return (0, B.throwNullException)("seqContainer");if(t.value===null)return (0, B.throwNullException)("numElementsIntVal.value");let n=t.value,o=(0, T.asOrThrows)(this.state.PopEvaluationStack(),F.IntValue).value;if(o===null)return (0, B.throwNullException)("seqCount");let r=o/n,a=o%n,u=e.path.toString(),l=0;for(let m=0,D=u.length;m<D;m++)l+=u.charCodeAt(m)||0;let h=l+r+this.state.storySeed,c=new So.PRNG(Math.floor(h)),d=[];for(let m=0;m<n;++m)d.push(m);for(let m=0;m<=a;++m){let D=c.next()%d.length,v=d[D];if(d.splice(D,1),m==a)return v}throw new Error("Should never reach here")}Error(t,e=false){let n=new fe.StoryException(t);throw n.useEndLineNumber=e,n}Warning(t){this.AddError(t,true);}AddError(t,e=false,n=false){let i=this.currentDebugMetadata,o=e?"WARNING":"ERROR";if(i!=null){let r=n?i.endLineNumber:i.startLineNumber;t="RUNTIME "+o+": '"+i.fileName+"' line "+r+": "+t;}else this.state.currentPointer.isNull?t="RUNTIME "+o+": "+t:t="RUNTIME "+o+": ("+this.state.currentPointer+"): "+t;this.state.AddError(t,e),e||this.state.ForceEnd();}Assert(t,e=null){if(t==false)throw e==null&&(e="Story assert"),new Error(e+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let t,e=this.state.currentPointer;if(!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(e=this.state.callStack.elements[n].currentPointer,!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.outputStream.length-1;n>=0;--n)if(t=this.state.outputStream[n].debugMetadata,t!==null)return t;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};me.Story=Be;Be.inkVersionCurrent=21;(function(s){(function(e){e[e.NoChange=0]="NoChange",e[e.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",e[e.NewlineRemoved=2]="NewlineRemoved";})(s.OutputStateChange||(s.OutputStateChange={}));})(Be||(me.Story=Be={}));});var yl=C(Jr=>{Object.defineProperty(Jr,"__esModule",{value:true});Jr.Story=void 0;var Zf=jn(),tp=Fi(),$r=K(),Hr=rt(),_n=$e(),Ur=Rt(),Sl=xe(),ep=Ma(),np=nr(),ip=Ja(),rp=vn(),Le=Gt(),sp=Yt(),ap=zt(),Fn=L(),op=ln(),up=hn(),lp=he(),Kr=class s extends Ur.FlowBase{get flowLevel(){return Sl.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(t,e=false){super(null,t,null,false,e),this._errorHandler=null,this._hadError=false,this._hadWarning=false,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=false,this.ExportRuntime=(n=null)=>{var i,o;this._errorHandler=n,this.constants=new Map;for(let h of this.FindAll(tp.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let d=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(d,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(np.ListDefinition)())!((i=h.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((o=h.identifier)===null||o===void 0?void 0:o.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let r=this.runtimeObject,a=new $r.Container;a.AddContent(Hr.ControlCommand.EvalStart());let u=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),a.AddContent(c.listDefinition.runtimeObject),u.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(a);}let d=new ap.VariableAssignment(h,true);d.isGlobal=true,a.AddContent(d);}a.AddContent(Hr.ControlCommand.EvalEnd()),a.AddContent(Hr.ControlCommand.End()),this.variableDeclarations.size>0&&(a.name="global decl",r.AddToNamedContentOnly(a)),r.AddContent(Hr.ControlCommand.Done());let l=new rp.Story(r,u);return this.runtimeObject=l,this.hadError||(this.FlattenContainersIn(r),this.ResolveReferences(this),this.hadError)?null:(l.ResetState(),l)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,o=null)=>{let r=null;if(n)return (r=this._listDefs.get(n))?r.ItemNamed(i):null;{let a=null,u=null;for(let[,l]of this._listDefs.entries()){let h=l.ItemNamed(i);h&&(a?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${u.identifier} and ${l.identifier}`,o,false):(a=h,u=l));}return a}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let o of n.content){let r=(0, Fn.asOrNull)(o,$r.Container);r&&i.add(r);}if(n.namedContent)for(let[,o]of n.namedContent){let r=(0, Fn.asOrNull)(o,$r.Container);r&&i.add(r);}for(let o of i)this.TryFlattenContainer(o),this.FlattenContainersIn(o);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let i=(0, Fn.asOrNull)(n.parent,$r.Container);if(i){let o=i.content.indexOf(n);i.content.splice(o,1);let r=n.ownDebugMetadata;if(n.content)for(let a of n.content)a.parent=null,r!==null&&a.ownDebugMetadata===null&&(a.debugMetadata=r),i.InsertContent(a,o),o+=1;}},this.Error=(n,i,o)=>{let r=o?_n.ErrorType.Warning:_n.ErrorType.Error,a="";if(i instanceof Zf.AuthorWarning?(a+="TODO: ",r=_n.ErrorType.Author):o?a+="WARNING: ":a+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(a+=`'${i.debugMetadata.fileName}' `),a+=`line ${i.debugMetadata.startLineNumber}: `),a+=n,n=a,this._errorHandler!==null)this._errorHandler(n,r);else throw new Error(n);this._hadError=r===_n.ErrorType.Error,this._hadWarning=r===_n.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=n=>this.externals.has(n),this.AddExternal=n=>{this.externals.has(n.name)?this.Error(`Duplicate EXTERNAL definition of '${n.name}'`,n,false):n.name&&this.externals.set(n.name,n);},this.DontFlattenContainer=n=>{this._dontFlattenContainers.add(n);},this.NameConflictError=(n,i,o,r)=>{n.Error(`${r} '${i}': name has already been used for a ${o.typeName.toLowerCase()} on ${o.debugMetadata}`);},this.CheckForNamingCollisions=(n,i,o,r="")=>{var a;let u=r||n.typeName;if(s.IsReservedKeyword(i?.name)){n.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a reserved keyword`);return}else if(up.FunctionCall.IsBuiltIn(i?.name||"")){n.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a built in function`);return}let l=this.ContentWithNameAtLevel(i?.name||"",Sl.FlowLevel.Knot),h=(0, Fn.asOrNull)(l,Ur.FlowBase);if(h&&(h!==n||o===Le.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,u);return}if(o<Le.SymbolType.List)return;for(let[D,v]of this._listDefs)if(i?.name===D&&n!==v&&v.variableAssignment!==n&&this.NameConflictError(n,i?.name,v,u),!(n instanceof ip.ListElementDefinition))for(let A of v.itemDefinitions)i?.name===A.name&&this.NameConflictError(n,i?.name||"",A,u);if(o<=Le.SymbolType.Var)return;let c=i?.name&&this.variableDeclarations.get(i?.name)||null;if(c&&c!==n&&c.isGlobalDeclaration&&c.listDefinition==null&&this.NameConflictError(n,i?.name||"",c,u),o<Le.SymbolType.SubFlowAndWeave)return;let m=new lp.Path(i).ResolveFromContext(n);if(m&&m!==n){this.NameConflictError(n,i?.name||"",m,u);return}if(!(o<Le.SymbolType.Arg)&&o!==Le.SymbolType.Arg){let D=(0, Fn.asOrNull)(n,Ur.FlowBase);if(D||(D=(0, op.ClosestFlowBase)(n)),D&&D.hasParameters&&D.args){for(let v of D.args)if(((a=v.identifier)===null||a===void 0?void 0:a.name)===i?.name){n.Error(`${u} '${i}': name has already been used for a argument to ${D.identifier} on ${D.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(t){super.PreProcessTopLevelObjects(t);let e=[];for(let n of t)if(n instanceof ep.IncludedFile){let i=n,o=t.indexOf(n);if(t.splice(o,1),i.includedStory){let r=[],a=i.includedStory;if(a.content!=null){for(let u of a.content)u instanceof Ur.FlowBase?e.push(u):r.push(u);r.push(new sp.Text(`
29
- `)),t.splice(o,0,...r);}}continue}t.splice(0,0,...e);}};Jr.Story=Kr;Kr.IsReservedKeyword=s=>{switch(s){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var Al=C(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.StringExpression=void 0;var bl=rt(),hp=Et(),cp=Yt(),dp=L(),yo=class s extends hp.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof cp.Text))}constructor(t){super(),this.GenerateIntoContainer=e=>{e.AddContent(bl.ControlCommand.BeginString());for(let n of this.content)e.AddContent(n.runtimeObject);e.AddContent(bl.ControlCommand.EndString());},this.toString=()=>{let e="";for(let n of this.content)e+=n;return e},this.AddContent(t);}get typeName(){return "String"}Equals(t){let e=(0, dp.asOrNull)(t,s);if(e===null||!this.isSingleString||!e.isSingleString)return false;let n=this.toString(),i=e.toString();return n===i}};zr.StringExpression=yo;});var Fl=C(We=>{Object.defineProperty(We,"__esModule",{value:true});We.LegacyTag=We.Tag=void 0;var fp=G(),_l=rt(),bo=class extends fp.ParsedObject{constructor(t,e=false){super(),this.GenerateRuntimeObject=()=>this.isStart?_l.ControlCommand.BeginTag():_l.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=t,this.inChoice=e;}get typeName(){return "Tag"}};We.Tag=bo;var pp=Ba(),Ao=class extends pp.Wrap{constructor(t){super(t);}get typeName(){return "Tag"}};We.LegacyTag=Ao;});var wl=C(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.DefaultFileHandler=void 0;var _o=class{constructor(t){this.rootPath=t,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};Xr.DefaultFileHandler=_o;});var Oo=C(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.InkParser=void 0;var mp=Xo(),gp=jn(),Cp=Ns(),xt=lu(),et=rn(),vp=we(),Dp=vu(),Ep=bi(),wn=da(),Ct=Bi(),Sp=Fi(),Yr=qu(),yp=ju(),ge=Te(),Fo=Pe(),bp=Et(),Ap=Mu(),xl=Gu(),Qr=hn(),_p=un(),Fp=$u(),wp=gr(),Zr=Uu(),Ol=Ma(),xp=Ku(),Op=Ha(),Pl=zu(),Pp=nr(),Tp=Ja(),Np=ua(),Tl=G(),Ip=he(),Nl=Zs(),Il=Sa(),tt=va(),ht=za(),kp=Ya(),kl=yl(),xn=Al(),$t=Gs(),qe=Fl(),Ht=Yt(),Rl=ba(),wo=Oa(),xo=Ie(),Rp=Ps(),ne=L(),On=ki(),je=ii(),Vl=$e(),Vp=wl(),W=class s extends $t.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(t){this._fileHandler=t;}constructor(t,e=null,n=null,i=null,o=null){if(super(t),this.ParseStory=()=>{let r=this.StatementsAtLevel(ht.StatementLevel.Top);return new kl.Story(r,this._rootParser!==this)},this.SeparatedList=(r,a)=>{let u=this.Parse(r);if(u===null)return null;let l=[];l.push(u);do{let h=this.BeginRule();if(a()===null){this.FailRule(h);break}let d=this.Parse(r);if(d===null){this.FailRule(h);break}this.SucceedRule(h),l.push(d);}while(true);return l},this.CreateDebugMetadata=(r,a)=>{let u=new yp.DebugMetadata;return u.startLineNumber=(r?.lineIndex||0)+1,u.endLineNumber=a.lineIndex+1,u.startCharacterNumber=(r?.characterInLineIndex||0)+1,u.endCharacterNumber=a.characterInLineIndex+1,u.fileName=this._filename,u},this.RuleDidSucceed=(r,a,u)=>{let l=(0, ne.asOrNull)(r,Tl.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(a,u));let h=Array.isArray(r)?r:null;if(h!==null)for(let d of h)(0, ne.asOrNull)(d,Tl.ParsedObject)&&(d.hasOwnDebugMetadata||(d.debugMetadata=this.CreateDebugMetadata(a,u)));let c=(0, ne.asOrNull)(r,On.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(a,u));},this.OnStringParserError=(r,a,u=0,l=false)=>{let c=l?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${u+1}: ${r}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,l?Vl.ErrorType.Warning:Vl.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let a=this.ParseUntilCharactersFromString(`
30
- \r`);return a?new gp.AuthorWarning(a):null},this.ExtendIdentifierCharacterRanges=r=>{let a=s.ListAllCharacterRanges();for(let u of a)r.AddCharacters(u.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let r=true,a=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!a){if(a=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),a===null)return null;r=false;}let u=this.Parse(this.BracketedName);this.Whitespace(),u!=null&&this.Newline();let l=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let h=null,c=this.Parse(this.MixedTextAndLogic);c&&(h=new Ct.ContentList(c));let d=null,m=null,D=this.ParseString("[")!==null;if(D){this.EndTagIfNecessary(h);let k=this.Parse(this.MixedTextAndLogic);k!==null&&(d=new Ct.ContentList(k)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(d);let f=this.Parse(this.MixedTextAndLogic);f!==null&&(m=new Ct.ContentList(f));}this.Whitespace(),this.EndTagIfNecessary(m??h);let v=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let A=!h&&!m&&!d;if(A&&v===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&D&&!d&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),m||(m=new Ct.ContentList),this.EndTagIfNecessary(m),v!==null)for(let k of v){let f=(0, ne.asOrNull)(k,ge.Divert);f&&f.isEmpty||m.AddContent(k);}m.AddContent(new Ht.Text(`
31
- `));let S=new vp.Choice(h,d,m);return u&&(S.identifier=u),S.indentationDepth=a.length,S.hasWeaveStyleInlineBrackets=D,S.condition=l,S.onceOnly=r,S.isInvisibleDefault=A,S},this.ChoiceCondition=()=>{let r=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return r===null?null:r.length===1?r[0]:new Np.MultipleConditionExpression(r)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),$t.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let r=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(r),this.Expect(this.String("}"),"closing '}' for choice condition"),r},this.Gather=()=>{let r=this.Parse(this.GatherDashes);if(r===null)return null;let a=Number(r),u=this.Parse(this.BracketedName),l=new _p.Gather(u,a);return this.Newline(),l},this.GatherDashes=()=>{this.Whitespace();let r=0;for(;this.ParseDashNotArrow()!==null;)r+=1,this.Whitespace();return r===0?null:r},this.ParseDashNotArrow=()=>{let r=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(r):this.FailRule(r)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),r)},this.InnerConditionalContent=r=>{if(r===void 0){let c=this.Parse(this.ConditionExpression),d=this.Parse(()=>this.InnerConditionalContent(c));return d===null?null:d}let a,u=r!==null,l=this.Parse(this.Newline)===null;if(l&&!u)return null;if(l)a=this.InlineConditionalBranches();else {if(a=this.MultilineConditionalBranches(),a===null){if(r){let c=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);if(c!==null){a=[new wn.ConditionalSingleBranch(c)];let m=this.Parse(this.SingleMultilineCondition);m&&(m.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",m),m.isElse=true),a.push(m));}}if(a===null)return null}else if(a.length===1&&a[0].isElse&&r){let c=new wn.ConditionalSingleBranch(null);c.isTrueBranch=true,a.unshift(c);}if(r){let c=false;for(let d=0;d<a.length;++d){let m=a[d],D=d===a.length-1;m.ownExpression?(m.matchingEquality=true,c=true):c&&D?(m.matchingEquality=true,m.isElse=true):!D&&a.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",m):d===0?m.isTrueBranch=true:m.isElse=true;}}else {for(let c=0;c<a.length;++c){let d=a[c],m=c===a.length-1;if(d.ownExpression===null)if(m)d.isElse=true;else if(d.isElse){let D=a[a.length-1];D.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",D):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",d);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",d);}a.length===1&&a[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",a[0]);}}if(a===null)return null;for(let c of a)c.isInline=l;return new Ep.Conditional(r,a)},this.InlineConditionalBranches=()=>{let r=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(r===null||r.length===0)return null;let a=[];if(r.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let u=new wn.ConditionalSingleBranch(r[0]);if(u.isTrueBranch=true,a.push(u),r.length>1){let l=new wn.ConditionalSingleBranch(r[1]);l.isElse=true,a.push(l);}}return a},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineCondition);return r===null?null:(this.MultilineWhitespace(),r)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=null,a=this.Parse(this.ElseExpression)!==null;a||(r=this.Parse(this.ConditionExpression));let u=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);r===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new Ht.Text("")]),this.MultilineWhitespace();let l=new wn.ConditionalSingleBranch(u);return l.ownExpression=r,l.isElse=a,l},this.ConditionExpression=()=>{let r=this.Parse(this.Expression);return r===null||(this.DisallowIncrement(r),this.Whitespace(),this.ParseString(":")===null)?null:r},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:$t.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(r,a)=>{if(r.length>0){let u=r.length-1,l=r[u];if(l instanceof Ht.Text){let h=l;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),a?h.text+=" ":h.text.length===0&&(r.splice(u,1),this.TrimEndWhitespace(r,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let r=this.Parse(this.MixedTextAndLogic);if(!r||!r.length)return null;let a=r[0];return a&&a.text&&a.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),r.length===0?null:(r[r.length-1]instanceof ge.Divert||this.TrimEndWhitespace(r,false),this.EndTagIfNecessary(r),r.length>0&&r[0]instanceof qe.Tag&&r[0].isStart||r.push(new Ht.Text(`
26
+ `)),o<e.length-1)){let h=e.length-o-1,c=new Z.StringValue(e.substring(o+1,o+1+h));a.push(c);}return a}PushToOutputStreamIndividual(t){let e=(0, X.asOrNull)(t,mo.Glue),n=(0, X.asOrNull)(t,Z.StringValue),i=true;if(e)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let o=-1,r=this.callStack.currentElement;r.type==Zt.PushPopType.Function&&(o=r.functionStartInOutputStream);let a=-1;for(let l=this.outputStream.length-1;l>=0;l--){let h=this.outputStream[l],c=h instanceof lt.ControlCommand?h:null;if((h instanceof mo.Glue?h:null)!=null){a=l;break}else if(c!=null&&c.commandType==lt.ControlCommand.CommandType.BeginString){l>=o&&(o=-1);break}}let u=-1;if(a!=-1&&o!=-1?u=Math.min(o,a):a!=-1?u=a:u=o,u!=-1){if(n.isNewline)i=false;else if(n.isNonWhitespace&&(a>-1&&this.RemoveExistingGlue(),o>-1)){let l=this.callStack.elements;for(let h=l.length-1;h>=0;h--){let c=l[h];if(c.type==Zt.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(t===null)return (0, At.throwNullException)("obj");this.outputStream.push(t),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let t=-1,e=this.outputStream.length-1;for(;e>=0;){let n=this.outputStream[e],i=(0, X.asOrNull)(n,lt.ControlCommand),o=(0, X.asOrNull)(n,Z.StringValue);if(i!=null||o!=null&&o.isNonWhitespace)break;o!=null&&o.isNewline&&(t=e),e--;}if(t>=0)for(e=t;e<this.outputStream.length;)(0, X.asOrNull)(this.outputStream[e],Z.StringValue)?this.outputStream.splice(e,1):e++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let t=this.outputStream.length-1;t>=0;t--){let e=this.outputStream[t];if(e instanceof mo.Glue)this.outputStream.splice(t,1);else if(e instanceof lt.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let t=this.outputStream.length-1;t>=0&&!(this.outputStream[t]instanceof lt.ControlCommand);t--){let n=this.outputStream[t];if(n instanceof Z.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let t of this.outputStream)if(t instanceof Z.StringValue)return true;return false}get inStringEvaluation(){for(let t=this.outputStream.length-1;t>=0;t--){let e=(0, X.asOrNull)(this.outputStream[t],lt.ControlCommand);if(e instanceof lt.ControlCommand&&e.commandType==lt.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(t){let e=(0, X.asOrNull)(t,Z.ListValue);if(e){let n=e.value;if(n===null)return (0, At.throwNullException)("rawList");if(n.originNames!=null){n.origins||(n.origins=[]),n.origins.length=0;for(let i of n.originNames){if(this.story.listDefinitions===null)return (0, At.throwNullException)("StoryState.story.listDefinitions");let o=this.story.listDefinitions.TryListGetDefinition(i,null);if(o.result===null)return (0, At.throwNullException)("StoryState def.result");n.origins.indexOf(o.result)<0&&n.origins.push(o.result);}}}if(t===null)return (0, At.throwNullException)("obj");this.evaluationStack.push(t);}PopEvaluationStack(t){if(typeof t>"u"){let e=this.evaluationStack.pop();return (0, X.nullIfUndefined)(e)}else {if(t>this.evaluationStack.length)throw new Error("trying to pop too many objects");let e=this.evaluationStack.splice(this.evaluationStack.length-t,t);return (0, X.nullIfUndefined)(e)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Ve.Pointer.Null,this.previousPointer=Ve.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){jf.Debug.Assert(this.callStack.currentElement.type==Zt.PushPopType.Function);let t=this.callStack.currentElement.functionStartInOutputStream;t==-1&&(t=0);for(let e=this.outputStream.length-1;e>=t;e--){let n=this.outputStream[e],i=(0, X.asOrNull)(n,Z.StringValue),o=(0, X.asOrNull)(n,lt.ControlCommand);if(i!=null){if(o)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(e,1),this.OutputStreamDirty();else break}}}PopCallStack(t=null){this.callStack.currentElement.type==Zt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(t);}SetChosenPath(t,e){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(t);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,e&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(t,e){this.callStack.Push(Zt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Ve.Pointer.StartOf(t),this.PassArgumentsToEvaluationStack(e);}PassArgumentsToEvaluationStack(t){if(t!==null)for(let e=0;e<t.length;e++){if(!(typeof t[e]=="number"||typeof t[e]=="string"||typeof t[e]=="boolean"||t[e]instanceof $f.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, X.nullIfUndefined)(t[e])===null?"null":t[e].constructor.name));this.PushEvaluationStack(Z.Value.Create(t[e]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Zt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Ve.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Zt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let t=this.callStack.currentElement.evaluationStackHeightWhenPushed,e=null;for(;this.evaluationStack.length>t;){let n=this.PopEvaluationStack();e===null&&(e=n);}if(this.PopCallStack(Zt.PushPopType.FunctionEvaluationFromGame),e){if(e instanceof qf.Void)return null;let n=(0, X.asOrThrows)(e,Z.Value);return n.valueType==Z.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(t,e){e?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(t)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(t));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};jr.StoryState=Co;});var ml=C(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.Stopwatch=void 0;var vo=class{constructor(){this.startTime=void 0;}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime();}Stop(){this.startTime=void 0;}};Mr.Stopwatch=vo;});var Cl=C(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.ErrorType=void 0;var gl;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(gl||(Gr.ErrorType=gl={}));});var Dn=C(me=>{Object.defineProperty(me,"__esModule",{value:true});me.Story=me.InkList=void 0;var at=J(),Do=dt(),Eo=Re(),Hf=pl(),P=rt(),_t=ue(),Uf=hi(),Kf=eo(),vl=kt(),F=H(),yo=ct(),An=oe(),$r=wr(),Jf=zt(),zf=Ne(),Xf=It(),fe=ze(),So=ho(),pe=se(),Yf=io(),Qf=ml(),ee=on(),_n=pt(),N=W(),L=it(),Dl=fo(),El=Cl(),Zf=pt();Object.defineProperty(me,"InkList",{enumerable:true,get:function(){return Zf.InkList}});Number.isInteger||(Number.isInteger=function(t){return typeof t=="number"&&isFinite(t)&&t>-9007199254740992&&t<9007199254740992&&Math.floor(t)===t});var Be=class s extends Do.InkObject{get currentChoices(){let t=[];if(this._state===null)return (0, L.throwNullException)("this._state");for(let e of this._state.currentChoices)e.isInvisibleDefault||(e.index=t.length,t.push(e));return t}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=false,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=false,this._temporaryEvaluationContainer=null,this._asyncContinueActive=false,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount=0,this._asyncSaving=false,this._profiler=null;let t,e=null,n=null;if(arguments[0]instanceof at.Container)t=arguments[0],typeof arguments[1]<"u"&&(e=arguments[1]),this._mainContentContainer=t;else if(typeof arguments[0]=="string"){let i=arguments[0];n=Dl.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(e!=null&&(this._listDefinitions=new Yf.ListDefinitionsOrigin(e)),this._externals=new Map,n!==null){let i=n,o=i.inkVersion;if(o==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let r=parseInt(o);if(r>s.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!=s.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${s.inkVersionCurrent} used to build story doesn't match current version of engine (${r}). Non-critical, but recommend synchronising.`);let a=i.root;if(a==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let u;(u=i.listDefs)&&(this._listDefinitions=Eo.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, N.asOrThrows)(Eo.JsonSerialisation.JTokenToRuntimeObject(a),at.Container),this.ResetState();}}ToJson(t){let e=false;if(t||(e=true,t=new Dl.SimpleJson.Writer),t.WriteObjectStart(),t.WriteIntProperty("inkVersion",s.inkVersionCurrent),t.WriteProperty("root",n=>Eo.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){t.WritePropertyStart("listDefs"),t.WriteObjectStart();for(let n of this._listDefinitions.lists){t.WritePropertyStart(n.name),t.WriteObjectStart();for(let[i,o]of n.items){let r=_n.InkListItem.fromSerializedKey(i),a=o;t.WriteIntProperty(r.itemName,a);}t.WriteObjectEnd(),t.WritePropertyEnd();}t.WriteObjectEnd(),t.WritePropertyEnd();}if(t.WriteObjectEnd(),e)return t.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new Hf.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, L.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, L.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let t=this.state.currentPointer.copy();this.ChoosePath(new yo.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=t;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(t){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+t);this.state.SwitchFlow_Internal(t);}RemoveFlow(t){this.state.RemoveFlow_Internal(t);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(t){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(t);}ContinueInternal(t=0){this._profiler!=null&&this._profiler.PreContinue();let e=t>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!e&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=e,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=false,this._state.ResetOutput(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation();}let n=new Qf.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(r){if(!(r instanceof fe.StoryException))throw r;this.AddError(r.message,void 0,r.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>t)break}while(this.canContinue);n.Stop();let o=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(_t.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(_t.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(o=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let r of this.state.currentErrors)this.onError(r,El.ErrorType.Error);if(this.state.hasWarning)for(let r of this.state.currentWarnings)this.onError(r,El.ErrorType.Warning);this.ResetErrors();}else {let r=new pe.StringBuilder;throw r.Append("Ink had "),this.state.hasError&&(r.Append(`${this.state.currentErrors.length}`),r.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&r.Append(" and ")),this.state.hasWarning&&(r.Append(`${this.state.currentWarnings.length}`),r.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&r.Append(" and ")),r.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),r.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new fe.StoryException(r.toString())}o!=null&&Object.keys(o).length>0&&this._state.variablesState.NotifyObservers(o);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, L.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, L.throwNullException)("this.state.currentTags");let t=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(t==s.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;t==s.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(t,e,n,i){if(t===null)return (0, L.throwNullException)("prevText");if(e===null)return (0, L.throwNullException)("currText");let o=e.length>=t.length&&t.length>0&&e.charAt(t.length-1)==`
27
+ `;if(n==i&&t.length==e.length&&o)return s.OutputStateChange.NoChange;if(!o)return s.OutputStateChange.NewlineRemoved;if(i>n)return s.OutputStateChange.ExtendedBeyondNewline;for(let r=t.length;r<e.length;r++){let a=e.charAt(r);if(a!=" "&&a!=" ")return s.OutputStateChange.ExtendedBeyondNewline}return s.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let t=new pe.StringBuilder;for(;this.canContinue;)t.Append(this.Continue());return t.toString()}ContentAtPath(t){return this.mainContentContainer.ContentAtPath(t)}KnotContainerWithName(t){let e=this.mainContentContainer.namedContent.get(t);return e instanceof at.Container?e:null}PointerAtPath(t){if(t.length==0)return ee.Pointer.Null;let e=new ee.Pointer,n=t.length,i=null;return t.lastComponent===null?(0, L.throwNullException)("path.lastComponent"):(t.lastComponent.isIndex?(n=t.length-1,i=this.mainContentContainer.ContentAtPath(t,void 0,n),e.container=i.container,e.index=t.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(t),e.container=i.container,e.index=-1),i.obj==null||i.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+t+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+t+"', so it was approximated to: '"+i.obj.path+"'."),e)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, L.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let t=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,t}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let t=true,e=this.state.currentPointer.copy();if(e.isNull)return;let n=(0, N.asOrNull)(e.Resolve(),at.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)e=ee.Pointer.StartOf(n),n=(0, N.asOrNull)(e.Resolve(),at.Container);this.state.currentPointer=e.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=e.Resolve(),o=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;o&&(t=false);let r=(0, N.asOrNull)(i,Uf.ChoicePoint);if(r){let u=this.ProcessChoice(r);u&&this.state.generatedChoices.push(u),i=null,t=false;}if(i instanceof at.Container&&(t=false),t){let u=(0, N.asOrNull)(i,F.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new F.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let a=(0, N.asOrNull)(i,P.ControlCommand);a&&a.commandType==P.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(t,e){(!t.countingAtStartOnly||e)&&(t.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(t),t.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(t));}VisitChangedContainersDueToDivert(){let t=this.state.previousPointer.copy(),e=this.state.currentPointer.copy();if(e.isNull||e.index==-1)return;if(this._prevContainers.length=0,!t.isNull){let r=t.Resolve(),a=(0, N.asOrNull)(r,at.Container)||(0, N.asOrNull)(t.container,at.Container);for(;a;)this._prevContainers.push(a),a=(0, N.asOrNull)(a.parent,at.Container);}let n=e.Resolve();if(n==null)return;let i=(0, N.asOrNull)(n.parent,at.Container),o=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let r=i.content.length>0&&n==i.content[0]&&o;r||(o=false),this.VisitContainer(i,r),n=i,i=(0, N.asOrNull)(i.parent,at.Container);}}PopChoiceStringAndTags(t){let e=(0, N.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);for(;this.state.evaluationStack.length>0&&(0, N.asOrNull)(this.state.PeekEvaluationStack(),$r.Tag)!=null;){let n=(0, N.asOrNull)(this.state.PopEvaluationStack(),$r.Tag);n&&t.push(n.text);}return e.value}ProcessChoice(t){let e=true;if(t.hasCondition){let a=this.state.PopEvaluationStack();this.IsTruthy(a)||(e=false);}let n="",i="",o=[];if(t.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(o)||""),t.hasStartContent&&(n=this.PopChoiceStringAndTags(o)||""),t.onceOnly&&this.state.VisitCountForContainer(t.choiceTarget)>0&&(e=false),!e)return null;let r=new Kf.Choice;return r.targetPath=t.pathOnChoice,r.sourcePath=t.path.toString(),r.isInvisibleDefault=t.isInvisibleDefault,r.threadAtGeneration=this.state.callStack.ForkThread(),r.tags=o.reverse(),r.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),r}IsTruthy(t){let e=false;if(t instanceof F.Value){let n=t;if(n instanceof F.DivertTargetValue){let i=n;return this.Error("Shouldn't use a divert target (to "+i.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return e}PerformLogicAndFlowControl(t){if(t==null)return false;if(t instanceof vl.Divert){let e=t;if(e.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(e.hasVariableTarget){let n=e.variableDivertName,i=this.state.variablesState.GetVariableWithName(n);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(i instanceof F.DivertTargetValue)){let r=(0, N.asOrNull)(i,F.IntValue),a="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";r instanceof F.IntValue&&r.value==0?a+="was empty/null (the value 0).":a+="contained '"+i+"'.",this.Error(a);}let o=(0, N.asOrThrows)(i,F.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(o.targetPath);}else {if(e.isExternal)return this.CallExternalFunction(e.targetPathString,e.externalArgs),true;this.state.divertedPointer=e.targetPointer.copy();}return e.pushesToStack&&this.state.callStack.Push(e.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!e.isExternal&&(e&&e.debugMetadata&&e.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+e.debugMetadata.sourceName):this.Error("Divert resolution failed: "+e)),true}else if(t instanceof P.ControlCommand){let e=t;switch(e.commandType){case P.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case P.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case P.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let p=this.state.PopEvaluationStack();if(!(p instanceof An.Void)){let D=new F.StringValue(p.toString());this.state.PushToOutputStream(D);}}break;case P.ControlCommand.CommandType.NoOp:break;case P.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case P.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case P.ControlCommand.CommandType.PopFunction:case P.ControlCommand.CommandType.PopTunnel:let n=e.commandType==P.ControlCommand.CommandType.PopFunction?_t.PushPopType.Function:_t.PushPopType.Tunnel,i=null;if(n==_t.PushPopType.Tunnel){let p=this.state.PopEvaluationStack();i=(0, N.asOrNull)(p,F.DivertTargetValue),i===null&&this.Assert(p instanceof An.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let p=new Map;p.set(_t.PushPopType.Function,"function return statement (~ return)"),p.set(_t.PushPopType.Tunnel,"tunnel onwards statement (->->)");let D=p.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(D="end of flow (-> END or choice)");let b="Found "+p.get(n)+", when expected "+D;this.Error(b);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case P.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(e),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case P.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(e);break;case P.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let p=[],D=0;for(let _=this.state.outputStream.length-1;_>=0;--_){let V=this.state.outputStream[_];D++;let vt=(0, N.asOrNull)(V,P.ControlCommand);if(vt!=null){if(vt.commandType==P.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}V instanceof F.StringValue&&p.push(V);}this.state.PopFromOutputStream(D);let b=new pe.StringBuilder;for(let _ of p.reverse())b.Append(_.toString());let w=new $r.Tag(this.state.CleanOutputWhitespace(b.toString()));this.state.PushEvaluationStack(w);}else this.state.PushToOutputStream(e);break}case P.ControlCommand.CommandType.EndString:{let p=[],D=[],b=0;for(let _=this.state.outputStream.length-1;_>=0;--_){let V=this.state.outputStream[_];b++;let vt=(0, N.asOrNull)(V,P.ControlCommand);if(vt&&vt.commandType==P.ControlCommand.CommandType.BeginString)break;V instanceof $r.Tag&&D.push(V),V instanceof F.StringValue&&p.push(V);}this.state.PopFromOutputStream(b);for(let _ of D)this.state.PushToOutputStream(_);p=p.reverse();let w=new pe.StringBuilder;for(let _ of p)w.Append(_.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new F.StringValue(w.toString()));break}case P.ControlCommand.CommandType.ChoiceCount:let o=this.state.generatedChoices.length;this.state.PushEvaluationStack(new F.IntValue(o));break;case P.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new F.IntValue(this.state.currentTurnIndex+1));break;case P.ControlCommand.CommandType.TurnsSince:case P.ControlCommand.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof F.DivertTargetValue)){let p="";r instanceof F.IntValue&&(p=". 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+p);break}let a=(0, N.asOrThrows)(r,F.DivertTargetValue),u=(0, N.asOrNull)(this.ContentAtPath(a.targetPath).correctObj,at.Container),l;u!=null?e.commandType==P.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(e.commandType==P.ControlCommand.CommandType.TurnsSince?l=-1:l=0,this.Warning("Failed to find container for "+e.toString()+" lookup at "+a.targetPath.toString())),this.state.PushEvaluationStack(new F.IntValue(l));break;case P.ControlCommand.CommandType.Random:{let p=(0, N.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),D=(0, N.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(D==null||!(D instanceof F.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(p==null||!(p instanceof F.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(p.value===null)return (0, L.throwNullException)("maxInt.value");if(D.value===null)return (0, L.throwNullException)("minInt.value");let b=p.value-D.value+1;(!isFinite(b)||b>Number.MAX_SAFE_INTEGER)&&(b=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),b<=0&&this.Error("RANDOM was called with minimum as "+D.value+" and maximum as "+p.value+". The maximum must be larger");let w=this.state.storySeed+this.state.previousRandom,V=new So.PRNG(w).next(),vt=V%b+D.value;this.state.PushEvaluationStack(new F.IntValue(vt)),this.state.previousRandom=V;break}case P.ControlCommand.CommandType.SeedRandom:let h=(0, N.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(h==null||!(h instanceof F.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, L.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new An.Void);break;case P.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new F.IntValue(c));break;case P.ControlCommand.CommandType.SequenceShuffleIndex:let m=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new F.IntValue(m));break;case P.ControlCommand.CommandType.StartThread:break;case P.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=ee.Pointer.Null);break;case P.ControlCommand.CommandType.End:this.state.ForceEnd();break;case P.ControlCommand.CommandType.ListFromInt:let g=(0, N.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),E=(0, N.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);if(g===null)throw new fe.StoryException("Passed non-integer when creating a list element from a numerical value.");let v=null;if(this.listDefinitions===null)return (0, L.throwNullException)("this.listDefinitions");let S=this.listDefinitions.TryListGetDefinition(E.value,null);if(S.exists){if(g.value===null)return (0, L.throwNullException)("minInt.value");let p=S.result.TryGetItemWithValue(g.value,_n.InkListItem.Null);p.exists&&(v=new F.ListValue(p.result,g.value));}else throw new fe.StoryException("Failed to find LIST called "+E.value);v==null&&(v=new F.ListValue),this.state.PushEvaluationStack(v);break;case P.ControlCommand.CommandType.ListRange:let y=(0, N.asOrNull)(this.state.PopEvaluationStack(),F.Value),T=(0, N.asOrNull)(this.state.PopEvaluationStack(),F.Value),R=(0, N.asOrNull)(this.state.PopEvaluationStack(),F.ListValue);if(R===null||T===null||y===null)throw new fe.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(R.value===null)return (0, L.throwNullException)("targetList.value");let d=R.value.ListWithSubRange(T.valueObject,y.valueObject);this.state.PushEvaluationStack(new F.ListValue(d));break;case P.ControlCommand.CommandType.ListRandom:{let p=this.state.PopEvaluationStack();if(p===null)throw new fe.StoryException("Expected list for LIST_RANDOM");let D=p.value,b=null;if(D===null)throw (0, L.throwNullException)("list");if(D.Count==0)b=new _n.InkList;else {let w=this.state.storySeed+this.state.previousRandom,V=new So.PRNG(w).next(),vt=V%D.Count,Me=D.entries();for(let Ro=0;Ro<=vt-1;Ro++)Me.next();let ko=Me.next().value,Nn={Key:_n.InkListItem.fromSerializedKey(ko[0]),Value:ko[1]};if(Nn.Key.originName===null)return (0, L.throwNullException)("randomItem.Key.originName");b=new _n.InkList(Nn.Key.originName,this),b.Add(Nn.Key,Nn.Value),this.state.previousRandom=V;}this.state.PushEvaluationStack(new F.ListValue(b));break}default:this.Error("unhandled ControlCommand: "+e);break}return true}else if(t instanceof Jf.VariableAssignment){let e=t,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(e,n),true}else if(t instanceof zf.VariableReference){let e=t,n=null;if(e.pathForCount!=null){let i=e.containerForCount,o=this.state.VisitCountForContainer(i);n=new F.IntValue(o);}else n=this.state.variablesState.GetVariableWithName(e.name),n==null&&(this.Warning("Variable not found: '"+e.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),n=new F.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(t instanceof Xf.NativeFunctionCall){let e=t,n=this.state.PopEvaluationStack(e.numberOfParameters),i=e.Call(n);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(t,e=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(t,n),e)this.ResetCallstack();else if(this.state.callStack.currentElement.type==_t.PushPopType.Function){let i="",o=this.state.callStack.currentElement.currentPointer.container;throw o!=null&&(i="("+o.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+t+`) - this is almost certainly not not what you want! Full stack trace:
28
+ `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new yo.Path(t));}IfAsyncWeCant(t){if(this._asyncContinueActive)throw new Error("Can't "+t+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(t,e=true){this.state.SetChosenPath(t,e),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(t){t=t;let e=this.currentChoices;this.Assert(t>=0&&t<e.length,"choice out of range");let n=e[t];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, L.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, L.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(t){try{return this.KnotContainerWithName(t)!=null}catch{return false}}EvaluateFunction(t,e=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(t,e),this.IfAsyncWeCant("evaluate a function"),t==null)throw new Error("Function is null");if(t==""||t.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(t);if(i==null)throw new Error("Function doesn't exist: '"+t+"'");let o=[];o.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,e);let r=new pe.StringBuilder;for(;this.canContinue;)r.Append(this.Continue());let a=r.toString();this._state.ResetOutput(o);let u=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(t,e,a,u),n?{returned:u,output:a}:u}EvaluateExpression(t){let e=this.state.callStack.elements.length;this.state.callStack.Push(_t.PushPopType.Tunnel),this._temporaryEvaluationContainer=t,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>e&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(t,e){if(t===null)return (0, L.throwNullException)("funcName");let n=this._externals.get(t),i=null,o=typeof n<"u";if(o&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+t+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+t+"()"),o&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!o)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(t),this.Assert(i!==null,"Trying to call EXTERNAL function '"+t+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(_t.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=ee.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+t+"' which has not been bound (and ink fallbacks disabled).");let r=[];for(let l=0;l<e;++l){let c=(0, N.asOrThrows)(this.state.PopEvaluationStack(),F.Value).valueObject;r.push(c);}r.reverse();let a=n.function(r),u=null;a!=null?(u=F.Value.Create(a),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof a)):u=new An.Void,this.state.PushEvaluationStack(u);}BindExternalFunctionGeneral(t,e,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(t),"Function '"+t+"' has already been bound."),this._externals.set(t,{function:e,lookAheadSafe:n});}TryCoerce(t){return t}BindExternalFunction(t,e,n=false){this.Assert(e!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(t,i=>{this.Assert(i.length>=e.length,"External function expected "+e.length+" arguments");let o=[];for(let r=0,a=i.length;r<a;r++)o[r]=this.TryCoerce(i[r]);return e.apply(null,o)},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 at.Container&&(t=arguments[0]),arguments[0]instanceof Do.InkObject&&(e=arguments[0]),t===null&&e===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=n.size>1?"s":"",i+=": '",i+=Array.from(n).join("', '"),i+="' ",i+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(i);}else if(t!=null){for(let i of t.content){let o=i;(o==null||!o.hasValidName)&&this.ValidateExternalBindings(i,n);}for(let[,i]of t.namedContent)this.ValidateExternalBindings((0, N.asOrNull)(i,Do.InkObject),n);}else if(e!=null){let i=(0, N.asOrNull)(e,vl.Divert);if(i&&i.isExternal){let o=i.targetPathString;if(o===null)return (0, L.throwNullException)("name");this._externals.has(o)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(o)||n.add(o);}}}ObserveVariable(t,e){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(t))throw new Error("Cannot observe variable '"+t+"' because it wasn't declared in the ink story.");this._variableObservers.has(t)?this._variableObservers.get(t).push(e):this._variableObservers.set(t,[e]);}ObserveVariables(t,e){for(let n=0,i=t.length;n<i;n++)this.ObserveVariable(t[n],e[n]);}RemoveVariableObserver(t,e){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(e!=null){if(this._variableObservers.has(e))if(t!=null){let n=this._variableObservers.get(e);n!=null&&(n.splice(n.indexOf(t),1),n.length===0&&this._variableObservers.delete(e));}else this._variableObservers.delete(e);}else if(t!=null){let n=this._variableObservers.keys();for(let i of n){let o=this._variableObservers.get(i);o!=null&&(o.splice(o.indexOf(t),1),o.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(t,e){if(this._variableObservers===null)return;let n=this._variableObservers.get(t);if(typeof n<"u"){if(!(e instanceof F.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, N.asOrThrows)(e,F.Value);for(let o of n)o(t,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(t){return this.TagsAtStartOfFlowContainerWithPathString(t)}TagsAtStartOfFlowContainerWithPathString(t){let e=new yo.Path(t),n=this.ContentAtPath(e).container;if(n===null)return (0, L.throwNullException)("flowContainer");for(;;){let r=n.content[0];if(r instanceof at.Container)n=r;else break}let i=false,o=null;for(let r of n.content){let a=(0, N.asOrNull)(r,P.ControlCommand);if(a!=null)a.commandType==P.ControlCommand.CommandType.BeginTag?i=true:a.commandType==P.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, N.asOrNull)(r,F.StringValue);u!==null?(o===null&&(o=[]),u.value!==null&&o.push(u.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return o}BuildStringOfHierarchy(){let t=new pe.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}BuildStringOfContainer(t){let e=new pe.StringBuilder;return t.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=ee.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let e=false;this.state.callStack.CanPop(_t.PushPopType.Function)?(this.state.PopCallStack(_t.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new An.Void),e=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),e=true):this.state.TryExitFunctionEvaluationFromGame(),e&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let t=true,e=this.state.callStack.currentElement.currentPointer.copy();if(e.index++,e.container===null)return (0, L.throwNullException)("pointer.container");for(;e.index>=e.container.content.length;){t=false;let n=(0, N.asOrNull)(e.container.parent,at.Container);if(!(n instanceof at.Container))break;let i=n.content.indexOf(e.container);if(i==-1)break;if(e=new ee.Pointer(n,i),e.index++,t=true,e.container===null)return (0, L.throwNullException)("pointer.container")}return t||(e=ee.Pointer.Null),this.state.callStack.currentElement.currentPointer=e.copy(),t}TryFollowDefaultInvisibleChoice(){let t=this._state.currentChoices,e=t.filter(i=>i.isInvisibleDefault);if(e.length==0||t.length>e.length)return false;let n=e[0];return n.targetPath===null?(0, L.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, L.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,false),true)}NextSequenceShuffleIndex(){let t=(0, N.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(!(t instanceof F.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let e=this.state.currentPointer.container;if(e===null)return (0, L.throwNullException)("seqContainer");if(t.value===null)return (0, L.throwNullException)("numElementsIntVal.value");let n=t.value,o=(0, N.asOrThrows)(this.state.PopEvaluationStack(),F.IntValue).value;if(o===null)return (0, L.throwNullException)("seqCount");let r=o/n,a=o%n,u=e.path.toString(),l=0;for(let g=0,E=u.length;g<E;g++)l+=u.charCodeAt(g)||0;let h=l+r+this.state.storySeed,c=new So.PRNG(Math.floor(h)),m=[];for(let g=0;g<n;++g)m.push(g);for(let g=0;g<=a;++g){let E=c.next()%m.length,v=m[E];if(m.splice(E,1),g==a)return v}throw new Error("Should never reach here")}Error(t,e=false){let n=new fe.StoryException(t);throw n.useEndLineNumber=e,n}Warning(t){this.AddError(t,true);}AddError(t,e=false,n=false){let i=this.currentDebugMetadata,o=e?"WARNING":"ERROR";if(i!=null){let r=n?i.endLineNumber:i.startLineNumber;t="RUNTIME "+o+": '"+i.fileName+"' line "+r+": "+t;}else this.state.currentPointer.isNull?t="RUNTIME "+o+": "+t:t="RUNTIME "+o+": ("+this.state.currentPointer+"): "+t;this.state.AddError(t,e),e||this.state.ForceEnd();}Assert(t,e=null){if(t==false)throw e==null&&(e="Story assert"),new Error(e+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let t,e=this.state.currentPointer;if(!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(e=this.state.callStack.elements[n].currentPointer,!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.outputStream.length-1;n>=0;--n)if(t=this.state.outputStream[n].debugMetadata,t!==null)return t;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};me.Story=Be;Be.inkVersionCurrent=21;(function(s){(function(e){e[e.NoChange=0]="NoChange",e[e.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",e[e.NewlineRemoved=2]="NewlineRemoved";})(s.OutputStateChange||(s.OutputStateChange={}));})(Be||(me.Story=Be={}));});var Sl=C(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.Story=void 0;var tp=Mn(),ep=wi(),Hr=J(),Ur=rt(),Fn=He(),Kr=Rt(),yl=xe(),np=Ga(),ip=ir(),rp=za(),sp=Dn(),Le=Gt(),ap=Yt(),op=zt(),wn=W(),up=hn(),lp=cn(),hp=he(),Jr=class s extends Kr.FlowBase{get flowLevel(){return yl.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(t,e=false){super(null,t,null,false,e),this._errorHandler=null,this._hadError=false,this._hadWarning=false,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=false,this.ExportRuntime=(n=null)=>{var i,o;this._errorHandler=n,this.constants=new Map;for(let h of this.FindAll(ep.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let m=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(m,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(ip.ListDefinition)())!((i=h.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((o=h.identifier)===null||o===void 0?void 0:o.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let r=this.runtimeObject,a=new Hr.Container;a.AddContent(Ur.ControlCommand.EvalStart());let u=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),a.AddContent(c.listDefinition.runtimeObject),u.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(a);}let m=new op.VariableAssignment(h,true);m.isGlobal=true,a.AddContent(m);}a.AddContent(Ur.ControlCommand.EvalEnd()),a.AddContent(Ur.ControlCommand.End()),this.variableDeclarations.size>0&&(a.name="global decl",r.AddToNamedContentOnly(a)),r.AddContent(Ur.ControlCommand.Done());let l=new sp.Story(r,u);return this.runtimeObject=l,this.hadError||(this.FlattenContainersIn(r),this.ResolveReferences(this),this.hadError)?null:(l.ResetState(),l)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,o=null)=>{let r=null;if(n)return (r=this._listDefs.get(n))?r.ItemNamed(i):null;{let a=null,u=null;for(let[,l]of this._listDefs.entries()){let h=l.ItemNamed(i);h&&(a?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${u.identifier} and ${l.identifier}`,o,false):(a=h,u=l));}return a}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let o of n.content){let r=(0, wn.asOrNull)(o,Hr.Container);r&&i.add(r);}if(n.namedContent)for(let[,o]of n.namedContent){let r=(0, wn.asOrNull)(o,Hr.Container);r&&i.add(r);}for(let o of i)this.TryFlattenContainer(o),this.FlattenContainersIn(o);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let i=(0, wn.asOrNull)(n.parent,Hr.Container);if(i){let o=i.content.indexOf(n);i.content.splice(o,1);let r=n.ownDebugMetadata;if(n.content)for(let a of n.content)a.parent=null,r!==null&&a.ownDebugMetadata===null&&(a.debugMetadata=r),i.InsertContent(a,o),o+=1;}},this.Error=(n,i,o)=>{let r=o?Fn.ErrorType.Warning:Fn.ErrorType.Error,a="";if(i instanceof tp.AuthorWarning?(a+="TODO: ",r=Fn.ErrorType.Author):o?a+="WARNING: ":a+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(a+=`'${i.debugMetadata.fileName}' `),a+=`line ${i.debugMetadata.startLineNumber}: `),a+=n,n=a,this._errorHandler!==null)this._errorHandler(n,r);else throw new Error(n);this._hadError=r===Fn.ErrorType.Error,this._hadWarning=r===Fn.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=n=>this.externals.has(n),this.AddExternal=n=>{this.externals.has(n.name)?this.Error(`Duplicate EXTERNAL definition of '${n.name}'`,n,false):n.name&&this.externals.set(n.name,n);},this.DontFlattenContainer=n=>{this._dontFlattenContainers.add(n);},this.NameConflictError=(n,i,o,r)=>{n.Error(`${r} '${i}': name has already been used for a ${o.typeName.toLowerCase()} on ${o.debugMetadata}`);},this.CheckForNamingCollisions=(n,i,o,r="")=>{var a;let u=r||n.typeName;if(s.IsReservedKeyword(i?.name)){n.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a reserved keyword`);return}else if(lp.FunctionCall.IsBuiltIn(i?.name||"")){n.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a built in function`);return}let l=this.ContentWithNameAtLevel(i?.name||"",yl.FlowLevel.Knot),h=(0, wn.asOrNull)(l,Kr.FlowBase);if(h&&(h!==n||o===Le.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,u);return}if(o<Le.SymbolType.List)return;for(let[E,v]of this._listDefs)if(i?.name===E&&n!==v&&v.variableAssignment!==n&&this.NameConflictError(n,i?.name,v,u),!(n instanceof rp.ListElementDefinition))for(let S of v.itemDefinitions)i?.name===S.name&&this.NameConflictError(n,i?.name||"",S,u);if(o<=Le.SymbolType.Var)return;let c=i?.name&&this.variableDeclarations.get(i?.name)||null;if(c&&c!==n&&c.isGlobalDeclaration&&c.listDefinition==null&&this.NameConflictError(n,i?.name||"",c,u),o<Le.SymbolType.SubFlowAndWeave)return;let g=new hp.Path(i).ResolveFromContext(n);if(g&&g!==n){this.NameConflictError(n,i?.name||"",g,u);return}if(!(o<Le.SymbolType.Arg)&&o!==Le.SymbolType.Arg){let E=(0, wn.asOrNull)(n,Kr.FlowBase);if(E||(E=(0, up.ClosestFlowBase)(n)),E&&E.hasParameters&&E.args){for(let v of E.args)if(((a=v.identifier)===null||a===void 0?void 0:a.name)===i?.name){n.Error(`${u} '${i}': name has already been used for a argument to ${E.identifier} on ${E.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(t){super.PreProcessTopLevelObjects(t);let e=[];for(let n of t)if(n instanceof np.IncludedFile){let i=n,o=t.indexOf(n);if(t.splice(o,1),i.includedStory){let r=[],a=i.includedStory;if(a.content!=null){for(let u of a.content)u instanceof Kr.FlowBase?e.push(u):r.push(u);r.push(new ap.Text(`
29
+ `)),t.splice(o,0,...r);}}continue}t.splice(0,0,...e);}};zr.Story=Jr;Jr.IsReservedKeyword=s=>{switch(s){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var Al=C(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.StringExpression=void 0;var bl=rt(),cp=Et(),dp=Yt(),fp=W(),bo=class s extends cp.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof dp.Text))}constructor(t){super(),this.GenerateIntoContainer=e=>{e.AddContent(bl.ControlCommand.BeginString());for(let n of this.content)e.AddContent(n.runtimeObject);e.AddContent(bl.ControlCommand.EndString());},this.toString=()=>{let e="";for(let n of this.content)e+=n;return e},this.AddContent(t);}get typeName(){return "String"}Equals(t){let e=(0, fp.asOrNull)(t,s);if(e===null||!this.isSingleString||!e.isSingleString)return false;let n=this.toString(),i=e.toString();return n===i}};Xr.StringExpression=bo;});var Fl=C(We=>{Object.defineProperty(We,"__esModule",{value:true});We.LegacyTag=We.Tag=void 0;var pp=$(),_l=rt(),Ao=class extends pp.ParsedObject{constructor(t,e=false){super(),this.GenerateRuntimeObject=()=>this.isStart?_l.ControlCommand.BeginTag():_l.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=t,this.inChoice=e;}get typeName(){return "Tag"}};We.Tag=Ao;var mp=La(),_o=class extends mp.Wrap{constructor(t){super(t);}get typeName(){return "Tag"}};We.LegacyTag=_o;});var wl=C(Yr=>{Object.defineProperty(Yr,"__esModule",{value:true});Yr.DefaultFileHandler=void 0;var Fo=class{constructor(t){this.rootPath=t,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};Yr.DefaultFileHandler=Fo;});var Po=C(es=>{Object.defineProperty(es,"__esModule",{value:true});es.InkParser=void 0;var gp=Xo(),Cp=Mn(),vp=Is(),xt=lu(),et=sn(),Dp=we(),Ep=vu(),yp=Ai(),xn=fa(),Ct=Li(),Sp=wi(),Qr=qu(),bp=ju(),ge=Te(),wo=Pe(),Ap=Et(),_p=Mu(),xl=Gu(),Zr=cn(),Fp=ln(),wp=$u(),xp=Cr(),ts=Uu(),Ol=Ga(),Op=Ku(),Pp=Ua(),Pl=zu(),Tp=ir(),Np=za(),Ip=la(),Tl=$(),kp=he(),Nl=ta(),Il=Sa(),tt=Da(),ht=Xa(),Rp=Qa(),kl=Sl(),On=Al(),$t=$s(),qe=Fl(),Ht=Yt(),Rl=Aa(),xo=Pa(),Oo=Ie(),Vp=Ts(),ne=W(),Pn=Ri(),je=ri(),Vl=He(),Bp=wl(),q=class s extends $t.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(t){this._fileHandler=t;}constructor(t,e=null,n=null,i=null,o=null){if(super(t),this.ParseStory=()=>{let r=this.StatementsAtLevel(ht.StatementLevel.Top);return new kl.Story(r,this._rootParser!==this)},this.SeparatedList=(r,a)=>{let u=this.Parse(r);if(u===null)return null;let l=[];l.push(u);do{let h=this.BeginRule();if(a()===null){this.FailRule(h);break}let m=this.Parse(r);if(m===null){this.FailRule(h);break}this.SucceedRule(h),l.push(m);}while(true);return l},this.CreateDebugMetadata=(r,a)=>{let u=new bp.DebugMetadata;return u.startLineNumber=(r?.lineIndex||0)+1,u.endLineNumber=a.lineIndex+1,u.startCharacterNumber=(r?.characterInLineIndex||0)+1,u.endCharacterNumber=a.characterInLineIndex+1,u.fileName=this._filename,u},this.RuleDidSucceed=(r,a,u)=>{let l=(0, ne.asOrNull)(r,Tl.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(a,u));let h=Array.isArray(r)?r:null;if(h!==null)for(let m of h)(0, ne.asOrNull)(m,Tl.ParsedObject)&&(m.hasOwnDebugMetadata||(m.debugMetadata=this.CreateDebugMetadata(a,u)));let c=(0, ne.asOrNull)(r,Pn.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(a,u));},this.OnStringParserError=(r,a,u=0,l=false)=>{let c=l?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${u+1}: ${r}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,l?Vl.ErrorType.Warning:Vl.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let a=this.ParseUntilCharactersFromString(`
30
+ \r`);return a?new Cp.AuthorWarning(a):null},this.ExtendIdentifierCharacterRanges=r=>{let a=s.ListAllCharacterRanges();for(let u of a)r.AddCharacters(u.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let r=true,a=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!a){if(a=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),a===null)return null;r=false;}let u=this.Parse(this.BracketedName);this.Whitespace(),u!=null&&this.Newline();let l=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let h=null,c=this.Parse(this.MixedTextAndLogic);c&&(h=new Ct.ContentList(c));let m=null,g=null,E=this.ParseString("[")!==null;if(E){this.EndTagIfNecessary(h);let T=this.Parse(this.MixedTextAndLogic);T!==null&&(m=new Ct.ContentList(T)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(m);let R=this.Parse(this.MixedTextAndLogic);R!==null&&(g=new Ct.ContentList(R));}this.Whitespace(),this.EndTagIfNecessary(g??h);let v=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let S=!h&&!g&&!m;if(S&&v===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&E&&!m&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),g||(g=new Ct.ContentList),this.EndTagIfNecessary(g),v!==null)for(let T of v){let R=(0, ne.asOrNull)(T,ge.Divert);R&&R.isEmpty||g.AddContent(T);}g.AddContent(new Ht.Text(`
31
+ `));let y=new Dp.Choice(h,m,g);return u&&(y.identifier=u),y.indentationDepth=a.length,y.hasWeaveStyleInlineBrackets=E,y.condition=l,y.onceOnly=r,y.isInvisibleDefault=S,y},this.ChoiceCondition=()=>{let r=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return r===null?null:r.length===1?r[0]:new Ip.MultipleConditionExpression(r)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),$t.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let r=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(r),this.Expect(this.String("}"),"closing '}' for choice condition"),r},this.Gather=()=>{let r=this.Parse(this.GatherDashes);if(r===null)return null;let a=Number(r),u=this.Parse(this.BracketedName),l=new Fp.Gather(u,a);return this.Newline(),l},this.GatherDashes=()=>{this.Whitespace();let r=0;for(;this.ParseDashNotArrow()!==null;)r+=1,this.Whitespace();return r===0?null:r},this.ParseDashNotArrow=()=>{let r=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(r):this.FailRule(r)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),r)},this.InnerConditionalContent=r=>{if(r===void 0){let c=this.Parse(this.ConditionExpression),m=this.Parse(()=>this.InnerConditionalContent(c));return m===null?null:m}let a,u=r!==null,l=this.Parse(this.Newline)===null;if(l&&!u)return null;if(l)a=this.InlineConditionalBranches();else {if(a=this.MultilineConditionalBranches(),a===null){if(r){let c=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);if(c!==null){a=[new xn.ConditionalSingleBranch(c)];let g=this.Parse(this.SingleMultilineCondition);g&&(g.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",g),g.isElse=true),a.push(g));}}if(a===null)return null}else if(a.length===1&&a[0].isElse&&r){let c=new xn.ConditionalSingleBranch(null);c.isTrueBranch=true,a.unshift(c);}if(r){let c=false;for(let m=0;m<a.length;++m){let g=a[m],E=m===a.length-1;g.ownExpression?(g.matchingEquality=true,c=true):c&&E?(g.matchingEquality=true,g.isElse=true):!E&&a.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",g):m===0?g.isTrueBranch=true:g.isElse=true;}}else {for(let c=0;c<a.length;++c){let m=a[c],g=c===a.length-1;if(m.ownExpression===null)if(g)m.isElse=true;else if(m.isElse){let E=a[a.length-1];E.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",E):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",m);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",m);}a.length===1&&a[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",a[0]);}}if(a===null)return null;for(let c of a)c.isInline=l;return new yp.Conditional(r,a)},this.InlineConditionalBranches=()=>{let r=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(r===null||r.length===0)return null;let a=[];if(r.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let u=new xn.ConditionalSingleBranch(r[0]);if(u.isTrueBranch=true,a.push(u),r.length>1){let l=new xn.ConditionalSingleBranch(r[1]);l.isElse=true,a.push(l);}}return a},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineCondition);return r===null?null:(this.MultilineWhitespace(),r)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=null,a=this.Parse(this.ElseExpression)!==null;a||(r=this.Parse(this.ConditionExpression));let u=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);r===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new Ht.Text("")]),this.MultilineWhitespace();let l=new xn.ConditionalSingleBranch(u);return l.ownExpression=r,l.isElse=a,l},this.ConditionExpression=()=>{let r=this.Parse(this.Expression);return r===null||(this.DisallowIncrement(r),this.Whitespace(),this.ParseString(":")===null)?null:r},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:$t.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(r,a)=>{if(r.length>0){let u=r.length-1,l=r[u];if(l instanceof Ht.Text){let h=l;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),a?h.text+=" ":h.text.length===0&&(r.splice(u,1),this.TrimEndWhitespace(r,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let r=this.Parse(this.MixedTextAndLogic);if(!r||!r.length)return null;let a=r[0];return a&&a.text&&a.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),r.length===0?null:(r[r.length-1]instanceof ge.Divert||this.TrimEndWhitespace(r,false),this.EndTagIfNecessary(r),r.length>0&&r[0]instanceof qe.Tag&&r[0].isStart||r.push(new Ht.Text(`
32
32
  `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),r)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let a=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let u=this.Parse(this.MultiDivert);u!==null&&(a===null&&(a=[]),this.EndTagIfNecessary(a),this.TrimEndWhitespace(a,true),a.push(...u));}return a||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let r=null;do{let a=this.Parse(this.ContentTextNoEscape),u=this.ParseString("\\")!==null;if(u||a!==null){if(r===null&&(r=""),a!==null&&(r+=String(a)),u){let l=this.ParseSingleCharacter();r+=l;}}else break}while(true);return r!==null?new Ht.Text(r):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new et.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new et.CharacterSet(`{}|
33
- \r\\#`),this._notTextEndCharactersChoice=new et.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new et.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let r=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),a=null;this.parsingStringExpression?a=this._notTextEndCharactersString:this._parsingChoice?a=this._notTextEndCharactersChoice:a=this._nonTextEndCharacters;let u=this.ParseUntil(r,this._nonTextPauseCharacters,a);return u!==null?u:null},this.MultiDivert=()=>{this.Whitespace();let r=[],a=this.Parse(this.StartThread);if(a)return r=[a],r;let u=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!u)return null;r=[],this.EndTagIfNecessary(r);for(let l=0;l<u.length;++l)if(l%2===0){if(u[l]==="->->"){l===0||l===u.length-1||l===u.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let d=new Rl.TunnelOnwards;if(l<u.length-1){let m=(0, ne.asOrNull)(u[l+1],ge.Divert);d.divertAfter=m;}r.push(d);break}}else {let c=u[l];l<u.length-1&&(c.isTunnel=true),r.push(c);}if(r.length===0&&u.length===1){let l=new ge.Divert(null);l.isEmpty=true,r.push(l),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return r},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let r=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new ge.Divert(null));return r.isThread=true,r},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let r=this.Parse(this.DotSeparatedDivertPathComponents);if(!r)return null;this.Whitespace();let a=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let u=new Ip.Path(r);return new ge.Divert(u,a)},this.SingleDivert=()=>{let r=this.Parse(this.MultiDivert);if(!r||r.length!==1||r[0]instanceof Rl.TunnelOnwards)return null;let u=r[0];return u.isTunnel?null:u},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let r=0;for(;this.ParseString("->")!==null;)r+=1;return r===0?null:r===1?"->":(r===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let r=this.ParseTempKeyword();this.Whitespace();let a=null;if(r?a=this.Expect(this.IdentifierWithMetadata,"variable name"):a=this.Parse(this.IdentifierWithMetadata),a===null)return null;this.Whitespace();let u=this.ParseString("+")!==null,l=this.ParseString("-")!==null;if(u&&l&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return r&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return u||l?new Zr.IncDecExpression(a,h,u):new wo.VariableAssignment({variableIdentifier:a,assignedExpression:h,isTemporaryNewDeclaration:r})},this.DisallowIncrement=r=>{r instanceof Zr.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let r=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(r),true):(this.FailRule(r),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let a=this.Parse(this.Expression);return new Nl.ReturnType(a)},this.Expression=(r=0)=>{this.Whitespace();let a=this.ExpressionUnary();if(a===null)return null;for(this.Whitespace();;){let u=this.BeginRule(),l=this.ParseInfixOperator();if(l!==null&&l.precedence>r){let h=`right side of '${l.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(a,l),h);if(c===null)return this.FailRule(u),null;a=this.SucceedRule(u,c);continue}this.FailRule(u);break}return this.Whitespace(),a},this.ExpressionUnary=()=>{let r=this.Parse(this.ExpressionDivertTarget);if(r!==null)return r;let a=this.OneOf([this.String("-"),this.String("!")]);a===null&&(a=this.Parse(this.ExpressionNot)),this.Whitespace();let u=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(u===null&&a!==null&&(u=this.ExpressionUnary()),u===null)return null;a!==null&&(u=Rp.UnaryExpression.WithInner(u,a)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let h=l==="++";if(!(u instanceof xo.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let c=u;u=new Zr.IncDecExpression(c.identifier,h);}}return u},this.ExpressionNot=()=>{let r=this.Identifier();return r==="not"?r:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let r=this.Parse(this.SingleDivert);return !r||r&&r.isThread?null:(this.Whitespace(),new Fo.DivertTarget(r))},this.ExpressionInt=()=>{let r=this.ParseInt();return r===null?null:new je.NumberExpression(r,"int")},this.ExpressionFloat=()=>{let r=this.ParseFloat();return r===null?null:new je.NumberExpression(r,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let a=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,a===null?a=[new Ht.Text("")]:a.find(u=>u instanceof ge.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new xn.StringExpression(a)},this.ExpressionBool=()=>{let r=this.Parse(this.Identifier);return r==="true"?new je.NumberExpression(true,"bool"):r==="false"?new je.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;this.Whitespace();let a=this.Parse(this.ExpressionFunctionCallArguments);return a===null?null:new Qr.FunctionCall(r,a)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Exclude(this.String(",")),a=this.Interleave(this.Expression,r);return a===null&&(a=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),a},this.ExpressionVariableName=()=>{let r=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return r===null||kl.Story.IsReservedKeyword(r[0].name)?null:new xo.VariableReference(r)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let r=this.Parse(this.Expression);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),r)},this.ExpressionInfixRight=(r,a)=>{if(!r)return null;this.Whitespace();let u=this.Parse(()=>this.Expression(a.precedence));return u?new Cp.BinaryExpression(r,u,a.type):null},this.ParseInfixOperator=()=>{for(let r of this._binaryOperators){let a=this.BeginRule();if(this.ParseString(r.type)!==null){if(r.requireWhitespace&&this.Whitespace()===null){this.FailRule(a);continue}return this.SucceedRule(a,r)}this.FailRule(a);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let r=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new Pl.List(r)},this.ListMember=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;if(this.ParseString(".")!==null){let u=this.Expect(this.IdentifierWithMetadata,`element name within the set ${r}`);r.name+=`.${u?.name}`;}return this.Whitespace(),r},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(r,a,u=false)=>{let l=new xp.InfixOperator(r,a,u);this._binaryOperators.push(l),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,r.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let r=this.Expect(()=>this.ParseUntilCharactersFromString(`
33
+ \r\\#`),this._notTextEndCharactersChoice=new et.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new et.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let r=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),a=null;this.parsingStringExpression?a=this._notTextEndCharactersString:this._parsingChoice?a=this._notTextEndCharactersChoice:a=this._nonTextEndCharacters;let u=this.ParseUntil(r,this._nonTextPauseCharacters,a);return u!==null?u:null},this.MultiDivert=()=>{this.Whitespace();let r=[],a=this.Parse(this.StartThread);if(a)return r=[a],r;let u=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!u)return null;r=[],this.EndTagIfNecessary(r);for(let l=0;l<u.length;++l)if(l%2===0){if(u[l]==="->->"){l===0||l===u.length-1||l===u.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let m=new Rl.TunnelOnwards;if(l<u.length-1){let g=(0, ne.asOrNull)(u[l+1],ge.Divert);m.divertAfter=g;}r.push(m);break}}else {let c=u[l];l<u.length-1&&(c.isTunnel=true),r.push(c);}if(r.length===0&&u.length===1){let l=new ge.Divert(null);l.isEmpty=true,r.push(l),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return r},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let r=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new ge.Divert(null));return r.isThread=true,r},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let r=this.Parse(this.DotSeparatedDivertPathComponents);if(!r)return null;this.Whitespace();let a=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let u=new kp.Path(r);return new ge.Divert(u,a)},this.SingleDivert=()=>{let r=this.Parse(this.MultiDivert);if(!r||r.length!==1||r[0]instanceof Rl.TunnelOnwards)return null;let u=r[0];return u.isTunnel?null:u},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let r=0;for(;this.ParseString("->")!==null;)r+=1;return r===0?null:r===1?"->":(r===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let r=this.ParseTempKeyword();this.Whitespace();let a=null;if(r?a=this.Expect(this.IdentifierWithMetadata,"variable name"):a=this.Parse(this.IdentifierWithMetadata),a===null)return null;this.Whitespace();let u=this.ParseString("+")!==null,l=this.ParseString("-")!==null;if(u&&l&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return r&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return u||l?new ts.IncDecExpression(a,h,u):new xo.VariableAssignment({variableIdentifier:a,assignedExpression:h,isTemporaryNewDeclaration:r})},this.DisallowIncrement=r=>{r instanceof ts.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let r=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(r),true):(this.FailRule(r),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let a=this.Parse(this.Expression);return new Nl.ReturnType(a)},this.Expression=(r=0)=>{this.Whitespace();let a=this.ExpressionUnary();if(a===null)return null;for(this.Whitespace();;){let u=this.BeginRule(),l=this.ParseInfixOperator();if(l!==null&&l.precedence>r){let h=`right side of '${l.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(a,l),h);if(c===null)return this.FailRule(u),null;a=this.SucceedRule(u,c);continue}this.FailRule(u);break}return this.Whitespace(),a},this.ExpressionUnary=()=>{let r=this.Parse(this.ExpressionDivertTarget);if(r!==null)return r;let a=this.OneOf([this.String("-"),this.String("!")]);a===null&&(a=this.Parse(this.ExpressionNot)),this.Whitespace();let u=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(u===null&&a!==null&&(u=this.ExpressionUnary()),u===null)return null;a!==null&&(u=Vp.UnaryExpression.WithInner(u,a)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let h=l==="++";if(!(u instanceof Oo.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let c=u;u=new ts.IncDecExpression(c.identifier,h);}}return u},this.ExpressionNot=()=>{let r=this.Identifier();return r==="not"?r:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let r=this.Parse(this.SingleDivert);return !r||r&&r.isThread?null:(this.Whitespace(),new wo.DivertTarget(r))},this.ExpressionInt=()=>{let r=this.ParseInt();return r===null?null:new je.NumberExpression(r,"int")},this.ExpressionFloat=()=>{let r=this.ParseFloat();return r===null?null:new je.NumberExpression(r,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let a=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,a===null?a=[new Ht.Text("")]:a.find(u=>u instanceof ge.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new On.StringExpression(a)},this.ExpressionBool=()=>{let r=this.Parse(this.Identifier);return r==="true"?new je.NumberExpression(true,"bool"):r==="false"?new je.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;this.Whitespace();let a=this.Parse(this.ExpressionFunctionCallArguments);return a===null?null:new Zr.FunctionCall(r,a)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Exclude(this.String(",")),a=this.Interleave(this.Expression,r);return a===null&&(a=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),a},this.ExpressionVariableName=()=>{let r=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return r===null||kl.Story.IsReservedKeyword(r[0].name)?null:new Oo.VariableReference(r)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let r=this.Parse(this.Expression);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),r)},this.ExpressionInfixRight=(r,a)=>{if(!r)return null;this.Whitespace();let u=this.Parse(()=>this.Expression(a.precedence));return u?new vp.BinaryExpression(r,u,a.type):null},this.ParseInfixOperator=()=>{for(let r of this._binaryOperators){let a=this.BeginRule();if(this.ParseString(r.type)!==null){if(r.requireWhitespace&&this.Whitespace()===null){this.FailRule(a);continue}return this.SucceedRule(a,r)}this.FailRule(a);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let r=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new Pl.List(r)},this.ListMember=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;if(this.ParseString(".")!==null){let u=this.Expect(this.IdentifierWithMetadata,`element name within the set ${r}`);r.name+=`.${u?.name}`;}return this.Whitespace(),r},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(r,a,u=false)=>{let l=new Op.InfixOperator(r,a,u);this._binaryOperators.push(l),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,r.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let r=this.Expect(()=>this.ParseUntilCharactersFromString(`
34
34
  \r`),"filename for include statement");r=r.replace(new RegExp(/[ \t]+$/g),"");let a=this.fileHandler.ResolveInkFilename(r,this._filename);if(this.FilenameIsAlreadyOpen(a))return this.Error(`Recursive INCLUDE detected: '${a}' is already open.`),this.ParseUntilCharactersFromString(`\r
35
35
  `),new Ol.IncludedFile(null);this.AddOpenFilename(a);let u=null,l="";try{l=this._rootParser.fileHandler.LoadInkFileContents(a,this._filename);}catch(h){this.Error(`Failed to load: '${r}'.
36
- Error:${h}`);}return l!=null&&(u=new s(l,r,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(a),new Ol.IncludedFile(u)},this.FilenameIsAlreadyOpen=r=>this._rootParser._openFilenames.includes(r),this.AddOpenFilename=r=>{this._rootParser._openFilenames.push(r);},this.RemoveOpenFilename=r=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(r),1);},this.KnotDefinition=()=>{let r=this.Parse(this.KnotDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let a=()=>this.StatementsAtLevel(ht.StatementLevel.Knot),u=this.Expect(a,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new Op.Knot(r.name,u,r.args,r.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata),a,u=r?.name==="function";u?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),a=this.Parse(this.IdentifierWithMetadata)):a=r,a===null&&(this.Error(`Expected the name of the ${u?"function":"knot"}`),a=new On.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new xl.FlowDecl(a,l,u)},this.KnotTitleEquals=()=>{let r=this.ParseCharactersFromString("=");return r===null||r.length<=1?null:r},this.StitchDefinition=()=>{let r=this.Parse(this.StitchDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let a=()=>this.StatementsAtLevel(ht.StatementLevel.Stitch),u=this.Expect(a,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new kp.Stitch(r.name,u,r.args,r.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let r=this.ParseString("function")!==null;r&&this.Whitespace();let a=this.Parse(this.IdentifierWithMetadata);if(a===null)return null;this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new xl.FlowDecl(a,u,r)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new et.CharacterSet("="),null),[new Ht.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),r===null&&(r=[]),r},this.FlowDeclArgument=()=>{let r=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let a=this.ParseDivertArrow();this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(r==null&&u===null)return null;let l=new mp.Argument;return a!==null&&(l.isDivertTarget=true),r!==null&&r.name==="ref"?(u===null&&this.Error("Expected an parameter name after 'ref'"),l.identifier=u,l.isByReference=true):(l.isDivertTarget?l.identifier=u:l.identifier=r,l.identifier===null&&this.Error("Expected an parameter name"),l.isByReference=false),l},this.ExternalDeclaration=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!="EXTERNAL")return null;this.Whitespace();let a=this.Expect(this.IdentifierWithMetadata,"name of external function")||new On.Identifier("");this.Whitespace();let u=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${a}()'`);u===null&&(u=[]);let l=u.map(h=>{var c;return (c=h.identifier)===null||c===void 0?void 0:c.name}).filter(ne.filterUndef);return new Ap.ExternalDeclaration(a,l)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let r=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),a=this.Expect(r,"expression after '~'",this.SkipToNextLine);if(a===null)return new Ct.ContentList;a instanceof bp.Expression&&!(a instanceof Qr.FunctionCall||a instanceof Zr.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
36
+ Error:${h}`);}return l!=null&&(u=new s(l,r,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(a),new Ol.IncludedFile(u)},this.FilenameIsAlreadyOpen=r=>this._rootParser._openFilenames.includes(r),this.AddOpenFilename=r=>{this._rootParser._openFilenames.push(r);},this.RemoveOpenFilename=r=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(r),1);},this.KnotDefinition=()=>{let r=this.Parse(this.KnotDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let a=()=>this.StatementsAtLevel(ht.StatementLevel.Knot),u=this.Expect(a,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new Pp.Knot(r.name,u,r.args,r.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata),a,u=r?.name==="function";u?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),a=this.Parse(this.IdentifierWithMetadata)):a=r,a===null&&(this.Error(`Expected the name of the ${u?"function":"knot"}`),a=new Pn.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new xl.FlowDecl(a,l,u)},this.KnotTitleEquals=()=>{let r=this.ParseCharactersFromString("=");return r===null||r.length<=1?null:r},this.StitchDefinition=()=>{let r=this.Parse(this.StitchDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let a=()=>this.StatementsAtLevel(ht.StatementLevel.Stitch),u=this.Expect(a,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new Rp.Stitch(r.name,u,r.args,r.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let r=this.ParseString("function")!==null;r&&this.Whitespace();let a=this.Parse(this.IdentifierWithMetadata);if(a===null)return null;this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new xl.FlowDecl(a,u,r)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new et.CharacterSet("="),null),[new Ht.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),r===null&&(r=[]),r},this.FlowDeclArgument=()=>{let r=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let a=this.ParseDivertArrow();this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(r==null&&u===null)return null;let l=new gp.Argument;return a!==null&&(l.isDivertTarget=true),r!==null&&r.name==="ref"?(u===null&&this.Error("Expected an parameter name after 'ref'"),l.identifier=u,l.isByReference=true):(l.isDivertTarget?l.identifier=u:l.identifier=r,l.identifier===null&&this.Error("Expected an parameter name"),l.isByReference=false),l},this.ExternalDeclaration=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!="EXTERNAL")return null;this.Whitespace();let a=this.Expect(this.IdentifierWithMetadata,"name of external function")||new Pn.Identifier("");this.Whitespace();let u=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${a}()'`);u===null&&(u=[]);let l=u.map(h=>{var c;return (c=h.identifier)===null||c===void 0?void 0:c.name}).filter(ne.filterUndef);return new _p.ExternalDeclaration(a,l)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let r=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),a=this.Expect(r,"expression after '~'",this.SkipToNextLine);if(a===null)return new Ct.ContentList;a instanceof Ap.Expression&&!(a instanceof Zr.FunctionCall||a instanceof ts.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
37
37
  ~ return
38
38
  ~ var x = blah
39
39
  ~ x++
40
- ~ myFunction()`);let u=(0, ne.asOrNull)(a,Qr.FunctionCall);return u&&(u.shouldPopReturnedValue=true),a.Find(Qr.FunctionCall)()!==null&&(a=new Ct.ContentList(a,new Ht.Text(`
41
- `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),a},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let a=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l?(l instanceof je.NumberExpression||l instanceof xn.StringExpression||l instanceof Fo.DivertTarget||l instanceof xo.VariableReference||l instanceof Pl.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):l instanceof xn.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new wo.VariableAssignment({assignedExpression:l,isGlobalDeclaration:true,variableIdentifier:a})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let a=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let u=this.Expect(this.ListDefinition,"list item names");return u?(u.identifier=new On.Identifier(a.name),new wo.VariableAssignment({variableIdentifier:a,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let r=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return r===null?null:new Pp.ListDefinition(r)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let r=this.ParseString("(")!==null,a=r;this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(u===null)return null;this.Whitespace(),r&&this.ParseString(")")!=null&&(a=false,this.Whitespace());let l=null;if(this.ParseString("=")!==null){this.Whitespace();let h=this.Expect(this.ExpressionInt,"value to be assigned to list item");h!==null&&(l=h.value),a&&(this.Whitespace(),this.ParseString(")")!==null&&(a=false));}return a&&this.Error("Expected closing ')'"),new Tp.ListElementDefinition(u,r,l)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let a=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u instanceof je.NumberExpression||u instanceof Fo.DivertTarget||u instanceof xn.StringExpression?u instanceof xn.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new Sp.ConstantDeclaration(a,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new Fp.Glue(new wp.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let r=this.parsingStringExpression,a=this.tagActive;this.Whitespace();let u=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(u===null)return this.parsingStringExpression=r,null;this.DisallowIncrement(u);let l=(0, ne.asOrNull)(u,Ct.ContentList);return l||(l=new Ct.ContentList(u)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=r,a||this.EndTagIfNecessary(l),l},this.InnerLogic=()=>{this.Whitespace();let r=this.ParseObject(this.SequenceTypeAnnotation);if(r!==null){let l=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return l===null?null:new Il.Sequence(l,r)}let a=this.Parse(this.ConditionExpression);if(a)return this.Expect(()=>this.InnerConditionalContent(a),"conditional content following query");let u=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let l of u){let h=this.BeginRule(),c=this.ParseObject(l);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let r=this.Parse(this.Expression);return r&&(r.outputWhenComplete=true),r},this.IdentifierWithMetadata=()=>{let r=this.Identifier();return r===null?null:new On.Identifier(r)},this.Identifier=()=>{let r=this.ParseCharactersFromCharSet(this.identifierCharSet);if(r===null)return null;let a=true;for(let u of r)if(!(u>="0"&&u<="9")){a=false;break}return a?null:r},this._sequenceTypeSymbols=new et.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let r=tt.SequenceType.Stopping,a=this.Parse(this.SequenceTypeAnnotation);a!==null&&(r=a);let u=this.Parse(this.InnerSequenceObjects);return u===null||u.length<=1?null:new Il.Sequence(u,r)},this.SequenceTypeAnnotation=()=>{let r=this.Parse(this.SequenceTypeSymbolAnnotation);if(r===null&&(r=this.Parse(this.SequenceTypeWordAnnotation)),r===null)return null;switch(r){case tt.SequenceType.Once:case tt.SequenceType.Cycle:case tt.SequenceType.Stopping:case tt.SequenceType.Shuffle:case tt.SequenceType.Shuffle|tt.SequenceType.Stopping:case tt.SequenceType.Shuffle|tt.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${r}`),tt.SequenceType.Stopping}return r},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new et.CharacterSet("!&~$ "));let r=0,a=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(a===null)return null;for(let u of a)switch(u){case "!":r|=tt.SequenceType.Once;break;case "&":r|=tt.SequenceType.Cycle;break;case "~":r|=tt.SequenceType.Shuffle;break;case "$":r|=tt.SequenceType.Stopping;break}return r===0?null:r},this.SequenceTypeWordAnnotation=()=>{let r=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(r===null||r.length===0||this.ParseString(":")===null)return null;let a=0;for(let u of r)a|=u;return a},this.SequenceTypeSingleWord=()=>{let r=null,a=this.Parse(this.IdentifierWithMetadata);if(a!==null)switch(a.name){case "once":r=tt.SequenceType.Once;break;case "cycle":r=tt.SequenceType.Cycle;break;case "shuffle":r=tt.SequenceType.Shuffle;break;case "stopping":r=tt.SequenceType.Stopping;break}return r===null?null:r},this.InnerSequenceObjects=()=>{let r=this.Parse(this.Newline)!==null,a=null;return r?a=this.Parse(this.InnerMultilineSequenceObjects):a=this.Parse(this.InnerInlineSequenceObjects),a},this.InnerInlineSequenceObjects=()=>{let r=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(r===null)return null;let a=[],u=false;for(let l of r)if(l==="|")u||a.push(new Ct.ContentList),u=false;else {let h=l;h===null?this.Error(`Expected content, but got ${l} (this is an ink compiler bug!)`):a.push(new Ct.ContentList(h)),u=true;}return u||a.push(new Ct.ContentList),a},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineSequenceElement);return r===null?null:r},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);return r===null?this.MultilineWhitespace():r.unshift(new Ht.Text(`
40
+ ~ myFunction()`);let u=(0, ne.asOrNull)(a,Zr.FunctionCall);return u&&(u.shouldPopReturnedValue=true),a.Find(Zr.FunctionCall)()!==null&&(a=new Ct.ContentList(a,new Ht.Text(`
41
+ `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),a},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let a=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l?(l instanceof je.NumberExpression||l instanceof On.StringExpression||l instanceof wo.DivertTarget||l instanceof Oo.VariableReference||l instanceof Pl.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):l instanceof On.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new xo.VariableAssignment({assignedExpression:l,isGlobalDeclaration:true,variableIdentifier:a})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let a=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let u=this.Expect(this.ListDefinition,"list item names");return u?(u.identifier=new Pn.Identifier(a.name),new xo.VariableAssignment({variableIdentifier:a,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let r=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return r===null?null:new Tp.ListDefinition(r)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let r=this.ParseString("(")!==null,a=r;this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(u===null)return null;this.Whitespace(),r&&this.ParseString(")")!=null&&(a=false,this.Whitespace());let l=null;if(this.ParseString("=")!==null){this.Whitespace();let h=this.Expect(this.ExpressionInt,"value to be assigned to list item");h!==null&&(l=h.value),a&&(this.Whitespace(),this.ParseString(")")!==null&&(a=false));}return a&&this.Error("Expected closing ')'"),new Np.ListElementDefinition(u,r,l)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let a=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u instanceof je.NumberExpression||u instanceof wo.DivertTarget||u instanceof On.StringExpression?u instanceof On.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new Sp.ConstantDeclaration(a,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new wp.Glue(new xp.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let r=this.parsingStringExpression,a=this.tagActive;this.Whitespace();let u=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(u===null)return this.parsingStringExpression=r,null;this.DisallowIncrement(u);let l=(0, ne.asOrNull)(u,Ct.ContentList);return l||(l=new Ct.ContentList(u)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=r,a||this.EndTagIfNecessary(l),l},this.InnerLogic=()=>{this.Whitespace();let r=this.ParseObject(this.SequenceTypeAnnotation);if(r!==null){let l=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return l===null?null:new Il.Sequence(l,r)}let a=this.Parse(this.ConditionExpression);if(a)return this.Expect(()=>this.InnerConditionalContent(a),"conditional content following query");let u=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let l of u){let h=this.BeginRule(),c=this.ParseObject(l);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let r=this.Parse(this.Expression);return r&&(r.outputWhenComplete=true),r},this.IdentifierWithMetadata=()=>{let r=this.Identifier();return r===null?null:new Pn.Identifier(r)},this.Identifier=()=>{let r=this.ParseCharactersFromCharSet(this.identifierCharSet);if(r===null)return null;let a=true;for(let u of r)if(!(u>="0"&&u<="9")){a=false;break}return a?null:r},this._sequenceTypeSymbols=new et.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let r=tt.SequenceType.Stopping,a=this.Parse(this.SequenceTypeAnnotation);a!==null&&(r=a);let u=this.Parse(this.InnerSequenceObjects);return u===null||u.length<=1?null:new Il.Sequence(u,r)},this.SequenceTypeAnnotation=()=>{let r=this.Parse(this.SequenceTypeSymbolAnnotation);if(r===null&&(r=this.Parse(this.SequenceTypeWordAnnotation)),r===null)return null;switch(r){case tt.SequenceType.Once:case tt.SequenceType.Cycle:case tt.SequenceType.Stopping:case tt.SequenceType.Shuffle:case tt.SequenceType.Shuffle|tt.SequenceType.Stopping:case tt.SequenceType.Shuffle|tt.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${r}`),tt.SequenceType.Stopping}return r},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new et.CharacterSet("!&~$ "));let r=0,a=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(a===null)return null;for(let u of a)switch(u){case "!":r|=tt.SequenceType.Once;break;case "&":r|=tt.SequenceType.Cycle;break;case "~":r|=tt.SequenceType.Shuffle;break;case "$":r|=tt.SequenceType.Stopping;break}return r===0?null:r},this.SequenceTypeWordAnnotation=()=>{let r=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(r===null||r.length===0||this.ParseString(":")===null)return null;let a=0;for(let u of r)a|=u;return a},this.SequenceTypeSingleWord=()=>{let r=null,a=this.Parse(this.IdentifierWithMetadata);if(a!==null)switch(a.name){case "once":r=tt.SequenceType.Once;break;case "cycle":r=tt.SequenceType.Cycle;break;case "shuffle":r=tt.SequenceType.Shuffle;break;case "stopping":r=tt.SequenceType.Stopping;break}return r===null?null:r},this.InnerSequenceObjects=()=>{let r=this.Parse(this.Newline)!==null,a=null;return r?a=this.Parse(this.InnerMultilineSequenceObjects):a=this.Parse(this.InnerInlineSequenceObjects),a},this.InnerInlineSequenceObjects=()=>{let r=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(r===null)return null;let a=[],u=false;for(let l of r)if(l==="|")u||a.push(new Ct.ContentList),u=false;else {let h=l;h===null?this.Error(`Expected content, but got ${l} (this is an ink compiler bug!)`):a.push(new Ct.ContentList(h)),u=true;}return u||a.push(new Ct.ContentList),a},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineSequenceElement);return r===null?null:r},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);return r===null?this.MultilineWhitespace():r.unshift(new Ht.Text(`
42
42
  `)),new Ct.ContentList(r)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=r=>(r===ht.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(r),()=>this.StatementsBreakForLevel(r))),this.StatementAtLevel=r=>{let a=this._statementRulesAtLevel[r],u=this.OneOf(a);return r===ht.StatementLevel.Top&&u instanceof Nl.ReturnType&&this.Error("should not have return statement outside of a knot"),u},this.StatementsBreakForLevel=r=>{this.Whitespace();let a=this._statementBreakRulesAtLevel[r],u=this.OneOf(a);return u===null?null:u},this.GenerateStatementLevelRules=()=>{let r=Object.values(ht.StatementLevel);this._statementRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]);for(let a of r){let u=[],l=[];u.push(this.Line(this.MultiDivert)),a>=ht.StatementLevel.Top&&u.push(this.KnotDefinition),u.push(this.Line(this.Choice)),u.push(this.Line(this.AuthorWarning)),a>ht.StatementLevel.InnerBlock&&u.push(this.Gather),a>=ht.StatementLevel.Knot&&u.push(this.StitchDefinition),u.push(this.Line(this.ListDeclaration)),u.push(this.Line(this.VariableDeclaration)),u.push(this.Line(this.ConstDeclaration)),u.push(this.Line(this.ExternalDeclaration)),u.push(this.Line(this.IncludeStatement)),u.push(this.LogicLine),u.push(this.LineOfMixedTextAndLogic),a<=ht.StatementLevel.Knot&&l.push(this.KnotDeclaration),a<=ht.StatementLevel.Stitch&&l.push(this.StitchDeclaration),a<=ht.StatementLevel.InnerBlock&&(l.push(this.ParseDashNotArrow),l.push(this.String("}"))),this._statementRulesAtLevel[a]=u,this._statementBreakRulesAtLevel[a]=l;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
43
- \r`),this.ParseNewline(),$t.ParseSuccess),this.Line=r=>()=>{let a=this.ParseObject(r);return a===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),a)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let r=null;if(this.tagActive){let a=new Ct.ContentList;a.AddContent(new qe.Tag(false)),a.AddContent(new qe.Tag(true)),r=a;}else r=new qe.Tag(true);return this.tagActive=true,this.Whitespace(),r},this._inlineWhitespaceChars=new et.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?$t.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?$t.ParseSuccess:null),this.MultilineWhitespace=()=>{let r=this.OneOrMore(this.Newline);return r===null?null:r.length>=1?$t.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?$t.ParseSuccess:null,this.Spaced=r=>()=>{this.Whitespace();let a=this.ParseObject(r);return a===null?null:(this.Whitespace(),a)},this.AnyWhitespace=()=>{let r=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)r=true;return r?$t.ParseSuccess:null},this.MultiSpaced=r=>()=>{this.AnyWhitespace();let a=this.ParseObject(r);return a===null?null:(this.AnyWhitespace(),a)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=e,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,o===null?this._fileHandler=new Vp.DefaultFileHandler:this._fileHandler=o,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let r=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(r);}}else this._rootParser=i;}PreProcessInputString(t){return new Dp.CommentEliminator(t).Process()}get parsingStringExpression(){return this.GetFlag(Number(Yr.CustomFlags.ParsingString))}set parsingStringExpression(t){this.SetFlag(Number(Yr.CustomFlags.ParsingString),t);}get tagActive(){return this.GetFlag(Number(Yr.CustomFlags.TagActive))}set tagActive(t){this.SetFlag(Number(Yr.CustomFlags.TagActive),t);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new et.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(t){this.tagActive&&(t!=null&&(t instanceof Ct.ContentList?t.AddContent(new qe.Tag(false)):t.push(new qe.Tag(false))),this.tagActive=false);}};ts.InkParser=W;W.LatinBasic=xt.CharacterRange.Define("A","z",new et.CharacterSet().AddRange("[","`"));W.LatinExtendedA=xt.CharacterRange.Define("\u0100","\u017F");W.LatinExtendedB=xt.CharacterRange.Define("\u0180","\u024F");W.Greek=xt.CharacterRange.Define("\u0370","\u03FF",new et.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));W.Cyrillic=xt.CharacterRange.Define("\u0400","\u04FF",new et.CharacterSet().AddRange("\u0482","\u0489"));W.Armenian=xt.CharacterRange.Define("\u0530","\u058F",new et.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));W.Hebrew=xt.CharacterRange.Define("\u0590","\u05FF",new et.CharacterSet);W.Arabic=xt.CharacterRange.Define("\u0600","\u06FF",new et.CharacterSet);W.Korean=xt.CharacterRange.Define("\uAC00","\uD7AF",new et.CharacterSet);W.Latin1Supplement=xt.CharacterRange.Define("\x80","\xFF",new et.CharacterSet);W.Chinese=xt.CharacterRange.Define("\u4E00","\u9FFF",new et.CharacterSet);W.ListAllCharacterRanges=()=>[W.LatinBasic,W.LatinExtendedA,W.LatinExtendedB,W.Arabic,W.Armenian,W.Cyrillic,W.Greek,W.Hebrew,W.Korean,W.Latin1Supplement,W.Chinese];});var Bl=C(es=>{Object.defineProperty(es,"__esModule",{value:true});es.GenerateStoryStats=void 0;var Bp=we(),Lp=Te(),Wp=un(),qp=Ha(),jp=Ya(),Mp=Yt();function Gp(s){let t=s.FindAll(Mp.Text)(),e=0;for(let u of t){let l=0,h=true;for(let c of u.text)c==" "||c==" "||c==`
44
- `||c=="\r"?h=true:h&&(l++,h=false);e+=l;}let n=s.FindAll(qp.Knot)(),i=s.FindAll(jp.Stitch)(),o=s.FindAll(Bp.Choice)(),r=s.FindAll(Wp.Gather)(u=>u.debugMetadata!=null),a=s.FindAll(Lp.Divert)();return {words:e,knots:n.length,functions:n.filter(u=>u.isFunction).length,stitches:i.length,gathers:r.length,diverts:a.length-1,choices:o.length}}es.GenerateStoryStats=Gp;});var Ll=C(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.JsonFileHandler=void 0;var Po=class{constructor(t){this.fileHierarchy=t,this.ResolveInkFilename=e=>{if(Object.keys(this.fileHierarchy).includes(e))return e;throw new Error(`Cannot locate ${e}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=e=>{if(Object.keys(this.fileHierarchy).includes(e))return this.fileHierarchy[e];throw new Error(`Cannot open ${e}.`)};}};ns.JsonFileHandler=Po;});var ql=C(ot=>{Object.defineProperty(ot,"__esModule",{value:true});ot.Compiler=ot.Story=ot.InkList=ot.JsonFileHandler=ot.StatementLevel=ot.InkParser=ot.CompilerOptions=void 0;var $p=fs(),Hp=Jo(),To=$e(),Up=Oo(),Kp=$(),Jp=L(),zp=Bl(),Xp=fs();Object.defineProperty(ot,"CompilerOptions",{enumerable:true,get:function(){return Xp.CompilerOptions}});var Yp=Oo();Object.defineProperty(ot,"InkParser",{enumerable:true,get:function(){return Yp.InkParser}});var Qp=za();Object.defineProperty(ot,"StatementLevel",{enumerable:true,get:function(){return Qp.StatementLevel}});var Zp=Ll();Object.defineProperty(ot,"JsonFileHandler",{enumerable:true,get:function(){return Zp.JsonFileHandler}});var Wl=vn();Object.defineProperty(ot,"InkList",{enumerable:true,get:function(){return Wl.InkList}});Object.defineProperty(ot,"Story",{enumerable:true,get:function(){return Wl.Story}});var No=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(t,e=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new Up.InkParser(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),this.errors.length===0?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var n;for(let i of this.runtimeStory.state.outputStream){let o=(0, Jp.asOrNull)(i,Kp.StringValue);if(o!==null){let r=new Hp.DebugSourceRange(((n=o.value)===null||n===void 0?void 0:n.length)||0,o.debugMetadata,o.value||"unknown");this.debugSourceRanges.push(r);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, zp.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let i=0,o=null;for(let r of this.debugSourceRanges){if(r.debugMetadata!==null&&(o=r.debugMetadata),n>=i&&n<i+r.length)return o;i+=r.length;}return null},this.OnError=(n,i)=>{switch(i){case To.ErrorType.Author:this._authorMessages.push(n);break;case To.ErrorType.Warning:this._warnings.push(n);break;case To.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=t,this._options=e||new $p.CompilerOptions;}};ot.Compiler=No;});var Ce;(i=>(i.log=(o,...r)=>console.log(`[Pixi\u2019VN Ink] ${o}`,...r),i.warn=(o,...r)=>console.warn(`[Pixi\u2019VN Ink] ${o}`,...r),i.error=(o,...r)=>console.error(`[Pixi\u2019VN Ink] ${o}`,...r),i.info=(o,...r)=>console.info(`[Pixi\u2019VN Ink] ${o}`,...r)))(Ce||={});var Yl=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Ql=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,Zl=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,rs={Space_Separator:Yl,ID_Start:Ql,ID_Continue:Zl},U={isSpaceSeparator(s){return typeof s=="string"&&rs.Space_Separator.test(s)},isIdStartChar(s){return typeof s=="string"&&(s>="a"&&s<="z"||s>="A"&&s<="Z"||s==="$"||s==="_"||rs.ID_Start.test(s))},isIdContinueChar(s){return typeof s=="string"&&(s>="a"&&s<="z"||s>="A"&&s<="Z"||s>="0"&&s<="9"||s==="$"||s==="_"||s==="\u200C"||s==="\u200D"||rs.ID_Continue.test(s))},isDigit(s){return typeof s=="string"&&/[0-9]/.test(s)},isHexDigit(s){return typeof s=="string"&&/[0-9A-Fa-f]/.test(s)}},as,ut,qt,In,Ut,Ft,Y,ls,Ge,th=function(t,e){as=String(t),ut="start",qt=[],In=0,Ut=1,Ft=0,Y=void 0,ls=void 0,Ge=void 0;do Y=eh(),rh[ut]();while(Y.type!=="eof");return typeof e=="function"?os({"":Ge},"",e):Ge};function os(s,t,e){let n=s[t];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=String(i),r=os(n,o,e);r===void 0?delete n[o]:Object.defineProperty(n,o,{value:r,writable:true,enumerable:true,configurable:true});}else for(let i in n){let o=os(n,i,e);o===void 0?delete n[i]:Object.defineProperty(n,i,{value:o,writable:true,enumerable:true,configurable:true});}return e.call(s,t,n)}var O,w,Me,Wt,N;function eh(){for(O="default",w="",Me=false,Wt=1;;){N=jt();let s=Wo[O]();if(s)return s}}function jt(){if(as[In])return String.fromCodePoint(as.codePointAt(In))}function g(){let s=jt();return s===`
45
- `?(Ut++,Ft=0):s?Ft+=s.length:Ft++,s&&(In+=s.length),s}var Wo={default(){switch(N){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
46
- `:case "\r":case "\u2028":case "\u2029":g();return;case "/":g(),O="comment";return;case void 0:return g(),q("eof")}if(U.isSpaceSeparator(N)){g();return}return Wo[ut]()},comment(){switch(N){case "*":g(),O="multiLineComment";return;case "/":g(),O="singleLineComment";return}throw j(g())},multiLineComment(){switch(N){case "*":g(),O="multiLineCommentAsterisk";return;case void 0:throw j(g())}g();},multiLineCommentAsterisk(){switch(N){case "*":g();return;case "/":g(),O="default";return;case void 0:throw j(g())}g(),O="multiLineComment";},singleLineComment(){switch(N){case `
47
- `:case "\r":case "\u2028":case "\u2029":g(),O="default";return;case void 0:return g(),q("eof")}g();},value(){switch(N){case "{":case "[":return q("punctuator",g());case "n":return g(),ie("ull"),q("null",null);case "t":return g(),ie("rue"),q("boolean",true);case "f":return g(),ie("alse"),q("boolean",false);case "-":case "+":g()==="-"&&(Wt=-1),O="sign";return;case ".":w=g(),O="decimalPointLeading";return;case "0":w=g(),O="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":w=g(),O="decimalInteger";return;case "I":return g(),ie("nfinity"),q("numeric",1/0);case "N":return g(),ie("aN"),q("numeric",NaN);case '"':case "'":Me=g()==='"',w="",O="string";return}throw j(g())},identifierNameStartEscape(){if(N!=="u")throw j(g());g();let s=us();switch(s){case "$":case "_":break;default:if(!U.isIdStartChar(s))throw Lo();break}w+=s,O="identifierName";},identifierName(){switch(N){case "$":case "_":case "\u200C":case "\u200D":w+=g();return;case "\\":g(),O="identifierNameEscape";return}if(U.isIdContinueChar(N)){w+=g();return}return q("identifier",w)},identifierNameEscape(){if(N!=="u")throw j(g());g();let s=us();switch(s){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!U.isIdContinueChar(s))throw Lo();break}w+=s,O="identifierName";},sign(){switch(N){case ".":w=g(),O="decimalPointLeading";return;case "0":w=g(),O="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":w=g(),O="decimalInteger";return;case "I":return g(),ie("nfinity"),q("numeric",Wt*(1/0));case "N":return g(),ie("aN"),q("numeric",NaN)}throw j(g())},zero(){switch(N){case ".":w+=g(),O="decimalPoint";return;case "e":case "E":w+=g(),O="decimalExponent";return;case "x":case "X":w+=g(),O="hexadecimal";return}return q("numeric",Wt*0)},decimalInteger(){switch(N){case ".":w+=g(),O="decimalPoint";return;case "e":case "E":w+=g(),O="decimalExponent";return}if(U.isDigit(N)){w+=g();return}return q("numeric",Wt*Number(w))},decimalPointLeading(){if(U.isDigit(N)){w+=g(),O="decimalFraction";return}throw j(g())},decimalPoint(){switch(N){case "e":case "E":w+=g(),O="decimalExponent";return}if(U.isDigit(N)){w+=g(),O="decimalFraction";return}return q("numeric",Wt*Number(w))},decimalFraction(){switch(N){case "e":case "E":w+=g(),O="decimalExponent";return}if(U.isDigit(N)){w+=g();return}return q("numeric",Wt*Number(w))},decimalExponent(){switch(N){case "+":case "-":w+=g(),O="decimalExponentSign";return}if(U.isDigit(N)){w+=g(),O="decimalExponentInteger";return}throw j(g())},decimalExponentSign(){if(U.isDigit(N)){w+=g(),O="decimalExponentInteger";return}throw j(g())},decimalExponentInteger(){if(U.isDigit(N)){w+=g();return}return q("numeric",Wt*Number(w))},hexadecimal(){if(U.isHexDigit(N)){w+=g(),O="hexadecimalInteger";return}throw j(g())},hexadecimalInteger(){if(U.isHexDigit(N)){w+=g();return}return q("numeric",Wt*Number(w))},string(){switch(N){case "\\":g(),w+=nh();return;case '"':if(Me)return g(),q("string",w);w+=g();return;case "'":if(!Me)return g(),q("string",w);w+=g();return;case `
48
- `:case "\r":throw j(g());case "\u2028":case "\u2029":sh(N);break;case void 0:throw j(g())}w+=g();},start(){switch(N){case "{":case "[":return q("punctuator",g())}O="value";},beforePropertyName(){switch(N){case "$":case "_":w=g(),O="identifierName";return;case "\\":g(),O="identifierNameStartEscape";return;case "}":return q("punctuator",g());case '"':case "'":Me=g()==='"',O="string";return}if(U.isIdStartChar(N)){w+=g(),O="identifierName";return}throw j(g())},afterPropertyName(){if(N===":")return q("punctuator",g());throw j(g())},beforePropertyValue(){O="value";},afterPropertyValue(){switch(N){case ",":case "}":return q("punctuator",g())}throw j(g())},beforeArrayValue(){if(N==="]")return q("punctuator",g());O="value";},afterArrayValue(){switch(N){case ",":case "]":return q("punctuator",g())}throw j(g())},end(){throw j(g())}};function q(s,t){return {type:s,value:t,line:Ut,column:Ft}}function ie(s){for(let t of s){if(jt()!==t)throw j(g());g();}}function nh(){switch(jt()){case "b":return g(),"\b";case "f":return g(),"\f";case "n":return g(),`
49
- `;case "r":return g(),"\r";case "t":return g()," ";case "v":return g(),"\v";case "0":if(g(),U.isDigit(jt()))throw j(g());return "\0";case "x":return g(),ih();case "u":return g(),us();case `
50
- `:case "\u2028":case "\u2029":return g(),"";case "\r":return g(),jt()===`
51
- `&&g(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw j(g());case void 0:throw j(g())}return g()}function ih(){let s="",t=jt();if(!U.isHexDigit(t)||(s+=g(),t=jt(),!U.isHexDigit(t)))throw j(g());return s+=g(),String.fromCodePoint(parseInt(s,16))}function us(){let s="",t=4;for(;t-- >0;){let e=jt();if(!U.isHexDigit(e))throw j(g());s+=g();}return String.fromCodePoint(parseInt(s,16))}var rh={start(){if(Y.type==="eof")throw re();ss();},beforePropertyName(){switch(Y.type){case "identifier":case "string":ls=Y.value,ut="afterPropertyName";return;case "punctuator":Nn();return;case "eof":throw re()}},afterPropertyName(){if(Y.type==="eof")throw re();ut="beforePropertyValue";},beforePropertyValue(){if(Y.type==="eof")throw re();ss();},beforeArrayValue(){if(Y.type==="eof")throw re();if(Y.type==="punctuator"&&Y.value==="]"){Nn();return}ss();},afterPropertyValue(){if(Y.type==="eof")throw re();switch(Y.value){case ",":ut="beforePropertyName";return;case "}":Nn();}},afterArrayValue(){if(Y.type==="eof")throw re();switch(Y.value){case ",":ut="beforeArrayValue";return;case "]":Nn();}},end(){}};function ss(){let s;switch(Y.type){case "punctuator":switch(Y.value){case "{":s={};break;case "[":s=[];break}break;case "null":case "boolean":case "numeric":case "string":s=Y.value;break}if(Ge===void 0)Ge=s;else {let t=qt[qt.length-1];Array.isArray(t)?t.push(s):Object.defineProperty(t,ls,{value:s,writable:true,enumerable:true,configurable:true});}if(s!==null&&typeof s=="object")qt.push(s),Array.isArray(s)?ut="beforeArrayValue":ut="beforePropertyName";else {let t=qt[qt.length-1];t==null?ut="end":Array.isArray(t)?ut="afterArrayValue":ut="afterPropertyValue";}}function Nn(){qt.pop();let s=qt[qt.length-1];s==null?ut="end":Array.isArray(s)?ut="afterArrayValue":ut="afterPropertyValue";}function j(s){return kn(s===void 0?`JSON5: invalid end of input at ${Ut}:${Ft}`:`JSON5: invalid character '${qo(s)}' at ${Ut}:${Ft}`)}function re(){return kn(`JSON5: invalid end of input at ${Ut}:${Ft}`)}function Lo(){return Ft-=5,kn(`JSON5: invalid identifier character at ${Ut}:${Ft}`)}function sh(s){console.warn(`JSON5: '${qo(s)}' in strings is not valid ECMAScript; consider escaping`);}function qo(s){let t={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(t[s])return t[s];if(s<" "){let e=s.charCodeAt(0).toString(16);return "\\x"+("00"+e).substring(e.length)}return s}function kn(s){let t=new SyntaxError(s);return t.lineNumber=Ut,t.columnNumber=Ft,t}var ah=function(t,e,n){let i=[],o="",r,a,u="",l;if(e!=null&&typeof e=="object"&&!Array.isArray(e)&&(n=e.space,l=e.quote,e=e.replacer),typeof e=="function")a=e;else if(Array.isArray(e)){r=[];for(let v of e){let A;typeof v=="string"?A=v:(typeof v=="number"||v instanceof String||v instanceof Number)&&(A=String(v)),A!==void 0&&r.indexOf(A)<0&&r.push(A);}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),u=" ".substr(0,n)):typeof n=="string"&&(u=n.substr(0,10)),h("",{"":t});function h(v,A){let S=A[v];switch(S!=null&&(typeof S.toJSON5=="function"?S=S.toJSON5(v):typeof S.toJSON=="function"&&(S=S.toJSON(v))),a&&(S=a.call(A,v,S)),S instanceof Number?S=Number(S):S instanceof String?S=String(S):S instanceof Boolean&&(S=S.valueOf()),S){case null:return "null";case true:return "true";case false:return "false"}if(typeof S=="string")return c(S);if(typeof S=="number")return String(S);if(typeof S=="object")return Array.isArray(S)?D(S):d(S)}function c(v){let A={"'":.1,'"':.2},S={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},k="";for(let y=0;y<v.length;y++){let p=v[y];switch(p){case "'":case '"':A[p]++,k+=p;continue;case "\0":if(U.isDigit(v[y+1])){k+="\\x00";continue}}if(S[p]){k+=S[p];continue}if(p<" "){let E=p.charCodeAt(0).toString(16);k+="\\x"+("00"+E).substring(E.length);continue}k+=p;}let f=l||Object.keys(A).reduce((y,p)=>A[y]<A[p]?y:p);return k=k.replace(new RegExp(f,"g"),S[f]),f+k+f}function d(v){if(i.indexOf(v)>=0)throw TypeError("Converting circular structure to JSON5");i.push(v);let A=o;o=o+u;let S=r||Object.keys(v),k=[];for(let y of S){let p=h(y,v);if(p!==void 0){let E=m(y)+":";u!==""&&(E+=" "),E+=p,k.push(E);}}let f;if(k.length===0)f="{}";else {let y;if(u==="")y=k.join(","),f="{"+y+"}";else {let p=`,
52
- `+o;y=k.join(p),f=`{
53
- `+o+y+`,
54
- `+A+"}";}}return i.pop(),o=A,f}function m(v){if(v.length===0)return c(v);let A=String.fromCodePoint(v.codePointAt(0));if(!U.isIdStartChar(A))return c(v);for(let S=A.length;S<v.length;S++)if(!U.isIdContinueChar(String.fromCodePoint(v.codePointAt(S))))return c(v);return v}function D(v){if(i.indexOf(v)>=0)throw TypeError("Converting circular structure to JSON5");i.push(v);let A=o;o=o+u;let S=[];for(let f=0;f<v.length;f++){let y=h(String(f),v);S.push(y!==void 0?y:"null");}let k;if(S.length===0)k="[]";else if(u==="")k="["+S.join(",")+"]";else {let f=`,
55
- `+o,y=S.join(f);k=`[
56
- `+o+y+`,
57
- `+A+"]";}return i.pop(),o=A,k}},oh={parse:th,stringify:ah},uh=oh,hs=uh;var Mo="\xA7SPACE\xA7",Go="\xA7DOUBLE_QUOTES\xA7",$o="\xA7QUOTES\xA7",Ho="SPECIAL_\xA7QUOTES\xA7",Uo="\xA7CURLY_BRACKETS1\xA7",lh="\xA7INK_VAR\xA7",Ko="\xA7CURLY_BRACKETS2\xA7",cs;(k=>{let s=[],t=[];async function e(f,y){for(let p=0;p<s.length;p++)try{let{validation:E}=s[p].opts;if(E instanceof RegExp){if(!E.test(f.join(" ")))continue}else if(E instanceof ZodType&&!E.safeParse(f).success)continue;let _=await s[p].fn(f,y,c);if(_===!0||typeof _=="string")return _}catch{}return false}function n(f,y={name:"custom-command",validation:/^/}){s.unshift({fn:f,opts:y});}k.add=n;function i(){return [...t.map(f=>f.opts),...s.map(f=>f.opts)]}k.info=i;function o(f,y){t.unshift({fn:f,opts:y});}k.addMapper=o;function r(){s.length=0;}k.clear=r;function a(){t.length=0;}k.clearMappers=a;async function u(f,y,p){try{let E=l(f),_=await e(E,p);return _===!0?void 0:typeof _=="string"?(_.startsWith("#")&&(_=_.substring(1)),await k.run(_,y,p)):h(E,y)}catch(E){throw Ce.error("Error parsing ink hashtag-command",f),E}}k.run=u;function l(f,y){if(f=f.replaceAll('\\"',Go),f=f.replaceAll("\\'",$o),f=f.replaceAll("\\`",Ho),f=f.replaceAll("\\{",Uo),f=f.replaceAll("\\}",Ko),y?.mergeInkVariables){let x;do x=f,f=f.replace(/\{[^{}:]*\}/g,lh);while(f!==x)}f=f.replaceAll("{"," { "),f=f.replaceAll("}"," } "),f=f.replaceAll(Uo,"{"),f=f.replaceAll(Ko,"}");let p=[],E,_="";for(let x=0;x<f.length;x++){let R=f[x];R==='"'||R==="'"||R==="`"?E===void 0?(p.push(_),_="",E=R,_+=R):E===R?(E=void 0,_+=R,p.push(_),_=""):_+=R:_+=R;}return _!==""&&p.push(_),p.forEach((x,R)=>{R%2===1&&(p[R]=x.replaceAll(" ",Mo));}),f=p.join(""),p=f.split(" ").filter(x=>x!==""),p=p.map(x=>x.replaceAll(Mo," ").replaceAll(Go,'"').replaceAll($o,"'").replaceAll(Ho,"`")),p=v(p),p=p.map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")||x.startsWith("`")&&x.endsWith("`")?x.slice(1,-1):x),p}k.convertTagTolist=l;function h(f,y,p){for(let E of t){let{validation:_}=E.opts,x=false;if(_ instanceof RegExp?x=_.test(f.join(" ")):_ instanceof ZodType&&(x=_.safeParse(f).success),x)return E.fn(f,y)}p?.silent||Ce.error("The operation is not valid",f);}k.convertOperation=h;function c(f){return d(f)}k.convertListStringToObj=c;function d(f){if(f.length===0)return {};if(f.length%2!==0)throw Ce.error("The props list must have a pair number of elements",f),new Error("The props list must have a pair number of elements");let y="{";f.forEach((p,E)=>{if(E%2===0)y+=`"${p}": `;else {switch(p){case "null":case "undefined":case "true":case "false":y+=`${p}`;break;default:D(p)?(p=m(p),y+=`"${p}"`):p.startsWith("{")&&p.endsWith("}")?y+=`${p}`:p.startsWith('"')&&p.endsWith('"')?y+=`${p}`:Number.isNaN(parseFloat(p))?y+=`"${p}"`:y+=`${p}`;}E<f.length-1&&(y+=", ");}}),y+="}";try{return hs.parse(y)}catch(p){throw Ce.error("Error parsing ink json",y),p}}function m(f){return f.startsWith('"')&&f.endsWith('"')||f.startsWith("'")&&f.endsWith("'")||f.startsWith("`")&&f.endsWith("`")?f.substring(1,f.length-1):f}function D(f){return !!(f.startsWith('"')&&f.endsWith('"')||f.startsWith("'")&&f.endsWith("'")||f.startsWith("`")&&f.endsWith("`"))}function v(f){return A(f).tokens}k.mergeJsonBlocks=v;function A(f){let y=[],p=false;for(let E=0;E<f.length;E++){let _=f[E];if(_!=="{"){y.push(_);continue}let x=S(f,E);if(x===-1){y.push(_);continue}let R=A(f.slice(E+1,x)),X=["{",...R.tokens,"}"],vt=X.join(" ");if(!R.hasInvalidMatchedBlock)try{hs.parse(vt),y.push(vt),E=x;continue}catch{}p=true,y.push(...X),E=x;}return {tokens:y,hasInvalidMatchedBlock:p}}function S(f,y){let p=0;for(let E=y;E<f.length;E++)if(f[E]==="{")p++;else if(f[E]==="}"&&(p--,p===0))return E;return -1}})(cs||={});var Ml=Bo(ql()),Gl=Bo($e()),tm=/(?:^|<>)\s*#\s*([^\r\n]+)/g,em=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,nm=new Set(["DONE","END"]),im="_|_",jl=new Map;function $l(s,t){let e=JSON.stringify([t,s]),n=jl.get(e);if(n)return n;let i=new RegExp(s,t);return jl.set(e,i),i}function Pn(s,t){if(!t||typeof t!="object")return false;let e=t,n=e.anyOf;if(Array.isArray(n))return n.some(r=>Pn(s,r));let i=e.oneOf;if(Array.isArray(i))return i.some(r=>Pn(s,r));let o=e.allOf;if(Array.isArray(o))return o.every(r=>Pn(s,r));if(typeof e.const=="string")return s===e.const;if(Array.isArray(e.enum))return e.enum.some(r=>typeof r=="string"&&r===s);if(e.type!=="string"||typeof e.minLength=="number"&&s.length<e.minLength||typeof e.maxLength=="number"&&s.length>e.maxLength)return false;if(typeof e.pattern=="string")try{if(!$l(e.pattern,"").test(s))return !1}catch{return false}return true}function is(s,t){if(!t||typeof t!="object")return false;let e=t,n=e.anyOf;if(Array.isArray(n))return n.some(a=>is(s,a));let i=e.oneOf;if(Array.isArray(i))return i.some(a=>is(s,a));let o=e.allOf;if(Array.isArray(o))return o.every(a=>is(s,a));if(e.type!=="array"||typeof e.minItems=="number"&&s.length<e.minItems||typeof e.maxItems=="number"&&s.length>e.maxItems)return false;let r=Array.isArray(e.prefixItems)?e.prefixItems:[];if(s.length<r.length)return false;for(let a=0;a<r.length;a++)if(!Pn(s[a],r[a]))return false;return s.length===r.length?true:e.items===false||typeof e.items>"u"?false:e.items===true?true:s.slice(r.length).every(a=>Pn(a,e.items))}function rm(s,t){if(t.type==="regexp")try{let e=$l(t.source,t.flags);return e.lastIndex=0,e.test(s.join(" "))}catch{return false}return t.type==="literal"?s.join(" ")===t.value:is(s,t.schema)}function sm(s){let t=s.split(/\r?\n/),e=[];for(let n=0;n<t.length;n++){let i=t[n];for(let o of i.matchAll(tm)){let r=(o[1]??"").trim();if(!r)continue;let a=cs.convertTagTolist(r,{mergeInkVariables:true});a.length!==0&&e.push({line:n+1,command:r,tokens:a});}}return e}var am;(i=>{function s(o,r={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let a=[];try{return {json:new Ml.Compiler(o,{errorHandler:(c,d)=>{let m=c.replace(/^[A-Z]+: line \d+: ?/,""),D=c.match(/line (\d+)/);a.push({message:m,type:d,line:D?Number(D[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:c=>c,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:a}}catch{let l=false,h={...r,textSource:o};return t(a,()=>{l=true;},h),l?s(h.textSource,r):{issues:a}}}i.compile=s;function t(o,r,a){let{functions:u,initialVarsToRemove:l,labelToRemove:h}=a,c=o.find(d=>d.type===Gl.ErrorType.Error);if(c){if(c.message.includes("Divert target not found")){let d=c.message.match(/Divert target not found: '-> (\w+)'/);if(d?.[1]){let m=d[1],D=`
43
+ \r`),this.ParseNewline(),$t.ParseSuccess),this.Line=r=>()=>{let a=this.ParseObject(r);return a===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),a)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let r=null;if(this.tagActive){let a=new Ct.ContentList;a.AddContent(new qe.Tag(false)),a.AddContent(new qe.Tag(true)),r=a;}else r=new qe.Tag(true);return this.tagActive=true,this.Whitespace(),r},this._inlineWhitespaceChars=new et.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?$t.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?$t.ParseSuccess:null),this.MultilineWhitespace=()=>{let r=this.OneOrMore(this.Newline);return r===null?null:r.length>=1?$t.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?$t.ParseSuccess:null,this.Spaced=r=>()=>{this.Whitespace();let a=this.ParseObject(r);return a===null?null:(this.Whitespace(),a)},this.AnyWhitespace=()=>{let r=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)r=true;return r?$t.ParseSuccess:null},this.MultiSpaced=r=>()=>{this.AnyWhitespace();let a=this.ParseObject(r);return a===null?null:(this.AnyWhitespace(),a)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=e,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,o===null?this._fileHandler=new Bp.DefaultFileHandler:this._fileHandler=o,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let r=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(r);}}else this._rootParser=i;}PreProcessInputString(t){return new Ep.CommentEliminator(t).Process()}get parsingStringExpression(){return this.GetFlag(Number(Qr.CustomFlags.ParsingString))}set parsingStringExpression(t){this.SetFlag(Number(Qr.CustomFlags.ParsingString),t);}get tagActive(){return this.GetFlag(Number(Qr.CustomFlags.TagActive))}set tagActive(t){this.SetFlag(Number(Qr.CustomFlags.TagActive),t);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new et.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(t){this.tagActive&&(t!=null&&(t instanceof Ct.ContentList?t.AddContent(new qe.Tag(false)):t.push(new qe.Tag(false))),this.tagActive=false);}};es.InkParser=q;q.LatinBasic=xt.CharacterRange.Define("A","z",new et.CharacterSet().AddRange("[","`"));q.LatinExtendedA=xt.CharacterRange.Define("\u0100","\u017F");q.LatinExtendedB=xt.CharacterRange.Define("\u0180","\u024F");q.Greek=xt.CharacterRange.Define("\u0370","\u03FF",new et.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));q.Cyrillic=xt.CharacterRange.Define("\u0400","\u04FF",new et.CharacterSet().AddRange("\u0482","\u0489"));q.Armenian=xt.CharacterRange.Define("\u0530","\u058F",new et.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));q.Hebrew=xt.CharacterRange.Define("\u0590","\u05FF",new et.CharacterSet);q.Arabic=xt.CharacterRange.Define("\u0600","\u06FF",new et.CharacterSet);q.Korean=xt.CharacterRange.Define("\uAC00","\uD7AF",new et.CharacterSet);q.Latin1Supplement=xt.CharacterRange.Define("\x80","\xFF",new et.CharacterSet);q.Chinese=xt.CharacterRange.Define("\u4E00","\u9FFF",new et.CharacterSet);q.ListAllCharacterRanges=()=>[q.LatinBasic,q.LatinExtendedA,q.LatinExtendedB,q.Arabic,q.Armenian,q.Cyrillic,q.Greek,q.Hebrew,q.Korean,q.Latin1Supplement,q.Chinese];});var Bl=C(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.GenerateStoryStats=void 0;var Lp=we(),Wp=Te(),qp=ln(),jp=Ua(),Mp=Qa(),Gp=Yt();function $p(s){let t=s.FindAll(Gp.Text)(),e=0;for(let u of t){let l=0,h=true;for(let c of u.text)c==" "||c==" "||c==`
44
+ `||c=="\r"?h=true:h&&(l++,h=false);e+=l;}let n=s.FindAll(jp.Knot)(),i=s.FindAll(Mp.Stitch)(),o=s.FindAll(Lp.Choice)(),r=s.FindAll(qp.Gather)(u=>u.debugMetadata!=null),a=s.FindAll(Wp.Divert)();return {words:e,knots:n.length,functions:n.filter(u=>u.isFunction).length,stitches:i.length,gathers:r.length,diverts:a.length-1,choices:o.length}}ns.GenerateStoryStats=$p;});var Ll=C(is=>{Object.defineProperty(is,"__esModule",{value:true});is.JsonFileHandler=void 0;var To=class{constructor(t){this.fileHierarchy=t,this.ResolveInkFilename=e=>{if(Object.keys(this.fileHierarchy).includes(e))return e;throw new Error(`Cannot locate ${e}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=e=>{if(Object.keys(this.fileHierarchy).includes(e))return this.fileHierarchy[e];throw new Error(`Cannot open ${e}.`)};}};is.JsonFileHandler=To;});var ql=C(ot=>{Object.defineProperty(ot,"__esModule",{value:true});ot.Compiler=ot.Story=ot.InkList=ot.JsonFileHandler=ot.StatementLevel=ot.InkParser=ot.CompilerOptions=void 0;var Hp=ps(),Up=Jo(),No=He(),Kp=Po(),Jp=H(),zp=W(),Xp=Bl(),Yp=ps();Object.defineProperty(ot,"CompilerOptions",{enumerable:true,get:function(){return Yp.CompilerOptions}});var Qp=Po();Object.defineProperty(ot,"InkParser",{enumerable:true,get:function(){return Qp.InkParser}});var Zp=Xa();Object.defineProperty(ot,"StatementLevel",{enumerable:true,get:function(){return Zp.StatementLevel}});var tm=Ll();Object.defineProperty(ot,"JsonFileHandler",{enumerable:true,get:function(){return tm.JsonFileHandler}});var Wl=Dn();Object.defineProperty(ot,"InkList",{enumerable:true,get:function(){return Wl.InkList}});Object.defineProperty(ot,"Story",{enumerable:true,get:function(){return Wl.Story}});var Io=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(t,e=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new Kp.InkParser(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),this.errors.length===0?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var n;for(let i of this.runtimeStory.state.outputStream){let o=(0, zp.asOrNull)(i,Jp.StringValue);if(o!==null){let r=new Up.DebugSourceRange(((n=o.value)===null||n===void 0?void 0:n.length)||0,o.debugMetadata,o.value||"unknown");this.debugSourceRanges.push(r);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, Xp.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let i=0,o=null;for(let r of this.debugSourceRanges){if(r.debugMetadata!==null&&(o=r.debugMetadata),n>=i&&n<i+r.length)return o;i+=r.length;}return null},this.OnError=(n,i)=>{switch(i){case No.ErrorType.Author:this._authorMessages.push(n);break;case No.ErrorType.Warning:this._warnings.push(n);break;case No.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=t,this._options=e||new Hp.CompilerOptions;}};ot.Compiler=Io;});var Ce;(i=>(i.log=(o,...r)=>console.log(`[Pixi\u2019VN Ink] ${o}`,...r),i.warn=(o,...r)=>console.warn(`[Pixi\u2019VN Ink] ${o}`,...r),i.error=(o,...r)=>console.error(`[Pixi\u2019VN Ink] ${o}`,...r),i.info=(o,...r)=>console.info(`[Pixi\u2019VN Ink] ${o}`,...r)))(Ce||={});var Ql=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Zl=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,th=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,ss={Space_Separator:Ql,ID_Start:Zl,ID_Continue:th},K={isSpaceSeparator(s){return typeof s=="string"&&ss.Space_Separator.test(s)},isIdStartChar(s){return typeof s=="string"&&(s>="a"&&s<="z"||s>="A"&&s<="Z"||s==="$"||s==="_"||ss.ID_Start.test(s))},isIdContinueChar(s){return typeof s=="string"&&(s>="a"&&s<="z"||s>="A"&&s<="Z"||s>="0"&&s<="9"||s==="$"||s==="_"||s==="\u200C"||s==="\u200D"||ss.ID_Continue.test(s))},isDigit(s){return typeof s=="string"&&/[0-9]/.test(s)},isHexDigit(s){return typeof s=="string"&&/[0-9A-Fa-f]/.test(s)}},os,ut,qt,kn,Ut,Ft,Y,hs,$e,eh=function(t,e){os=String(t),ut="start",qt=[],kn=0,Ut=1,Ft=0,Y=void 0,hs=void 0,$e=void 0;do Y=nh(),sh[ut]();while(Y.type!=="eof");return typeof e=="function"?us({"":$e},"",e):$e};function us(s,t,e){let n=s[t];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let i=0;i<n.length;i++){let o=String(i),r=us(n,o,e);r===void 0?delete n[o]:Object.defineProperty(n,o,{value:r,writable:true,enumerable:true,configurable:true});}else for(let i in n){let o=us(n,i,e);o===void 0?delete n[i]:Object.defineProperty(n,i,{value:o,writable:true,enumerable:true,configurable:true});}return e.call(s,t,n)}var O,x,Ge,Wt,I;function nh(){for(O="default",x="",Ge=false,Wt=1;;){I=jt();let s=Wo[O]();if(s)return s}}function jt(){if(os[kn])return String.fromCodePoint(os.codePointAt(kn))}function f(){let s=jt();return s===`
45
+ `?(Ut++,Ft=0):s?Ft+=s.length:Ft++,s&&(kn+=s.length),s}var Wo={default(){switch(I){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
46
+ `:case "\r":case "\u2028":case "\u2029":f();return;case "/":f(),O="comment";return;case void 0:return f(),j("eof")}if(K.isSpaceSeparator(I)){f();return}return Wo[ut]()},comment(){switch(I){case "*":f(),O="multiLineComment";return;case "/":f(),O="singleLineComment";return}throw M(f())},multiLineComment(){switch(I){case "*":f(),O="multiLineCommentAsterisk";return;case void 0:throw M(f())}f();},multiLineCommentAsterisk(){switch(I){case "*":f();return;case "/":f(),O="default";return;case void 0:throw M(f())}f(),O="multiLineComment";},singleLineComment(){switch(I){case `
47
+ `:case "\r":case "\u2028":case "\u2029":f(),O="default";return;case void 0:return f(),j("eof")}f();},value(){switch(I){case "{":case "[":return j("punctuator",f());case "n":return f(),ie("ull"),j("null",null);case "t":return f(),ie("rue"),j("boolean",true);case "f":return f(),ie("alse"),j("boolean",false);case "-":case "+":f()==="-"&&(Wt=-1),O="sign";return;case ".":x=f(),O="decimalPointLeading";return;case "0":x=f(),O="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":x=f(),O="decimalInteger";return;case "I":return f(),ie("nfinity"),j("numeric",1/0);case "N":return f(),ie("aN"),j("numeric",NaN);case '"':case "'":Ge=f()==='"',x="",O="string";return}throw M(f())},identifierNameStartEscape(){if(I!=="u")throw M(f());f();let s=ls();switch(s){case "$":case "_":break;default:if(!K.isIdStartChar(s))throw Lo();break}x+=s,O="identifierName";},identifierName(){switch(I){case "$":case "_":case "\u200C":case "\u200D":x+=f();return;case "\\":f(),O="identifierNameEscape";return}if(K.isIdContinueChar(I)){x+=f();return}return j("identifier",x)},identifierNameEscape(){if(I!=="u")throw M(f());f();let s=ls();switch(s){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!K.isIdContinueChar(s))throw Lo();break}x+=s,O="identifierName";},sign(){switch(I){case ".":x=f(),O="decimalPointLeading";return;case "0":x=f(),O="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":x=f(),O="decimalInteger";return;case "I":return f(),ie("nfinity"),j("numeric",Wt*(1/0));case "N":return f(),ie("aN"),j("numeric",NaN)}throw M(f())},zero(){switch(I){case ".":x+=f(),O="decimalPoint";return;case "e":case "E":x+=f(),O="decimalExponent";return;case "x":case "X":x+=f(),O="hexadecimal";return}return j("numeric",Wt*0)},decimalInteger(){switch(I){case ".":x+=f(),O="decimalPoint";return;case "e":case "E":x+=f(),O="decimalExponent";return}if(K.isDigit(I)){x+=f();return}return j("numeric",Wt*Number(x))},decimalPointLeading(){if(K.isDigit(I)){x+=f(),O="decimalFraction";return}throw M(f())},decimalPoint(){switch(I){case "e":case "E":x+=f(),O="decimalExponent";return}if(K.isDigit(I)){x+=f(),O="decimalFraction";return}return j("numeric",Wt*Number(x))},decimalFraction(){switch(I){case "e":case "E":x+=f(),O="decimalExponent";return}if(K.isDigit(I)){x+=f();return}return j("numeric",Wt*Number(x))},decimalExponent(){switch(I){case "+":case "-":x+=f(),O="decimalExponentSign";return}if(K.isDigit(I)){x+=f(),O="decimalExponentInteger";return}throw M(f())},decimalExponentSign(){if(K.isDigit(I)){x+=f(),O="decimalExponentInteger";return}throw M(f())},decimalExponentInteger(){if(K.isDigit(I)){x+=f();return}return j("numeric",Wt*Number(x))},hexadecimal(){if(K.isHexDigit(I)){x+=f(),O="hexadecimalInteger";return}throw M(f())},hexadecimalInteger(){if(K.isHexDigit(I)){x+=f();return}return j("numeric",Wt*Number(x))},string(){switch(I){case "\\":f(),x+=ih();return;case '"':if(Ge)return f(),j("string",x);x+=f();return;case "'":if(!Ge)return f(),j("string",x);x+=f();return;case `
48
+ `:case "\r":throw M(f());case "\u2028":case "\u2029":ah(I);break;case void 0:throw M(f())}x+=f();},start(){switch(I){case "{":case "[":return j("punctuator",f())}O="value";},beforePropertyName(){switch(I){case "$":case "_":x=f(),O="identifierName";return;case "\\":f(),O="identifierNameStartEscape";return;case "}":return j("punctuator",f());case '"':case "'":Ge=f()==='"',O="string";return}if(K.isIdStartChar(I)){x+=f(),O="identifierName";return}throw M(f())},afterPropertyName(){if(I===":")return j("punctuator",f());throw M(f())},beforePropertyValue(){O="value";},afterPropertyValue(){switch(I){case ",":case "}":return j("punctuator",f())}throw M(f())},beforeArrayValue(){if(I==="]")return j("punctuator",f());O="value";},afterArrayValue(){switch(I){case ",":case "]":return j("punctuator",f())}throw M(f())},end(){throw M(f())}};function j(s,t){return {type:s,value:t,line:Ut,column:Ft}}function ie(s){for(let t of s){if(jt()!==t)throw M(f());f();}}function ih(){switch(jt()){case "b":return f(),"\b";case "f":return f(),"\f";case "n":return f(),`
49
+ `;case "r":return f(),"\r";case "t":return f()," ";case "v":return f(),"\v";case "0":if(f(),K.isDigit(jt()))throw M(f());return "\0";case "x":return f(),rh();case "u":return f(),ls();case `
50
+ `:case "\u2028":case "\u2029":return f(),"";case "\r":return f(),jt()===`
51
+ `&&f(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw M(f());case void 0:throw M(f())}return f()}function rh(){let s="",t=jt();if(!K.isHexDigit(t)||(s+=f(),t=jt(),!K.isHexDigit(t)))throw M(f());return s+=f(),String.fromCodePoint(parseInt(s,16))}function ls(){let s="",t=4;for(;t-- >0;){let e=jt();if(!K.isHexDigit(e))throw M(f());s+=f();}return String.fromCodePoint(parseInt(s,16))}var sh={start(){if(Y.type==="eof")throw re();as();},beforePropertyName(){switch(Y.type){case "identifier":case "string":hs=Y.value,ut="afterPropertyName";return;case "punctuator":In();return;case "eof":throw re()}},afterPropertyName(){if(Y.type==="eof")throw re();ut="beforePropertyValue";},beforePropertyValue(){if(Y.type==="eof")throw re();as();},beforeArrayValue(){if(Y.type==="eof")throw re();if(Y.type==="punctuator"&&Y.value==="]"){In();return}as();},afterPropertyValue(){if(Y.type==="eof")throw re();switch(Y.value){case ",":ut="beforePropertyName";return;case "}":In();}},afterArrayValue(){if(Y.type==="eof")throw re();switch(Y.value){case ",":ut="beforeArrayValue";return;case "]":In();}},end(){}};function as(){let s;switch(Y.type){case "punctuator":switch(Y.value){case "{":s={};break;case "[":s=[];break}break;case "null":case "boolean":case "numeric":case "string":s=Y.value;break}if($e===void 0)$e=s;else {let t=qt[qt.length-1];Array.isArray(t)?t.push(s):Object.defineProperty(t,hs,{value:s,writable:true,enumerable:true,configurable:true});}if(s!==null&&typeof s=="object")qt.push(s),Array.isArray(s)?ut="beforeArrayValue":ut="beforePropertyName";else {let t=qt[qt.length-1];t==null?ut="end":Array.isArray(t)?ut="afterArrayValue":ut="afterPropertyValue";}}function In(){qt.pop();let s=qt[qt.length-1];s==null?ut="end":Array.isArray(s)?ut="afterArrayValue":ut="afterPropertyValue";}function M(s){return Rn(s===void 0?`JSON5: invalid end of input at ${Ut}:${Ft}`:`JSON5: invalid character '${qo(s)}' at ${Ut}:${Ft}`)}function re(){return Rn(`JSON5: invalid end of input at ${Ut}:${Ft}`)}function Lo(){return Ft-=5,Rn(`JSON5: invalid identifier character at ${Ut}:${Ft}`)}function ah(s){console.warn(`JSON5: '${qo(s)}' in strings is not valid ECMAScript; consider escaping`);}function qo(s){let t={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(t[s])return t[s];if(s<" "){let e=s.charCodeAt(0).toString(16);return "\\x"+("00"+e).substring(e.length)}return s}function Rn(s){let t=new SyntaxError(s);return t.lineNumber=Ut,t.columnNumber=Ft,t}var oh=function(t,e,n){let i=[],o="",r,a,u="",l;if(e!=null&&typeof e=="object"&&!Array.isArray(e)&&(n=e.space,l=e.quote,e=e.replacer),typeof e=="function")a=e;else if(Array.isArray(e)){r=[];for(let v of e){let S;typeof v=="string"?S=v:(typeof v=="number"||v instanceof String||v instanceof Number)&&(S=String(v)),S!==void 0&&r.indexOf(S)<0&&r.push(S);}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),u=" ".substr(0,n)):typeof n=="string"&&(u=n.substr(0,10)),h("",{"":t});function h(v,S){let y=S[v];switch(y!=null&&(typeof y.toJSON5=="function"?y=y.toJSON5(v):typeof y.toJSON=="function"&&(y=y.toJSON(v))),a&&(y=a.call(S,v,y)),y instanceof Number?y=Number(y):y instanceof String?y=String(y):y instanceof Boolean&&(y=y.valueOf()),y){case null:return "null";case true:return "true";case false:return "false"}if(typeof y=="string")return c(y);if(typeof y=="number")return String(y);if(typeof y=="object")return Array.isArray(y)?E(y):m(y)}function c(v){let S={"'":.1,'"':.2},y={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},T="";for(let d=0;d<v.length;d++){let p=v[d];switch(p){case "'":case '"':S[p]++,T+=p;continue;case "\0":if(K.isDigit(v[d+1])){T+="\\x00";continue}}if(y[p]){T+=y[p];continue}if(p<" "){let D=p.charCodeAt(0).toString(16);T+="\\x"+("00"+D).substring(D.length);continue}T+=p;}let R=l||Object.keys(S).reduce((d,p)=>S[d]<S[p]?d:p);return T=T.replace(new RegExp(R,"g"),y[R]),R+T+R}function m(v){if(i.indexOf(v)>=0)throw TypeError("Converting circular structure to JSON5");i.push(v);let S=o;o=o+u;let y=r||Object.keys(v),T=[];for(let d of y){let p=h(d,v);if(p!==void 0){let D=g(d)+":";u!==""&&(D+=" "),D+=p,T.push(D);}}let R;if(T.length===0)R="{}";else {let d;if(u==="")d=T.join(","),R="{"+d+"}";else {let p=`,
52
+ `+o;d=T.join(p),R=`{
53
+ `+o+d+`,
54
+ `+S+"}";}}return i.pop(),o=S,R}function g(v){if(v.length===0)return c(v);let S=String.fromCodePoint(v.codePointAt(0));if(!K.isIdStartChar(S))return c(v);for(let y=S.length;y<v.length;y++)if(!K.isIdContinueChar(String.fromCodePoint(v.codePointAt(y))))return c(v);return v}function E(v){if(i.indexOf(v)>=0)throw TypeError("Converting circular structure to JSON5");i.push(v);let S=o;o=o+u;let y=[];for(let R=0;R<v.length;R++){let d=h(String(R),v);y.push(d!==void 0?d:"null");}let T;if(y.length===0)T="[]";else if(u==="")T="["+y.join(",")+"]";else {let R=`,
55
+ `+o,d=y.join(R);T=`[
56
+ `+o+d+`,
57
+ `+S+"]";}return i.pop(),o=S,T}},uh={parse:eh,stringify:oh},lh=uh,cs=lh;var Mo="\xA7SPACE\xA7",Go="\xA7DOUBLE_QUOTES\xA7",$o="\xA7QUOTES\xA7",Ho="SPECIAL_\xA7QUOTES\xA7",Uo="\xA7CURLY_BRACKETS1\xA7",hh="\xA7INK_VAR\xA7",Ko="\xA7CURLY_BRACKETS2\xA7",ds;(R=>{let s=[],t=[];async function e(d,p){for(let D=0;D<s.length;D++)try{let{validation:b}=s[D].opts;if(b instanceof RegExp){if(!b.test(d.join(" ")))continue}else if(b instanceof ZodType&&!b.safeParse(d).success)continue;let w=await s[D].fn(d,p,c);if(w===!0||typeof w=="string")return w}catch{}return false}function n(d,p={name:"custom-command",validation:/^/}){s.unshift({fn:d,opts:p});}R.add=n;function i(){return [...t.map(d=>d.opts),...s.map(d=>d.opts)]}R.info=i;function o(d,p){t.unshift({fn:d,opts:p});}R.addMapper=o;function r(){s.length=0;}R.clear=r;function a(){t.length=0;}R.clearMappers=a;async function u(d,p,D){try{let b=l(d),w=await e(b,D);return w===!0?void 0:typeof w=="string"?(w.startsWith("#")&&(w=w.substring(1)),await R.run(w,p,D)):h(b,p)}catch(b){throw Ce.error("Error parsing ink hashtag-command",d),b}}R.run=u;function l(d,p){if(d=d.replaceAll('\\"',Go),d=d.replaceAll("\\'",$o),d=d.replaceAll("\\`",Ho),d=d.replaceAll("\\{",Uo),d=d.replaceAll("\\}",Ko),p?.mergeInkVariables){let _;do _=d,d=d.replace(/\{[^{}:]*\}/g,hh);while(d!==_)}d=d.replaceAll("{"," { "),d=d.replaceAll("}"," } "),d=d.replaceAll(Uo,"{"),d=d.replaceAll(Ko,"}");let D=[],b,w="";for(let _=0;_<d.length;_++){let V=d[_];V==='"'||V==="'"||V==="`"?b===void 0?(D.push(w),w="",b=V,w+=V):b===V?(b=void 0,w+=V,D.push(w),w=""):w+=V:w+=V;}return w!==""&&D.push(w),D.forEach((_,V)=>{V%2===1&&(D[V]=_.replaceAll(" ",Mo));}),d=D.join(""),D=d.split(" ").filter(_=>_!==""),D=D.map(_=>_.replaceAll(Mo," ").replaceAll(Go,'"').replaceAll($o,"'").replaceAll(Ho,"`")),D=v(D),D=D.flatMap(_=>T(_)),D=D.map(_=>_.startsWith('"')&&_.endsWith('"')||_.startsWith("'")&&_.endsWith("'")||_.startsWith("`")&&_.endsWith("`")?_.slice(1,-1):_),D}R.convertTagTolist=l;function h(d,p,D){for(let b of t){let{validation:w}=b.opts,_=false;if(w instanceof RegExp?_=w.test(d.join(" ")):w instanceof ZodType&&(_=w.safeParse(d).success),_)return b.fn(d,p)}D?.silent||Ce.error("The operation is not valid",d);}R.convertOperation=h;function c(d){return m(d)}R.convertListStringToObj=c;function m(d){if(d.length===0)return {};if(d.length%2!==0)throw Ce.error("The props list must have a pair number of elements",d),new Error("The props list must have a pair number of elements");let p="{";d.forEach((D,b)=>{if(b%2===0)p+=`"${D}": `;else {switch(D){case "null":case "undefined":case "true":case "false":p+=`${D}`;break;default:E(D)?(D=g(D),p+=`"${D}"`):D.startsWith("{")&&D.endsWith("}")?p+=`${D}`:D.startsWith('"')&&D.endsWith('"')?p+=`${D}`:Number.isNaN(parseFloat(D))?p+=`"${D}"`:p+=`${D}`;}b<d.length-1&&(p+=", ");}}),p+="}";try{return cs.parse(p)}catch(D){throw Ce.error("Error parsing ink json",p),D}}function g(d){return d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`")?d.substring(1,d.length-1):d}function E(d){return !!(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`"))}function v(d){return S(d).tokens}R.mergeJsonBlocks=v;function S(d){let p=[],D=false;for(let b=0;b<d.length;b++){let w=d[b];if(w!=="{"){p.push(w);continue}let _=y(d,b);if(_===-1){p.push(w);continue}let V=S(d.slice(b+1,_)),vt=["{",...V.tokens,"}"],Me=vt.join(" ");if(!V.hasInvalidMatchedBlock)try{cs.parse(Me),p.push(Me),b=_;continue}catch{}D=true,p.push(...vt),b=_;}return {tokens:p,hasInvalidMatchedBlock:D}}function y(d,p){let D=0;for(let b=p;b<d.length;b++)if(d[b]==="{")D++;else if(d[b]==="}"&&(D--,D===0))return b;return -1}function T(d){if(d==="["||d==="]")return [d];let p=0,D=d.length,b=[];for(;p<D&&d[p]==="[";)b.push("["),p++;let w=[];for(;D>p&&d[D-1]==="]";)w.unshift("]"),D--;let _=d.slice(p,D);return _===""?[...b,...w]:[...b,_,...w]}})(ds||={});var Ml=Bo(ql()),Gl=Bo(He());var nm=/(?:^|<>)\s*#\s*([^\r\n]+)/g,im=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,rm=new Set(["DONE","END"]),sm="_|_",jl=new Map;function $l(s,t){let e=JSON.stringify([t,s]),n=jl.get(e);if(n)return n;let i=new RegExp(s,t);return jl.set(e,i),i}function Tn(s,t){if(!t||typeof t!="object")return false;let e=t,n=e.anyOf;if(Array.isArray(n))return n.some(r=>Tn(s,r));let i=e.oneOf;if(Array.isArray(i))return i.some(r=>Tn(s,r));let o=e.allOf;if(Array.isArray(o))return o.every(r=>Tn(s,r));if(typeof e.const=="string")return s===e.const;if(Array.isArray(e.enum))return e.enum.some(r=>typeof r=="string"&&r===s);if(e.type!=="string"||typeof e.minLength=="number"&&s.length<e.minLength||typeof e.maxLength=="number"&&s.length>e.maxLength)return false;if(typeof e.pattern=="string")try{if(!$l(e.pattern,"").test(s))return !1}catch{return false}return true}function rs(s,t){if(!t||typeof t!="object")return false;let e=t,n=e.anyOf;if(Array.isArray(n))return n.some(a=>rs(s,a));let i=e.oneOf;if(Array.isArray(i))return i.some(a=>rs(s,a));let o=e.allOf;if(Array.isArray(o))return o.every(a=>rs(s,a));if(e.type!=="array"||typeof e.minItems=="number"&&s.length<e.minItems||typeof e.maxItems=="number"&&s.length>e.maxItems)return false;let r=Array.isArray(e.prefixItems)?e.prefixItems:[];if(s.length<r.length)return false;for(let a=0;a<r.length;a++)if(!Tn(s[a],r[a]))return false;return s.length===r.length?true:e.items===false||typeof e.items>"u"?false:e.items===true?true:s.slice(r.length).every(a=>Tn(a,e.items))}function am(s,t){if(t.type==="regexp")try{let e=$l(t.source,t.flags);return e.lastIndex=0,e.test(s.join(" "))}catch{return false}return t.type==="literal"?s.join(" ")===t.value:rs(s,t.schema)}function om(s){let t=s.split(/\r?\n/),e=[];for(let n=0;n<t.length;n++){let i=t[n];for(let o of i.matchAll(nm)){let r=(o[1]??"").trim();if(!r)continue;let a=ds.convertTagTolist(r,{mergeInkVariables:true});a.length!==0&&e.push({line:n+1,command:r,tokens:a});}}return e}function Hl(s){return s.keyword==="required"&&typeof s.params?.missingProperty=="string"?s.params.missingProperty:s.instancePath.split("/").pop()||"(root)"}function um(s,t){let e=t.split("/").filter(Boolean).map(r=>r.replace(/~1/g,"/").replace(/~0/g,"~")),n=s,i,o=r=>{r&&typeof r=="object"&&typeof r.$origin=="string"&&(i=r.$origin);};o(n);for(let r of e){if(n===null||typeof n!="object")break;n=n[r],o(n);}return i}function lm(s){let t=s.map(a=>a.instancePath),e=a=>t.some(u=>u!==a&&u.startsWith(`${a}/`)),n=s.filter(a=>!e(a.instancePath)),i=new Map;for(let a of n){let u=i.get(a.instancePath)??[];u.push(a),i.set(a.instancePath,u);}let o=[];for(let a of i.values()){let u=a.filter(l=>l.keyword!=="anyOf"&&l.keyword!=="oneOf");o.push(...u.length>0?u:a);}let r=new Set;return o.filter(a=>{let u=`${Hl(a)}|${a.message}`;return r.has(u)?false:(r.add(u),true)})}var hm;(r=>{function s(a,u={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let l=[];try{return {json:new Ml.Compiler(a,{errorHandler:(g,E)=>{let v=g.replace(/^[A-Z]+: line \d+: ?/,""),S=g.match(/line (\d+)/);l.push({message:v,type:E,line:S?Number(S[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:g=>g,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:l}}catch{let c=false,m={...u,textSource:a};return t(l,()=>{c=true;},m),c?s(m.textSource,u):{issues:l}}}r.compile=s;function t(a,u,l){let{functions:h,initialVarsToRemove:c,labelToRemove:m}=l,g=a.find(E=>E.type===Gl.ErrorType.Error);if(g){if(g.message.includes("Divert target not found")){let E=g.message.match(/Divert target not found: '-> (\w+)'/);if(E?.[1]){let v=E[1],S=`
58
58
 
59
- === ${m} ===
59
+ === ${v} ===
60
60
 
61
- -> DONE`;return a.textSource=a.textSource.concat(D),h.push(m),r()}}if(c.message.includes("Unresolved variable")){let d=c.message.match(/Unresolved variable: (\w+)/);if(d?.[1]){let m=d[1],D=`VAR ${m} = ""
61
+ -> DONE`;return l.textSource=l.textSource.concat(S),m.push(v),u()}}if(g.message.includes("Unresolved variable")){let E=g.message.match(/Unresolved variable: (\w+)/);if(E?.[1]){let v=E[1],S=`VAR ${v} = ""
62
62
 
63
- `;return a.textSource=D.concat(a.textSource),l.push(m),r()}}if(c.message.includes("Variable could not be found to assign to")){let d=c.message.match(/Variable could not be found to assign to: (\w+)/);if(d?.[1]){let m=d[1],D=`VAR ${m} = ""
63
+ `;return l.textSource=S.concat(l.textSource),c.push(v),u()}}if(g.message.includes("Variable could not be found to assign to")){let E=g.message.match(/Variable could not be found to assign to: (\w+)/);if(E?.[1]){let v=E[1],S=`VAR ${v} = ""
64
64
 
65
- `;return a.textSource=D.concat(a.textSource),l.push(m),r()}}if(c.message.includes("Variable could not be found to assign to")){let d=c.message.match(/Variable could not be found to assign to: '(\w+)'/);if(d?.[1]){let m=d[1],D=`VAR ${m} = ""
65
+ `;return l.textSource=S.concat(l.textSource),c.push(v),u()}}if(g.message.includes("Variable could not be found to assign to")){let E=g.message.match(/Variable could not be found to assign to: '(\w+)'/);if(E?.[1]){let v=E[1],S=`VAR ${v} = ""
66
66
 
67
- `;return a.textSource=D.concat(a.textSource),l.push(m),r()}}if(c.message.includes("Function call target not found")){let d=c.message.match(/Function call target not found: '-> (\w+)'/);if(d?.[1]){let m=d[1],D=`
67
+ `;return l.textSource=S.concat(l.textSource),c.push(v),u()}}if(g.message.includes("Function call target not found")){let E=g.message.match(/Function call target not found: '-> (\w+)'/);if(E?.[1]){let v=E[1],S=`
68
68
 
69
- === function ${m}() ===
69
+ === function ${v}() ===
70
70
 
71
71
  ~ return
72
72
 
73
- `;return a.textSource=a.textSource.concat(D),u.push({name:m,args:0}),h.push(m),r()}}if(c.message.includes(" arguments, but got ")){let d=c.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(d?.[1]){let m=d[1],D=parseInt(d[3]||"0",10),v=D>0?Array.from({length:D},(k,f)=>`arg${f+1}`).join(", "):"",A=`
73
+ `;return l.textSource=l.textSource.concat(S),h.push({name:v,args:0}),m.push(v),u()}}if(g.message.includes(" arguments, but got ")){let E=g.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(E?.[1]){let v=E[1],S=parseInt(E[3]||"0",10),y=S>0?Array.from({length:S},(d,p)=>`arg${p+1}`).join(", "):"",T=`
74
74
 
75
- === function ${m}(${v}) ===
75
+ === function ${v}(${y}) ===
76
76
 
77
77
  ~ return
78
78
 
79
- `;a.textSource=a.textSource.replaceAll(`
79
+ `;l.textSource=l.textSource.replaceAll(`
80
80
 
81
- === function ${m}() ===
81
+ === function ${v}() ===
82
82
 
83
83
  ~ return
84
84
 
85
- `,""),a.textSource=a.textSource.concat(A);let S=u.find(k=>k.name===m);return S?S.args=D:(u.push({name:m,args:D}),h.push(m)),r()}}if(c.message.includes("Could not find target for read count")){let d=c.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(d?.[1]){let m=d[1],[D,v]=m.split("."),A=`
85
+ `,""),l.textSource=l.textSource.concat(T);let R=h.find(d=>d.name===v);return R?R.args=S:(h.push({name:v,args:S}),m.push(v)),u()}}if(g.message.includes("Could not find target for read count")){let E=g.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(E?.[1]){let v=E[1],[S,y]=v.split("."),T=`
86
86
 
87
- LIST ${D} = ${v}
87
+ LIST ${S} = ${y}
88
88
 
89
- `;return a.textSource=a.textSource.concat(A),a.initialVarsToRemove.push(D),a.initialVarsToRemove.push(`${D}.${v}`),r()}}if(c.message.includes("variable for increment could not be found")){let d=c.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(d?.[1]){let m=d[1],D=`VAR ${m} = 0
89
+ `;return l.textSource=l.textSource.concat(T),l.initialVarsToRemove.push(S),l.initialVarsToRemove.push(`${S}.${y}`),u()}}if(g.message.includes("variable for increment could not be found")){let E=g.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(E?.[1]){let v=E[1],S=`VAR ${v} = 0
90
90
 
91
- `;return a.textSource=D.concat(a.textSource),a.initialVarsToRemove.push(m),r()}}return o.forEach(d=>{let m=d.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);m?.[1]&&(d.message=`The function '${m[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:o}}return {issues:o}}i.getErrors=t;function e(o,r){return sm(o).filter(({tokens:a})=>!r.some(({validation:u})=>rm(a,u)))}i.getUnknownHashtagCommands=e;function n(o,r){let a=new Set;for(let d of o.matchAll(em))d[1]&&a.add(d[1]);let u=new Set(r),l=new Set,h=o.split(/\r?\n/),c=[];for(let d=0;d<h.length;d++){let m=(h[d]??"").replace(/\/\/.*$/,"");for(let D of m.matchAll(/->[ \t]+(\w[\w.]*)/g)){let v=D[1];if(!v)continue;let A=v.split(".")[0]??v;nm.has(A)||a.has(A)||u.has(v)||u.has(v.replaceAll(".",im))||u.has(A)||l.has(v)||(l.add(v),c.push({line:d+1,target:v}));}}return c}i.getUnknownDivertTargets=n;})(am||={});export{am as InkCompiler};
91
+ `;return l.textSource=S.concat(l.textSource),l.initialVarsToRemove.push(v),u()}}return a.forEach(E=>{let v=E.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);v?.[1]&&(E.message=`The function '${v[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:a}}return {issues:a}}r.getErrors=t;function e(a,u){return om(a).filter(({tokens:l})=>!u.some(({validation:h})=>am(l,h)))}r.getUnknownHashtagCommands=e;function n(a,u){let l=new Set;for(let E of a.matchAll(im))E[1]&&l.add(E[1]);let h=new Set(u),c=new Set,m=a.split(/\r?\n/),g=[];for(let E=0;E<m.length;E++){let v=(m[E]??"").replace(/\/\/.*$/,"");for(let S of v.matchAll(/->[ \t]+(\w[\w.]*)/g)){let y=S[1];if(!y)continue;let T=y.split(".")[0]??y;rm.has(T)||l.has(T)||h.has(y)||h.has(y.replaceAll(".",sm))||h.has(T)||c.has(y)||(c.add(y),g.push({line:E+1,target:y}));}}return g}r.getUnknownDivertTargets=n;function i(a){return new em({strict:false,allErrors:true}).compile(a)}r.getSchemaValidator=i;function o(a,u){let l=typeof u=="function"?u:i(u);return l(a)?[]:lm(l.errors??[]).map(c=>({instancePath:c.instancePath||"(root)",element:Hl(c),message:c.message??"invalid value",origin:um(a,c.instancePath)}))}r.validateAgainstJsonSchema=o;})(hm||={});export{hm as InkCompiler};