'use strict';var pixiVn=require('@drincs/pixi-vn');var gh=Object.create;var qo=Object.defineProperty;var mh=Object.getOwnPropertyDescriptor;var Ch=Object.getOwnPropertyNames;var vh=Object.getPrototypeOf,yh=Object.prototype.hasOwnProperty;var Ze=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var C=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var Sh=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ch(e))!yh.call(s,i)&&i!==t&&qo(s,i,{get:()=>e[i],enumerable:!(n=mh(e,i))||n.enumerable});return s};var bh=(s,e,t)=>(t=s!=null?gh(vh(s)):{},Sh(qo(t,"default",{value:s,enumerable:!0}),s));var us=C(kn=>{Object.defineProperty(kn,"__esModule",{value:!0});kn.CompilerOptions=void 0;var ls=class{constructor(e=null,t=[],n=!1,i=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=a;}};kn.CompilerOptions=ls;});var al=C(Rn=>{Object.defineProperty(Rn,"__esModule",{value:!0});Rn.DebugSourceRange=void 0;var hs=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};Rn.DebugSourceRange=hs;});var Ln=C(Dn=>{Object.defineProperty(Dn,"__esModule",{value:!0});Dn.ErrorType=void 0;var ol;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(ol||(Dn.ErrorType=ol={}));});var ll=C(Wn=>{Object.defineProperty(Wn,"__esModule",{value:!0});Wn.Argument=void 0;var cs=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};Wn.Argument=cs;});var k=C(H=>{Object.defineProperty(H,"__esModule",{value:!0});H.filterUndef=H.isEquatable=H.nullIfUndefined=H.asINamedContentOrNull=H.asBooleanOrThrows=H.asNumberOrThrows=H.asOrThrows=H.asOrNull=void 0;function rc(s,e){return s instanceof e?ul(s):null}H.asOrNull=rc;function sc(s,e){if(s instanceof e)return ul(s);throw new Error(`${s} is not of type ${e}`)}H.asOrThrows=sc;function ac(s){if(typeof s=="number")return s;throw new Error(`${s} is not a number`)}H.asNumberOrThrows=ac;function oc(s){if(typeof s=="boolean")return s;throw new Error(`${s} is not a boolean`)}H.asBooleanOrThrows=oc;function lc(s){return s.hasValidName&&s.name?s:null}H.asINamedContentOrNull=lc;function uc(s){return typeof s>"u"?null:s}H.nullIfUndefined=uc;function hc(s){return typeof s=="object"&&typeof s.Equals=="function"}H.isEquatable=hc;function ul(s,e){return s}function cc(s){return s!=null}H.filterUndef=cc;});var q=C(qn=>{Object.defineProperty(qn,"__esModule",{value:!0});qn.ParsedObject=void 0;var hl=k(),ds=class{constructor(){this._alreadyHadError=!1,this._alreadyHadWarning=!1,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let n of t)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let n=(0, hl.asOrNull)(this,e);if(n!==null&&(t===null||t(n)===!0))return n;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,n)=>{let i=Array.isArray(n)?n:[],a=(0, hl.asOrNull)(this,e);if(a!==null&&(!t||t(a)===!0)&&i.push(a),this.content===null)return [];for(let r of this.content)r.FindAll&&r.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,!0);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,n=!1){if(t===null&&(t=this),!(t._alreadyHadError&&!n||t._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(e,t,n);else throw new Error(`No parent object to send error to: ${e}`);n?t._alreadyHadWarning=!0:t._alreadyHadError=!0;}}};qn.ParsedObject=ds;});var Mn=C(jn=>{Object.defineProperty(jn,"__esModule",{value:!0});jn.AuthorWarning=void 0;var dc=q(),fs=class extends dc.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};jn.AuthorWarning=fs;});var se=C(Ut=>{Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Path=void 0;var mt=class s{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=!1,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof s.Component&&arguments[1]instanceof s){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new s(e)}else return s.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e=0}get isParent(){return this.name==s.parentId}static ToParent(){return new e(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:!1}}s.Component=e;})(mt||(Ut.Path=mt={}));});var Ht=C(Bn=>{Object.defineProperty(Bn,"__esModule",{value:!0});Bn.Debug=void 0;var cl;(function(s){function e(n,i,a){t(n instanceof i,a);}s.AssertType=e;function t(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}s.Assert=t;})(cl||(Bn.Debug=cl={}));});var Q=C(Ct=>{Object.defineProperty(Ct,"__esModule",{value:!0});Ct.throwNullException=Ct.NullException=void 0;var Gn=class extends Error{};Ct.NullException=Gn;function fc(s){throw new Gn(`${s} is null or undefined`)}Ct.throwNullException=fc;});var ae=C($n=>{Object.defineProperty($n,"__esModule",{value:!0});$n.InkObject=void 0;var vt=se(),Kt=J(),ps=Ht(),yt=k(),Jn=Q(),gs=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let n=t.ContentAtPath(e).obj;if(n){let i=n.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new vt.Path;else {let e=[],t=this,n=(0, yt.asOrNull)(t.parent,Kt.Container);for(;n!==null;){let i=(0, yt.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Jn.throwNullException)("namedChild.name");e.unshift(new vt.Path.Component(i.name));}else e.unshift(new vt.Path.Component(n.content.indexOf(t)));t=n,n=(0, yt.asOrNull)(n.parent,Kt.Container);}this._path=new vt.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Jn.throwNullException)("path");if(e.isRelative){let t=(0, yt.asOrNull)(this,Kt.Container);return t===null&&(ps.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, yt.asOrNull)(this.parent,Kt.Container),ps.Debug.Assert(t!==null,"Expected parent to be a container"),ps.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Jn.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Jn.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,n=Math.min(e.length,t.length),i=-1;for(let l=0;l{Object.defineProperty(Un,"__esModule",{value:!0});Un.StringBuilder=void 0;var ms=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=` `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(n,i)=>typeof t[i]<"u"?t[i]:n);}toString(){return this.string}Clear(){this.string="";}};Un.StringBuilder=ms;});var le=C(St=>{Object.defineProperty(St,"__esModule",{value:!0});St.InkList=St.InkListItem=void 0;var xe=Q(),pc=nt(),oe=class s{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new 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(e){if(e instanceof s){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return !1}copy(){return new s(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!s.isLikeInkListItem(t))return s.Null;let n=t;return new s(n.originName,n.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};St.InkListItem=oe;var Cs=class s extends Map{constructor(){if(super(arguments[0]instanceof s?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof s){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, xe.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, xe.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var n;if(e==null||e=="")return new s;let i=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(i)return i.value===null?(0, xe.throwNullException)("listValue.value"):new s(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof oe){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, xe.throwNullException)("this.origins");for(let i of this.origins)if(i.name==n.originName){let a=i.TryGetValueForItem(n,0);if(a.exists){this.Add(n,a.result);return}else throw new Error("Could not add the item "+n+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let n=e,i=null;if(this.origins===null)return (0, xe.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, xe.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=s.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new oe(i.name,n),r=i.ValueForItem(a);this.Add(a,r);}}}ContainsItemNamed(e){for(let[t]of this)if(oe.fromSerializedKey(t).itemName==e)return !0;return !1}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let n=e.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${e}`);this.set(n,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(n=>n.name==e?(t=n,!1):!0),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=oe.fromSerializedKey(e);if(t.originName===null)return (0, xe.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:oe.Null,Value:0};for(let[t,n]of this){let i=oe.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:i,Value:n});}return e}get minItem(){let e={Key:oe.Null,Value:0};for(let[t,n]of this){let i=oe.fromSerializedKey(t);(e.Key.isNull||ne.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?!1:e.Count==0?!0:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?!1:this.Count==0?!0:this.maxItem.Value0?new s(this.maxItem):new s}MinAsList(){return this.Count>0?new s(this.minItem):new s}ListWithSubRange(e,t){if(this.Count==0)return new s;let n=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof s&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof s&&t.Count>0&&(a=t.maxItem.Value);let r=new s;r.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=i&&o.Value<=a&&r.Add(o.Key,o.Value);return r}Equals(e){if(!(e instanceof s)||e.Count!=this.Count)return !1;for(let[t]of this)if(!e.has(t))return !1;return !0}get orderedItems(){let e=new Array;for(let[t,n]of this){let i=oe.fromSerializedKey(t);e.push({Key:i,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, xe.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, xe.throwNullException)("y.Key.originName"):t.Value==n.Value?t.Key.originName.localeCompare(n.Key.originName):t.Valuen.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new pc.StringBuilder;for(let n=0;n0&&t.Append(", ");let i=e[n].Key;if(i.itemName===null)return (0, xe.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};St.InkList=Cs;});var zt=C(Hn=>{Object.defineProperty(Hn,"__esModule",{value:!0});Hn.StoryException=void 0;var vs=class extends Error{constructor(e){super(e),this.useEndLineNumber=!1,this.message=e,this.name="StoryException";}};Hn.StoryException=vs;});var bt=C(Me=>{Object.defineProperty(Me,"__esModule",{value:!0});Me.tryParseFloat=Me.tryParseInt=Me.tryGetValueFromMap=void 0;function gc(s,e,t){if(s===null)return {result:t,exists:!1};let n=s.get(e);return typeof n>"u"?{result:t,exists:!1}:{result:n,exists:!0}}Me.tryGetValueFromMap=gc;function mc(s,e=0){let t=parseInt(s);return Number.isNaN(t)?{result:e,exists:!1}:{result:t,exists:!0}}Me.tryParseInt=mc;function Cc(s,e=0){let t=parseFloat(s);return Number.isNaN(t)?{result:e,exists:!1}:{result:t,exists:!0}}Me.tryParseFloat=Cc;});var j=C(M=>{Object.defineProperty(M,"__esModule",{value:!0});M.ValueType=M.ListValue=M.VariablePointerValue=M.DivertTargetValue=M.StringValue=M.FloatValue=M.IntValue=M.BoolValue=M.Value=M.AbstractValue=void 0;var dl=ae(),fl=se(),it=le(),vc=zt(),Xt=k(),pl=bt(),me=Q(),Kn=class s extends dl.InkObject{static Create(e,t){if(t){if(t===W.Int&&Number.isInteger(Number(e)))return new Pe(Number(e));if(t===W.Float&&!isNaN(e))return new Oe(Number(e))}if(typeof e=="boolean")return new _t(!!e);if(typeof e=="string")return new Le(String(e));if(Number.isInteger(Number(e)))return new Pe(Number(e));if(isNaN(e)){if(e instanceof fl.Path)return new zn((0, Xt.asOrThrows)(e,fl.Path));if(e instanceof it.InkList)return new Xn((0, Xt.asOrThrows)(e,it.InkList))}else return new Oe(Number(e));return null}Copy(){return (0, Xt.asOrThrows)(s.Create(this.valueObject),dl.InkObject)}BadCastException(e){return new vc.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};M.AbstractValue=Kn;var we=class extends Kn{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, me.throwNullException)("Value.value"):this.value.toString()}};M.Value=we;var _t=class extends we{constructor(e){super(e||!1);}get isTruthy(){return !!this.value}get valueType(){return W.Bool}Cast(e){if(this.value===null)return (0, me.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==W.Int)return new Pe(this.value?1:0);if(e==W.Float)return new Oe(this.value?1:0);if(e==W.String)return new Le(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};M.BoolValue=_t;var Pe=class extends we{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return W.Int}Cast(e){if(this.value===null)return (0, me.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==W.Bool)return new _t(this.value!==0);if(e==W.Float)return new Oe(this.value);if(e==W.String)return new Le(""+this.value);throw this.BadCastException(e)}};M.IntValue=Pe;var Oe=class extends we{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return W.Float}Cast(e){if(this.value===null)return (0, me.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==W.Bool)return new _t(this.value!==0);if(e==W.Int)return new Pe(this.value);if(e==W.String)return new Le(""+this.value);throw this.BadCastException(e)}};M.FloatValue=Oe;var Le=class extends we{constructor(e){if(super(e||""),this._isNewline=this.value==` `,this._isInlineWhitespace=!0,this.value===null)return (0, me.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=!1,!1):!0);}get valueType(){return W.String}get isTruthy(){return this.value===null?(0, me.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==W.Int){let t=(0, pl.tryParseInt)(this.value);if(t.exists)return new Pe(t.result);throw this.BadCastException(e)}if(e==W.Float){let t=(0, pl.tryParseFloat)(this.value);if(t.exists)return new Oe(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};M.StringValue=Le;var zn=class extends we{constructor(e=null){super(e);}get valueType(){return W.DivertTarget}get targetPath(){return this.value===null?(0, me.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};M.DivertTargetValue=zn;var ys=class s extends we{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, me.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return W.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new s(this.variableName,this.contextIndex)}};M.VariablePointerValue=ys;var Xn=class s extends we{get isTruthy(){return this.value===null?(0, me.throwNullException)("this.value"):this.value.Count>0}get valueType(){return W.List}Cast(e){if(this.value===null)return (0, me.throwNullException)("Value.value");if(e==W.Int){let t=this.value.maxItem;return t.Key.isNull?new Pe(0):new Pe(t.Value)}else if(e==W.Float){let t=this.value.maxItem;return t.Key.isNull?new Oe(0):new Oe(t.Value)}else if(e==W.String){let t=this.value.maxItem;return t.Key.isNull?new Le(""):new Le(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new it.InkList:e instanceof it.InkList?this.value=new it.InkList(e):e instanceof it.InkListItem&&typeof t=="number"&&(this.value=new it.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, Xt.asOrNull)(e,s),i=(0, Xt.asOrNull)(t,s);if(i&&i.value===null)return (0, me.throwNullException)("newList.value");if(n&&n.value===null)return (0, me.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};M.ListValue=Xn;var W;(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";})(W||(M.ValueType=W={}));});var gl=C(Yn=>{Object.defineProperty(Yn,"__esModule",{value:!0});Yn.SearchResult=void 0;var yc=J(),Ss=class s{constructor(){this.obj=null,this.approximate=!1;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof yc.Container?this.obj:null}copy(){let e=new s;return e.obj=this.obj,e.approximate=this.approximate,e}};Yn.SearchResult=Ss;});var J=C(Qt=>{Object.defineProperty(Qt,"__esModule",{value:!0});Qt.Container=void 0;var Sc=j(),ml=Q(),bc=nt(),Et=ae(),_c=gl(),Cl=se(),vl=Ht(),Ec=bt(),Be=k(),Yt=class s extends Et.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=!1,this.turnIndexShouldBeCounted=!1,this.countingAtStartOnly=!1,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,n]of this.namedContent){let i=(0, Be.asOrThrows)(n,Et.InkObject);e.set(t,i);}for(let t of this.content){let n=(0, Be.asINamedContentOrNull)(t);n!=null&&n.hasValidName&&e.delete(n.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[n]of t)this.namedContent.delete(n);if(e!=null)for(let[,n]of e){let i=(0, Be.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=s.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=s.CountFlags.Turns),this.countingAtStartOnly&&(e|=s.CountFlags.CountStartOnly),e==s.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&s.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=!0),(t&s.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=!0),(t&s.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=!0);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof s;)t.content.length>0&&(e.push(new Cl.Path.Component(0)),t=t.content[0]);return new Cl.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let n of t)this.AddContent(n);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, Be.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){vl.Debug.AssertType(e,Et.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, Be.asOrThrows)(e,Et.InkObject);if(t.parent=this,e.name===null)return (0, ml.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let i=new _c.SearchResult;i.approximate=!1;let a=this,r=this;for(let o=t;o=0&&e.index=0||a.set(r,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,r]of a)vl.Debug.AssertType(r,s,"Can only print out named Containers"),r.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,i(),e.Append("]");}};Qt.Container=Yt;(function(s){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(s.CountFlags||(s.CountFlags={}));})(Yt||(Qt.Container=Yt={}));});var Z=C(en=>{Object.defineProperty(en,"__esModule",{value:!0});en.ControlCommand=void 0;var Tc=ae(),Zt=class s extends Tc.InkObject{get commandType(){return this._commandType}constructor(e=s.CommandType.NotSet){super(),this._commandType=e;}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()}};en.ControlCommand=Zt;(function(s){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(s.CommandType||(s.CommandType={}));})(Zt||(en.ControlCommand=Zt={}));});var Ce=C(Qn=>{Object.defineProperty(Qn,"__esModule",{value:!0});Qn.Expression=void 0;var yl=J(),bs=Z(),xc=q(),_s=class extends xc.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=!1,this.GenerateRuntimeObject=()=>{let e=new yl.Container;return e.AddContent(bs.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(bs.ControlCommand.EvalOutput()),e.AddContent(bs.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new yl.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let n=t.Copy();n&&e.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return !1}};Qn.Expression=_s;});var rt=C(Zn=>{Object.defineProperty(Zn,"__esModule",{value:!0});Zn.Void=void 0;var wc=ae(),Es=class extends wc.InkObject{toString(){return "Void"}};Zn.Void=Es;});var Ne=C(ti=>{Object.defineProperty(ti,"__esModule",{value:!0});ti.NativeFunctionCall=void 0;var E=j(),tn=zt(),Pc=rt(),ei=le(),Oc=ae(),ve=k(),ue=Q(),A=class s extends Oc.InkObject{static CallWithName(e){return new s(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, ue.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(s._nativeFunctions===null?(0, ue.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=s._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=!1;for(let a of e){if(a instanceof Pc.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?');a instanceof E.ListValue&&(t=!0);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),i=n[0].valueType;return i==E.ValueType.Int?this.CallType(n):i==E.ValueType.Float?this.CallType(n):i==E.ValueType.String?this.CallType(n):i==E.ValueType.DivertTarget?this.CallType(n):i==E.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, ve.asOrThrows)(e[0],E.Value),n=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, ue.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(n);if(!r){let o=E.ValueType[n];throw new tn.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, ve.asOrThrows)(e[1],E.Value),u=r;if(i.value===null||l.value===null)return (0, ue.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(i.value,l.value);return E.Value.Create(h)}else {let o=r;if(i.value===null)return (0, ue.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(i.value);return this.name===s.Int?E.Value.Create(l,E.ValueType.Int):this.name===s.Float?E.Value.Create(l,E.ValueType.Float):E.Value.Create(l,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof E.ListValue&&e[1]instanceof E.IntValue)return this.CallListIncrementOperation(e);let t=(0, ve.asOrThrows)(e[0],E.Value),n=(0, ve.asOrThrows)(e[1],E.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=E.ValueType.List||n.valueType!=E.ValueType.List)){if(this._operationFuncs===null)return (0, ue.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(E.ValueType.Int);if(i===null)return (0, ue.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, ve.asBooleanOrThrows)(i(t.isTruthy?1:0,n.isTruthy?1:0));return new E.BoolValue(a)}if(t.valueType==E.ValueType.List&&n.valueType==E.ValueType.List)return this.CallType([t,n]);throw new tn.StoryException("Can not call use "+this.name+" operation on "+E.ValueType[t.valueType]+" and "+E.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, ve.asOrThrows)(e[0],E.ListValue),n=(0, ve.asOrThrows)(e[1],E.IntValue),i=new ei.InkList;if(t.value===null)return (0, ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,r]of t.value){let o=ei.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, ue.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(E.ValueType.Int);if(n.value===null)return (0, ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(r,n.value),h=null;if(t.value.origins===null)return (0, ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of t.value.origins)if(c.name==o.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(u,ei.InkListItem.Null);c.exists&&i.Add(c.result,u);}}return new E.ListValue(i)}CoerceValuesToSingleType(e){let t=E.ValueType.Int,n=null;for(let a of e){let r=(0, ve.asOrThrows)(a,E.Value);r.valueType>t&&(t=r.valueType),r.valueType==E.ValueType.List&&(n=(0, ve.asOrNull)(r,E.ListValue));}let i=[];if(E.ValueType[t]==E.ValueType[E.ValueType.List])for(let a of e){let r=(0, ve.asOrThrows)(a,E.Value);if(r.valueType==E.ValueType.List)i.push(r);else if(r.valueType==E.ValueType.Int){let o=parseInt(r.valueObject);if(n=(0, ve.asOrThrows)(n,E.ListValue),n.value===null)return (0, ue.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, ue.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,ei.InkListItem.Null);if(u.exists){let h=new E.ListValue(u.result,o);i.push(h);}else throw new tn.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=E.ValueType[r.valueType];throw new tn.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, ve.asOrThrows)(a,E.Value).Cast(t);i.push(o);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=!1,this._operationFuncs=null,arguments.length===0)s.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];s.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=!0,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,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)=>nn>=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)=>nn>=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 e=(n,i)=>n.Equals(i),t=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,E.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,E.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,n,i){if(this._nativeFunctions===null)return (0, ue.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new s(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,E.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,E.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,E.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,E.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,E.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,E.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,E.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};ti.NativeFunctionCall=A;A.Add="+";A.Subtract="-";A.Divide="/";A.Multiply="*";A.Mod="%";A.Negate="_";A.Equal="==";A.Greater=">";A.Less="<";A.GreaterThanOrEquals=">=";A.LessThanOrEquals="<=";A.NotEquals="!=";A.Not="!";A.And="&&";A.Or="||";A.Min="MIN";A.Max="MAX";A.Pow="POW";A.Floor="FLOOR";A.Ceiling="CEILING";A.Int="INT";A.Float="FLOAT";A.Has="?";A.Hasnt="!?";A.Intersect="^";A.ListMin="LIST_MIN";A.ListMax="LIST_MAX";A.All="LIST_ALL";A.Count="LIST_COUNT";A.ValueOfList="LIST_VALUE";A.Invert="LIST_INVERT";A._nativeFunctions=null;});var ii=C(ni=>{Object.defineProperty(ni,"__esModule",{value:!0});ni.NumberExpression=void 0;var Nc=Ce(),Ts=j(),Ac=k(),xs=class s extends Nc.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new Ts.IntValue(this.value)):this.isFloat()?n.AddContent(new Ts.FloatValue(this.value)):this.isBool()&&n.AddContent(new Ts.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, Ac.asOrNull)(e,s);return t?t.subtype==this.subtype&&t.value==this.value:!1}};ni.NumberExpression=xs;});var ws=C(ri=>{Object.defineProperty(ri,"__esModule",{value:!0});ri.UnaryExpression=void 0;var Ic=Ce(),Fc=Ne(),Tt=ii(),Vc=k(),nn=class extends Ic.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(Fc.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};ri.UnaryExpression=nn;nn.WithInner=(s,e)=>{let t=(0, Vc.asOrNull)(s,Tt.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new Tt.NumberExpression(-t.value,"int");if(t.isFloat())return new Tt.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new Tt.NumberExpression(t.value==0,"bool");if(t.isFloat())return new Tt.NumberExpression(t.value==0,"bool");if(t.isBool())return new Tt.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new nn(s,e)};});var Os=C(si=>{Object.defineProperty(si,"__esModule",{value:!0});si.BinaryExpression=void 0;var kc=Ce(),Rc=Ne(),Dc=ws(),Lc=k(),Ps=class extends kc.Expression{constructor(e,t,n){super(),this.opName=n,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(Rc.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(e),this.rightExpression=this.AddContent(t),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, Lc.asOrNull)(this.leftExpression,Dc.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};si.BinaryExpression=Ps;});var sn=C(ai=>{Object.defineProperty(ai,"__esModule",{value:!0});ai.CharacterSet=void 0;var rn=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,n)=>{for(let i=t.charCodeAt(0);i<=n.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let n of t)this.Add(n);else for(let n of t.set)this.Add(n);return this},e&&this.AddCharacters(e);}};ai.CharacterSet=rn;rn.FromRange=(s,e)=>new rn().AddRange(s,e);});var bl=C(oi=>{Object.defineProperty(oi,"__esModule",{value:!0});oi.CharacterRange=void 0;var Sl=sn(),an=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Sl.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),a;i<=this.end.charCodeAt(0);i+=1)a=String.fromCharCode(i),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},n instanceof Sl.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=an;an.Define=(s,e,t=[])=>new an(s,e,t);});var ui=C(li=>{Object.defineProperty(li,"__esModule",{value:!0});li.ChoicePoint=void 0;var Wc=ae(),qc=se(),Ns=Q(),As=class extends Wc.InkObject{constructor(e=!0){super(),this._pathOnChoice=null,this.hasCondition=!1,this.hasStartContent=!1,this.hasChoiceOnlyContent=!1,this.isInvisibleDefault=!1,this.onceOnly=!0,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, Ns.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Ns.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new qc.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Ns.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};li.ChoicePoint=As;});var st=C(hi=>{Object.defineProperty(hi,"__esModule",{value:!0});hi.PushPopType=void 0;var _l;(function(s){s[s.Tunnel=0]="Tunnel",s[s.Function=1]="Function",s[s.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(_l||(hi.PushPopType=_l={}));});var on=C(ci=>{Object.defineProperty(ci,"__esModule",{value:!0});ci.Pointer=void 0;var jc=se(),Is=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 jc.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(e){return new s(e,0)}static get Null(){return new s(null,-1)}};ci.Pointer=Is;});var Ae=C(fi=>{Object.defineProperty(fi,"__esModule",{value:!0});fi.Divert=void 0;var Mc=se(),Bc=st(),Gc=nt(),Jc=ae(),Fs=on(),El=J(),di=Q(),Vs=class s extends Jc.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=Fs.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=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(e===null)return (0, di.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof El.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Fs.Pointer.StartOf(e instanceof El.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new Mc.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=Fs.Pointer.Null,this.variableDivertName=null,this.pushesToStack=!1,this.stackPushType=0,this.isExternal=!1,this.externalArgs=0,this.isConditional=!1,this.pushesToStack=!1,typeof e<"u"&&(this.pushesToStack=!0,this.stackPushType=e);}Equals(e){let t=e;return t instanceof s&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, di.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):!1}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new Gc.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==Bc.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};fi.Divert=Vs;});var We=C(pi=>{Object.defineProperty(pi,"__esModule",{value:!0});pi.SymbolType=void 0;var Tl;(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";})(Tl||(pi.SymbolType=Tl={}));});var Ge=C(gi=>{Object.defineProperty(gi,"__esModule",{value:!0});gi.VariableAssignment=void 0;var $c=ae(),ks=class extends $c.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=!1;}toString(){return "VarAssign to "+this.variableName}};gi.VariableAssignment=ks;});var xt=C(Ci=>{Object.defineProperty(Ci,"__esModule",{value:!0});Ci.Choice=void 0;var Uc=ui(),mi=J(),Je=Z(),Rs=Ae(),xl=j(),Hc=q(),Kc=We(),wl=Ge(),Ds=class extends Hc.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,n){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=!1,this.hasWeaveStyleInlineBrackets=!1,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new mi.Container,this._runtimeChoice=new Uc.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Je.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new xl.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new wl.VariableAssignment("$r",!0);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Je.ControlCommand.BeginString()),this._divertToStartContentOuter=new Rs.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Rs.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new mi.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Je.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=!0;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Je.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Je.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=!0;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=!0),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Je.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new mi.Container,this.startContent){this._returnToR2=new xl.DivertTargetValue,this._innerContentContainer.AddContent(Je.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Je.ControlCommand.EvalEnd());let i=new wl.VariableAssignment("$r",!0);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Rs.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new mi.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=!0),this._innerContentContainer.countingAtStartOnly=!0,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=e,this.choiceOnlyContent=t,this.innerContent=n,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=!0;}get typeName(){return "Choice"}ResolveReferences(e){var t;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=!0)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Kc.SymbolType.SubFlowAndWeave);}};Ci.Choice=Ds;});var Pl=C(yi=>{Object.defineProperty(yi,"__esModule",{value:!0});yi.StringParserElement=void 0;var vi=class s{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=!1,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{s._uniqueIdCounter++,this.uniqueId=s._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=!1;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};yi.StringParserElement=vi;vi._uniqueIdCounter=1e3;});var Nl=C(Si=>{Object.defineProperty(Si,"__esModule",{value:!0});Si.StringParserState=void 0;var Ol=Pl(),Ls=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new Ol.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(t),n.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],n=this._stack[this._numElements-1];t.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=!0;};let e=200;for(let t=0;t{Object.defineProperty(at,"__esModule",{value:!0});at.StringParser=at.ParseSuccess=void 0;var Ws=sn(),zc=Nl();at.ParseSuccess=Symbol("ParseSuccessStruct");var ln=class s{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=!1,this.BeginRule=()=>this.state.Push(),this.FailRule=n=>(this.state.Pop(n),null),this.CancelRule=n=>{this.state.Pop(n);},this.SucceedRule=(n,i=null)=>{let a=this.state.Peek(n),r=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,r,a),this.state.Squash();let o=i;return o===null&&(o=s.ParseSuccess),o},this.Expect=(n,i=null,a=null)=>{let r=this.ParseObject(n);if(r===null){i===null&&(i=n.name);let o,l=this.LineRemainder();l===null||l.length===0?o="end of line":o=`'${l}'`,this.Error(`Expected ${i} but saw ${o}`),a!==null&&(r=a());}return r},this.Error=(n,i=!1)=>{this.ErrorOnLine(n,this.lineIndex+1,i);},this.ErrorWithParsedObject=(n,i,a=!1)=>{this.ErrorOnLine(n,i.debugMetadata?i.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(n,i,a)=>{if(!this.state.errorReportedAlreadyInScope){let r=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,i-1,a);else throw new Error(`${r} on line ${i}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=!0);},this.Warning=n=>this.Error(n,!0),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(` \r`)),this.SetFlag=(n,i)=>{i?this.state.customFlags|=n:this.state.customFlags&=~n;},this.GetFlag=n=>!!(this.state.customFlags&n),this.ParseObject=n=>{let i=this.BeginRule(),a=this.state.stackHeight,r=n();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return r===null?this.FailRule(i):(this.SucceedRule(i,r),r)},this.Parse=n=>{let i=this.BeginRule(),a=n();return a===null?(this.FailRule(i),null):(this.SucceedRule(i,a),a)},this.OneOf=n=>{for(let i of n){let a=this.ParseObject(i);if(a!==null)return a}return null},this.OneOrMore=n=>{let i=[],a=null;do a=this.ParseObject(n),a!==null&&i.push(a);while(a!==null);return i.length>0?i:null},this.Optional=n=>()=>{let i=this.ParseObject(n);return i===null?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,a=!0)=>{if(n!==s.ParseSuccess){if(a&&Array.isArray(n)){let r=n;if(r!==null){for(let o of r)i.push(o);return}}i.push(n);}},this.Interleave=(n,i,a=null,r=!0)=>{let o=this.BeginRule(),l=[],u=this.ParseObject(n);if(u===null)return this.FailRule(o);this.TryAddResultToList(u,l,r);let h=null,c=null;do{if(a!==null&&this.Peek(a)!==null||(h=this.ParseObject(i),h===null))break;if(this.TryAddResultToList(h,l,r),c=null,h!==null){if(c=this.ParseObject(n),c===null)break;this.TryAddResultToList(c,l,r);}}while((h!==null||c!==null)&&!(h===s.ParseSuccess&&c==s.ParseSuccess)&&this.remainingLength>0);return l.length===0?this.FailRule(o):this.SucceedRule(o,l)},this.ParseString=n=>{if(n.length>this.remainingLength)return null;let i=this.BeginRule(),a=this.index,r=this.characterInLineIndex,o=this.lineIndex,l=!0;for(let u=0;u{if(this.remainingLength>0){let n=this._chars[this.index];return n===` `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,i=-1)=>this.ParseCharactersFromString(n,!1,i),this.ParseUntilCharactersFromCharSet=(n,i=-1)=>this.ParseCharactersFromCharSet(n,!1,i),this.ParseCharactersFromString=(n,i=-1,a=-1)=>{let r=new Ws.CharacterSet(n);return typeof i=="number"?this.ParseCharactersFromCharSet(r,!0,i):this.ParseCharactersFromCharSet(r,i,a)},this.ParseCharactersFromCharSet=(n,i=!0,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let r=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,h=0;for(;or?this._chars.slice(r,this.index).join(""):null},this.Peek=n=>{let i=this.BeginRule(),a=n();return this.CancelRule(i),a},this.ParseInt=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");let r=this.ParseCharactersFromCharSet(s.numbersCharacterSet);if(r===null)return this.index=n,this.characterInLineIndex=i,null;let o;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):(o=Number(r),a?-o:o)},this.ParseFloat=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let r=this.ParseCharactersFromCharSet(s.numbersCharacterSet);return +`${a}.${r}`}return this.index=n,this.characterInLineIndex=i,null},this.ParseNewline=()=>{let n=this.BeginRule();return this.ParseString("\r"),this.ParseString(` `)===null?this.FailRule(n):this.SucceedRule(n,` `)};let t=this.PreProcessInputString(e);this.state=new zc.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,n=null){let i=this.BeginRule(),a=new Ws.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let r="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(r+=l),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(t!==null&&t.set.has(u)){r+=u,u===` `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(!0);return r.length>0?this.SucceedRule(i,String(r)):this.FailRule(i)}};at.StringParser=ln;ln.ParseSuccess=at.ParseSuccess;ln.numbersCharacterSet=new Ws.CharacterSet("0123456789");});var Al=C(bi=>{Object.defineProperty(bi,"__esModule",{value:!0});bi.CommentEliminator=void 0;var js=sn(),Xc=qs(),Ms=class extends Xc.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new js.CharacterSet(`/\r `),this._commentBlockEndCharacter=new js.CharacterSet("*"),this._newlineCharacters=new js.CharacterSet(` \r`),this.Process=()=>{let e=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return e!==null?e.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let e=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return e!==null?e.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>this.ParseString("//")===null?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(this.ParseString("/*")===null)return null;let e=this.lineIndex,t=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),t!=null?` `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};bi.CommentEliminator=Ms;});var Ei=C(_i=>{Object.defineProperty(_i,"__esModule",{value:!0});_i.Conditional=void 0;var Yc=J(),Il=Z(),Qc=q(),Bs=class extends Qc.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new Yc.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let a=i.runtimeObject;n.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(Il.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Il.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=t;}super.ResolveReferences(e);}};_i.Conditional=Bs;});var $e=C(Ti=>{Object.defineProperty(Ti,"__esModule",{value:!0});Ti.Text=void 0;var Zc=q(),ed=j(),Gs=class extends Zc.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new ed.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Ti.Text=Gs;});var wi=C(xi=>{Object.defineProperty(xi,"__esModule",{value:!0});xi.ConstantDeclaration=void 0;var td=q(),nd=We(),Js=class extends td.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,nd.SymbolType.Var);}};xi.ConstantDeclaration=Js;});var wt=C(Pi=>{Object.defineProperty(Pi,"__esModule",{value:!0});Pi.FlowLevel=void 0;var Fl;(function(s){s[s.Story=0]="Story",s[s.Knot=1]="Knot",s[s.Stitch=2]="Stitch",s[s.WeavePoint=3]="WeavePoint";})(Fl||(Pi.FlowLevel=Fl={}));});var un=C(Oi=>{Object.defineProperty(Oi,"__esModule",{value:!0});Oi.Gather=void 0;var id=J(),rd=q(),sd=We(),$s=class extends rd.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let n=new id.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=!0),n.countingAtStartOnly=!0,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"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,sd.SymbolType.SubFlowAndWeave);}};Oi.Gather=$s;});var ot=C(Ai=>{Object.defineProperty(Ai,"__esModule",{value:!0});Ai.Path=void 0;var Ni=k(),Vl=Ie(),Pt=wt(),ad=lt(),Us=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Pt.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(Ni.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Pt.FlowLevel.WeavePoint?"-> ":"":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(n);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=n=>{let i=this.firstComponent,a=n;for(;a;){let r=a===n,o=this.GetChildFromContext(a,i,null,r);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=n=>{let i=n;if(!this.components)return null;for(let a=1;a{let o=a===null,l=(0, Ni.asOrNull)(n,ad.Weave);if(i&&l!==null&&(o||a===Pt.FlowLevel.WeavePoint))return l.WeavePointNamed(i);let u=(0, Ni.asOrNull)(n,Vl.FlowBase);if(i&&u!==null){let h=r||u.flowLevel===Pt.FlowLevel.Knot;return u.ContentWithNameAtLevel(i,a,h)}return null},Object.values(Pt.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};Ai.Path=Us;});var zs=C(Ii=>{Object.defineProperty(Ii,"__esModule",{value:!0});Ii.ReturnType=void 0;var od=q(),ld=J(),Hs=Z(),ud=rt(),Ks=class extends od.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new ld.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(Hs.ControlCommand.EvalStart()),t.AddContent(new ud.Void),t.AddContent(Hs.ControlCommand.EvalEnd())),t.AddContent(Hs.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Ii.ReturnType=Ks;});var hn=C(Fi=>{Object.defineProperty(Fi,"__esModule",{value:!0});Fi.ClosestFlowBase=void 0;function hd(s){let e=s.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}Fi.ClosestFlowBase=hd;});var ki=C(Vi=>{Object.defineProperty(Vi,"__esModule",{value:!0});Vi.Identifier=void 0;var Xs=class s{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new s("DONE")}};Vi.Identifier=Xs;});var Ie=C(Ri=>{Object.defineProperty(Ri,"__esModule",{value:!0});Ri.FlowBase=void 0;var cd=xt(),Ys=Nt(),dd=Ot(),Fe=wt(),fd=un(),pd=q(),gd=ot(),md=zs(),Cd=J(),vd=Ae(),yd=Ge(),Qs=We(),Sd=lt(),bd=hn(),_d=ki(),kl=k(),Zs=class s extends pd.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,n=null,i=!1,a=!1){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=()=>!0,this.SplitWeaveAndSubFlowContent=(r,o)=>{var l,u;let h=[],c=[];this._subFlowsByName=new Map;for(let p of r){let m=(0, kl.asOrNull)(p,s);m?(this._firstChildFlow===null&&(this._firstChildFlow=m),c.push(p),!((l=m.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=m.identifier)===null||u===void 0?void 0:u.name,m)):h.push(p);}o&&h.push(new fd.Gather(null,1),new Ys.Divert(new gd.Path(_d.Identifier.Done())));let f=[];return h.length>0&&(this._rootWeave=new Sd.Weave(h,0),f.push(this._rootWeave)),c.length>0&&f.push(...c),f},this.ResolveVariableWithName=(r,o)=>{var l;let u={},h=o===null?this:(0, bd.ClosestFlowBase)(o);if(h){if(h.args!==null){for(let c of h.args)if(((l=c.identifier)===null||l===void 0?void 0:l.name)===r)return u.found=!0,u.isArgument=!0,u.ownerFlow=h,u}if(h!==this.story&&h.variableDeclarations.has(r))return u.found=!0,u.ownerFlow=h,u.isTemporary=!0,u}return this.story.variableDeclarations.has(r)?(u.found=!0,u.ownerFlow=this.story,u.isGlobal=!0,u):(u.found=!1,u)},this.AddNewVariableDeclaration=r=>{let o=r.variableName;if(this.variableDeclarations.has(o)){let l=this.variableDeclarations.get(o),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${u}`,r,!1);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 o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===Fe.FlowLevel.Knot||this.flowLevel===Fe.FlowLevel.Stitch)&&(o=this.Find(md.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let l=new Cd.Container;l.name=(r=this.identifier)===null||r===void 0?void 0:r.name,this.story.countAllVisits&&(l.visitsShouldBeCounted=!0),this.GenerateArgumentVariableAssignments(l);let u=0;for(;this.content!==null&&u{var o;if(!(this.args===null||this.args.length===0))for(let l=this.args.length-1;l>=0;--l){let u=((o=this.args[l].identifier)===null||o===void 0?void 0:o.name)||null,h=new yd.VariableAssignment(u,!0);r.AddContent(h);}},this.ContentWithNameAtLevel=(r,o=null,l=!1)=>{var u;if((o===this.flowLevel||o===null)&&r===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===Fe.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(r),c))return c;if(o===Fe.FlowLevel.WeavePoint)return l?this.DeepSearchForAnyLevelContent(r):null}if(o!==null&&o{let o=this.ContentWithNameAtLevel(r,Fe.FlowLevel.WeavePoint,!1);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(r,null,!0);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==Fe.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[l,u]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${l}' within the function '${this.identifier}'`,u);if(!this._rootWeave)throw new Error;let r=this._rootWeave.FindAll(Ys.Divert)();for(let l of r)!l.isFunctionCall&&!(l.parent instanceof dd.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(cd.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},this.WarningInTermination=r=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";r.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let l=(0, kl.asOrNull)(r,Ys.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,r);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,Qs.SymbolType.Arg,"argument");for(let i=0;i{Object.defineProperty(Di,"__esModule",{value:!0});Di.ContentList=void 0;var Ed=J(),Td=q(),xd=$e(),wd=k(),ea=class extends Td.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=!1,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let i=(0, wd.asOrNull)(this.content[n],xd.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 Ed.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};Di.ContentList=ea;});var At=C(Wi=>{Object.defineProperty(Wi,"__esModule",{value:!0});Wi.VariableReference=void 0;var Pd=ae(),Od=se(),ta=class extends Pd.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new Od.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};Wi.VariableReference=ta;});var It=C(qi=>{Object.defineProperty(qi,"__esModule",{value:!0});qi.VariableReference=void 0;var Nd=Li(),Ad=Ce(),Rl=Ie(),Id=ot(),Fd=At(),Vd=lt(),kd=ki(),Dl=k(),na=class extends Ad.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(Dl.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new kd.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=!1,this.isListItemReference=!1,this.GenerateIntoContainer=t=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(t),this.isConstantReference=!0;return}if(this._runtimeVarRef=new Fd.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",a="";this.path.length===1?i=this.path[0]:(a=this.path[0],i=this.path[1]),this.story.ResolveListItem(a,i,this)&&(this.isListItemReference=!0);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new Id.Path(this.pathIdentifiers),n=t.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=!0,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let i=(0, Dl.asOrNull)(n,Rl.FlowBase);i&&i.isFunction&&(this.parent instanceof Vd.Weave||this.parent instanceof Nd.ContentList||this.parent instanceof Rl.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: ${t}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};qi.VariableReference=na;});var cn=C(Gi=>{Object.defineProperty(Gi,"__esModule",{value:!0});Gi.FunctionCall=void 0;var Ve=Z(),Rd=Nt(),Dd=Ot(),Ld=Ce(),Wd=le(),qd=j(),Mi=Ne(),Ll=ii(),jd=ot(),Md=j(),Bd=It(),ji=k(),Bi=class s extends Ld.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(e,t){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=!1,this.GenerateIntoContainer=n=>{let i=this.story.ResolveList(this.name),a=!1;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),n.AddContent(Ve.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(Ve.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let r=(0, ji.asOrNull)(this.args[0],Dd.DivertTarget),o=(0, ji.asOrNull)(this.args[0],Bd.VariableReference);if(this.args.length!==1||r===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}r?(this._divertTargetToCount=r,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(Ve.ControlCommand.TurnsSince()):n.AddContent(Ve.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;r1&&(o+="s"),this.Error(o);}for(let o=0;o1&&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 Md.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(Ve.ControlCommand.ListFromInt());else {let r=new Wd.InkList;r.SetInitialOriginName(this.name),n.AddContent(new qd.ListValue(r));}else n.AddContent(this._proxyDivert.runtimeObject),a=!0;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(Ve.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new Rd.Divert(new jd.Path(e),t),this._proxyDivert.isFunctionCall=!0,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,n=t.runtimeDivert.variableDivertName!=null;if(n){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let i=t.targetContent;if(i===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=!0;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${s.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Gi.FunctionCall=Bi;Bi.IsBuiltIn=s=>Mi.NativeFunctionCall.CallExistsWithName(s)?!0:s==="CHOICE_COUNT"||s==="TURNS_SINCE"||s==="TURNS"||s==="RANDOM"||s==="SEED_RANDOM"||s==="LIST_VALUE"||s==="LIST_RANDOM"||s==="READ_COUNT";});var ra=C(Ji=>{Object.defineProperty(Ji,"__esModule",{value:!0});Ji.MultipleConditionExpression=void 0;var Gd=Ce(),Jd=Ne(),ia=class extends Gd.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let n=!0;for(let i of this.subExpressions)i.GenerateIntoContainer(t),n||t.AddContent(Jd.NativeFunctionCall.CallWithName("&&")),n=!1;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Ji.MultipleConditionExpression=ia;});var Ot=C($i=>{Object.defineProperty($i,"__esModule",{value:!0});$i.DivertTarget=void 0;var $d=Os(),Ud=xt(),Hd=Ei(),Kd=la(),zd=j(),sa=Ce(),Xd=Ie(),Wl=cn(),Yd=ra(),ql=It(),aa=k(),oa=class s extends sa.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new zd.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, aa.asOrNull)(t,s);if(!n||!this.divert.target||!n.divert.target)return !1;let i=this.divert.target.dotSeparatedComponents,a=n.divert.target.dotSeparatedComponents;return i===a},this.divert=this.AddContent(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof sa.Expression;){let i=!1,a=!1,r=t.parent;if(r instanceof $d.BinaryExpression){let o=r;o.opName!=="=="&&o.opName!=="!="?i=!0:(o.leftExpression instanceof s||o.leftExpression instanceof ql.VariableReference)&&(o.rightExpression instanceof s||o.rightExpression instanceof ql.VariableReference)||(i=!0),a=!0;}else if(r instanceof Wl.FunctionCall){let o=r;!o.isTurnsSince&&!o.isReadCount&&(i=!0),a=!0;}else (r instanceof sa.Expression||r instanceof Yd.MultipleConditionExpression||r instanceof Ud.Choice&&r.condition===t||r instanceof Hd.Conditional||r instanceof Kd.ConditionalSingleBranch)&&(i=!0,a=!0);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;t=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, aa.asOrNull)(this.parent,Wl.FunctionCall);r&&r.isTurnsSince||(i.visitsShouldBeCounted=!0),i.turnIndexShouldBeCounted=!0;}let a=(0, aa.asOrNull)(n,Xd.FlowBase);if(a!=null&&a.args!==null)for(let r of a.args)r.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${r.identifier}').`);}}};$i.DivertTarget=oa;});var Nt=C(Ui=>{Object.defineProperty(Ui,"__esModule",{value:!0});Ui.Divert=void 0;var Qd=J(),dn=Z(),Zd=Ae(),ua=Ot(),ha=Ie(),ef=cn(),tf=q(),jl=ot(),nf=se(),Ml=st(),rf=j(),Bl=It(),sf=hn(),fn=k(),ca=class extends tf.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=!1,this.isEmpty=!1,this.isTunnel=!1,this.isThread=!1,this.GenerateRuntimeObject=()=>{if(this.isEnd)return dn.ControlCommand.End();if(this.isDone)return dn.ControlCommand.Done();this.runtimeDivert=new Zd.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 Qd.Container;if(n){this.isFunctionCall||i.AddContent(dn.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let r=0;rthis.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, sf.ClosestFlowBase)(this),ha.FlowBase);if(i){let a=i.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let r=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});r&&!r.isDivertTarget&&this.Error(`Since '${r.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${r.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let i=(0, fn.asOrNull)(this.targetContent,ha.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 ua.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==n){let r;n===0?r="but there weren't any passed to it":n ${o.identifier} but saw ${l}`,l);else if(u){let h=new jl.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let i=this.target?this.target.firstComponent:null,a=n.externals.get(i);if(!a)throw new Error("external not found");let r=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==r&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${r} but got ${o}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> ";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, fn.asOrNull)(this.targetContent,ha.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof ua.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let n=this.targetContent!==null,i=!1,a=!1;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=ef.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=!0,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=!1,this.runtimeDivert.targetPath=new nf.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,n=!1){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,n):super.Error(`Divert ${e}`,t,n);}};Ui.Divert=ca;});var Gl=C(Hi=>{Object.defineProperty(Hi,"__esModule",{value:!0});Hi.GatherPointToResolve=void 0;var da=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};Hi.GatherPointToResolve=da;});var Jl=C(Ki=>{Object.defineProperty(Ki,"__esModule",{value:!0});Ki.SequenceDivertToResolve=void 0;var fa=class{constructor(e,t){this.divert=e,this.targetContent=t;}};Ki.SequenceDivertToResolve=fa;});var pa=C(zi=>{Object.defineProperty(zi,"__esModule",{value:!0});zi.SequenceType=void 0;var $l;(function(s){s[s.Stopping=1]="Stopping",s[s.Cycle=2]="Cycle",s[s.Shuffle=4]="Shuffle",s[s.Once=8]="Once";})($l||(zi.SequenceType=$l={}));});var Ca=C(Qi=>{Object.defineProperty(Qi,"__esModule",{value:!0});Qi.Sequence=void 0;var Ul=J(),Ee=Z(),ga=Ae(),pn=j(),Xi=Ne(),af=q(),of=Jl(),Yi=pa(),lf=lt(),ma=class extends af.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new Ul.Container;n.visitsShouldBeCounted=!0,n.countingAtStartOnly=!0,this._sequenceDivertsToResolve=[],n.AddContent(Ee.ControlCommand.EvalStart()),n.AddContent(Ee.ControlCommand.VisitIndex());let i=(this.sequenceType&Yi.SequenceType.Once)>0,a=(this.sequenceType&Yi.SequenceType.Cycle)>0,r=(this.sequenceType&Yi.SequenceType.Stopping)>0,o=(this.sequenceType&Yi.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(i&&(l+=1),r||i?(n.AddContent(new pn.IntValue(l-1)),n.AddContent(Xi.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new pn.IntValue(this.sequenceElements.length)),n.AddContent(Xi.NativeFunctionCall.CallWithName("%"))),o){let h=Ee.ControlCommand.NoOp();if(i||r){let f=r?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(Ee.ControlCommand.Duplicate()),n.AddContent(new pn.IntValue(f)),n.AddContent(Xi.NativeFunctionCall.CallWithName("=="));let p=new ga.Divert;p.isConditional=!0,n.AddContent(p),this.AddDivertToResolve(p,h);}let c=this.sequenceElements.length;r&&(c-=1),n.AddContent(new pn.IntValue(c)),n.AddContent(Ee.ControlCommand.SequenceShuffleIndex()),(i||r)&&n.AddContent(h);}n.AddContent(Ee.ControlCommand.EvalEnd());let u=Ee.ControlCommand.NoOp();for(let h=0;h{this._sequenceDivertsToResolve.push(new of.SequenceDivertToResolve(n,i));},this.sequenceType=t,this.sequenceElements=[];for(let n of e){let i=n.content,a=null;i===null||i.length===0?a=n:a=new lf.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};Qi.Sequence=ma;});var ya=C(Zi=>{Object.defineProperty(Zi,"__esModule",{value:!0});Zi.TunnelOnwards=void 0;var uf=J(),gn=Z(),hf=Ae(),cf=j(),df=q(),ff=rt(),pf=k(),gf=At(),va=class extends df.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new uf.Container;if(e.AddContent(gn.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let r=-1,o=-1;for(let l=0;l` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};Zi.TunnelOnwards=va;});var _a=C(er=>{Object.defineProperty(er,"__esModule",{value:!0});er.ListDefinition=void 0;var Sa=le(),ba=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let n=new Sa.InkListItem(this.name,e);this._items.set(n.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?!1:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[n,i]of this._itemNameToValues)if(i==e)return t=new Sa.InkListItem(this.name,n),{result:t,exists:!0};return t=Sa.InkListItem.Null,{result:t,exists:!1}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:!1};let n=this._itemNameToValues.get(e.itemName);return n?{result:n,exists:!0}:{result:0,exists:!1}}};er.ListDefinition=ba;});var nr=C(tr=>{Object.defineProperty(tr,"__esModule",{value:!0});tr.ListDefinition=void 0;var mf=le(),Cf=le(),vf=_a(),yf=j(),Sf=q(),bf=We(),Ea=class extends Sf.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let n of this.itemDefinitions)t.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):t.set(n.name,n.seriesValue);return new vf.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,i;let a=new mf.InkList;for(let r of this.itemDefinitions)if(r.inInitialList){let o=new Cf.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,r.name||null);a.Add(o,r.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new yf.ListValue(a)};let t=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(t=n.explicitValue),n.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,bf.SymbolType.List);}};tr.ListDefinition=Ea;});var xa=C(ir=>{Object.defineProperty(ir,"__esModule",{value:!0});ir.VariableAssignment=void 0;var _f=J(),Ef=hn(),Tf=nr(),xf=q(),Hl=We(),wf=Ge(),Pf=It(),Of=k(),Ta=class extends xf.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let r=null;if(this.isGlobalDeclaration?r=this.story:this.isNewTemporaryDeclaration&&(r=(0, Ef.ClosestFlowBase)(this)),r&&r.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new _f.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new wf.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!n,i instanceof Tf.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=!0):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?Hl.SymbolType.Var:Hl.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, Of.asOrNull)(this.expression,Pf.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};ir.VariableAssignment=Ta;});var lt=C(ar=>{Object.defineProperty(ar,"__esModule",{value:!0});ar.Weave=void 0;var Kl=Mn(),ye=xt(),rr=Ei(),Nf=wi(),Af=J(),sr=Nt(),If=Ae(),Ff=Ot(),Vf=Ie(),ke=un(),kf=Gl(),Rf=q(),wa=Ca(),Df=$e(),Lf=ya(),Wf=xa(),Se=k(),Pa=class s extends Rf.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let n=this.content.length-1;n>=0;--n){e=this.content[n];let i=(0, Se.asOrNull)(e,Df.Text);if(!(i&&i.text===` `)&&!this.IsGlobalDeclaration(e))break}let t=(0, Se.asOrNull)(e,s);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=!1,this.hasSeenChoiceInSection=!1,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var n,i,a;let r=[...this.FindAll(ke.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(ye.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of r){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof ke.Gather?"gather":"choice",h=l;this.Error(`A ${u} with the same label name '${o.name}' already exists in this context on line ${h.debugMetadata?h.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((i=o.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;nthis.baseIndentIndex){let o=n;for(;n{for(let i of n)if(i instanceof ye.Choice||i instanceof ke.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new Af.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof ye.Choice||n instanceof ke.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=!1;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let r of this.looseEnds){let o=r;if(o instanceof ke.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof sr.Divert)l=o.runtimeObject;else {l=new If.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new kf.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof ke.Gather)this.AddRuntimeForGather(n);else if(n instanceof ye.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof ke.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=!0;}this.addContentToPreviousWeavePoint=!1,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, Se.asOrNull)(n,ye.Choice)&&(this.addContentToPreviousWeavePoint=!0)),this.previousWeavePoint=n;},this.AddRuntimeForNestedWeave=n=>{this.AddGeneralRuntimeContent(n.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=!1);},this.AddGeneralRuntimeContent=n=>{if(n!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(n);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let n=null,i=null,a=!1;for(let r=this.parent;r!==null;r=r.parent){let o=(0, Se.asOrNull)(r,s);o&&(!a&&n===null&&(n=o),a&&i===null&&(i=o)),(r instanceof wa.Sequence||r instanceof rr.Conditional)&&(a=!0);}if(!(n===null&&i===null))for(let r=this.looseEnds.length-1;r>=0;r-=1){let o=this.looseEnds[r],l=!1;if(a){if(o instanceof ye.Choice&&n!==null)n.ReceiveLooseEnd(o),l=!0;else if(!(o instanceof ye.Choice)){let u=n||i;u!==null&&(u.ReceiveLooseEnd(o),l=!0);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(o),l=!0;l&&this.looseEnds.splice(r,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(n);return i||null},this.IsGlobalDeclaration=n=>{let i=(0, Se.asOrNull)(n,Wf.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, Se.asOrNull)(n,Nf.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let i=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||i.push(l);let r=(0, Se.asOrNull)(a.parent,s);if(r===null)throw new Error("Expected weave point parent to be weave?");let o=r.content.indexOf(a);for(let l=o+1;l{if(this.lastParsedSignificantObject instanceof Kl.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let r=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(r,a,n);}else {for(let a of this.content)if(a instanceof ye.Choice||a 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 wa.Sequence||r instanceof rr.Conditional){i=(0, Se.asOrNull)(r,rr.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(ye.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,i,a)=>{let r=!1,o=i;for(let l of n){if(l.Find(sr.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof Ff.DivertTarget))!==null&&(r=!0),l.Find(Lf.TunnelOnwards)()!=null){r=!0;break}o=l;}if(!r){if(o instanceof Kl.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return !0;for(let i=n.content.length-1;i>=0;--i){let a=(0, Se.asOrNull)(n.content[i],sr.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return !1}return !0},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let i of this.ancestry){let a=(0, Se.asOrNull)(i,Vf.FlowBase);if(a)n.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let r of n){let o=r.ContentWithNameAtLevel(i);if(o&&o!==a){let l=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(l,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=!1;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof wa.Sequence||n instanceof rr.Conditional){t=!0;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};ar.Weave=Pa;});var la=C(lr=>{Object.defineProperty(lr,"__esModule",{value:!0});lr.ConditionalSingleBranch=void 0;var zl=J(),or=Z(),Xl=Ae(),qf=q(),jf=Ne(),Mf=j(),Bf=$e(),Gf=lt(),Jf=k(),Oa=class extends qf.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=!1,this.matchingEquality=!1,this.isElse=!1,this.isInline=!1,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let a=(0, Jf.asOrNull)(i,Bf.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new zl.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(or.ControlCommand.Duplicate()),this._conditionalDivert=new Xl.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(or.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(jf.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(or.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new Mf.StringValue(` `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(or.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Xl.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new zl.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new Gf.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};lr.ConditionalSingleBranch=Oa;});var Ql=C(ur=>{Object.defineProperty(ur,"__esModule",{value:!0});ur.CustomFlags=void 0;var Yl;(function(s){s[s.ParsingString=1]="ParsingString",s[s.TagActive=2]="TagActive";})(Yl||(ur.CustomFlags=Yl={}));});var Zl=C(hr=>{Object.defineProperty(hr,"__esModule",{value:!0});hr.DebugMetadata=void 0;var Na=class s{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new s;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumbere.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber{Object.defineProperty(cr,"__esModule",{value:!0});cr.ExternalDeclaration=void 0;var $f=q(),Aa=class extends $f.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};cr.ExternalDeclaration=Aa;});var tu=C(dr=>{Object.defineProperty(dr,"__esModule",{value:!0});dr.FlowDecl=void 0;var Ia=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};dr.FlowDecl=Ia;});var Va=C(fr=>{Object.defineProperty(fr,"__esModule",{value:!0});fr.Wrap=void 0;var Uf=q(),Fa=class extends Uf.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};fr.Wrap=Fa;});var nu=C(pr=>{Object.defineProperty(pr,"__esModule",{value:!0});pr.Glue=void 0;var Hf=Va(),ka=class extends Hf.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};pr.Glue=ka;});var mr=C(gr=>{Object.defineProperty(gr,"__esModule",{value:!0});gr.Glue=void 0;var Kf=ae(),Ra=class extends Kf.InkObject{toString(){return "Glue"}};gr.Glue=Ra;});var ru=C(Cr=>{Object.defineProperty(Cr,"__esModule",{value:!0});Cr.IncDecExpression=void 0;var zf=Li(),iu=Ce(),Xf=Ie(),Yf=Ne(),Qf=j(),Zf=Ge(),ep=At(),tp=lt(),Da=class extends iu.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,r;i.AddContent(new ep.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new Qf.IntValue(1)),i.AddContent(Yf.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new Zf.VariableAssignment(((r=this.varIdentifier)===null||r===void 0?void 0:r.name)||null,!1),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,a;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof iu.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!n):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let n=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof tp.Weave)&&!(this.parent instanceof Xf.FlowBase)&&!(this.parent instanceof zf.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Cr.IncDecExpression=Da;});var Wa=C(vr=>{Object.defineProperty(vr,"__esModule",{value:!0});vr.IncludedFile=void 0;var np=q(),La=class extends np.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};vr.IncludedFile=La;});var su=C(yr=>{Object.defineProperty(yr,"__esModule",{value:!0});yr.InfixOperator=void 0;var qa=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};yr.InfixOperator=qa;});var Ma=C(Sr=>{Object.defineProperty(Sr,"__esModule",{value:!0});Sr.Knot=void 0;var ip=Ie(),au=wt(),ja=class extends ip.FlowBase{get flowLevel(){return au.FlowLevel.Knot}constructor(e,t,n,i){super(e,t,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let n in this.subFlowsByName){let i=t.ContentWithNameAtLevel(n,au.FlowLevel.Knot,!1);if(i){let a=this.subFlowsByName.get(n),r=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(r,a);}}}};Sr.Knot=ja;});var ou=C(br=>{Object.defineProperty(br,"__esModule",{value:!0});br.List=void 0;var rp=Ce(),sp=le(),ap=le(),op=j(),Ba=class extends rp.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,i;let a=new sp.InkList;if(this.itemIdentifierList!=null)for(let r of this.itemIdentifierList){let o=((n=r?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";o.length>1?(l=o[0],u=o[1]):u=o[0];let h=this.story.ResolveListItem(l,u,this);if(h===null)l===null?this.Error(`Could not find list definition that contains item '${r}'`):this.Error(`Could not find list item ${r}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${r}`);return}l||(l=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new ap.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${r}' in list.`):a.Add(c,h.seriesValue);}}t.AddContent(new op.ListValue(a));};}get typeName(){return "List"}};br.List=Ba;});var Ja=C(_r=>{Object.defineProperty(_r,"__esModule",{value:!0});_r.ListElementDefinition=void 0;var lp=q(),up=We(),Ga=class extends lp.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,n=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=n,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,up.SymbolType.ListItem);}};_r.ListElementDefinition=Ga;});var $a=C(Er=>{Object.defineProperty(Er,"__esModule",{value:!0});Er.StatementLevel=void 0;var lu;(function(s){s[s.InnerBlock=0]="InnerBlock",s[s.Stitch=1]="Stitch",s[s.Knot=2]="Knot",s[s.Top=3]="Top";})(lu||(Er.StatementLevel=lu={}));});var Ha=C(Tr=>{Object.defineProperty(Tr,"__esModule",{value:!0});Tr.Stitch=void 0;var hp=Ie(),cp=wt(),Ua=class extends hp.FlowBase{get flowLevel(){return cp.FlowLevel.Stitch}constructor(e,t,n,i){super(e,t,n,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};Tr.Stitch=Ua;});var wr=C(xr=>{Object.defineProperty(xr,"__esModule",{value:!0});xr.Tag=void 0;var dp=ae(),Ka=class extends dp.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};xr.Tag=Ka;});var Xa=C(Pr=>{Object.defineProperty(Pr,"__esModule",{value:!0});Pr.Choice=void 0;var fp=se(),pp=Q(),gp=ae(),za=class s extends gp.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=!1,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, pp.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new fp.Path(e);}Clone(){let e=new s;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};Pr.Choice=za;});var Qa=C(Or=>{Object.defineProperty(Or,"__esModule",{value:!0});Or.ListDefinitionsOrigin=void 0;var mp=le(),Cp=j(),vp=Q(),Ya=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[n,i]of t.items){let a=mp.InkListItem.fromSerializedKey(n),r=new Cp.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,r),this._allUnambiguousListValueCache.set(a.fullName,r);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:!1};let n=this._lists.get(e);return n?{result:n,exists:!0}:{result:t,exists:!1}}FindSingleItemListWithName(e){if(e===null)return (0, vp.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Or.ListDefinitionsOrigin=Ya;});var Vt=C(Fr=>{Object.defineProperty(Fr,"__esModule",{value:!0});Fr.JsonSerialisation=void 0;var Nr=J(),de=j(),uu=mr(),F=Z(),Ft=st(),hu=Ae(),cu=ui(),Za=At(),du=Ge(),eo=Ne(),fu=rt(),pu=wr(),yp=se(),gu=Xa(),Sp=_a(),bp=Qa(),Ar=le(),$=k(),ut=Q(),Ir=class s{static JArrayToRuntimeObjList(e,t=!1){let n=e.length;t&&n--;let i=[];for(let a=0;at->"));let _;i.hasVariableTarget?_=i.variableDivertName:_=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(g,_),i.hasVariableTarget&&e.WriteProperty("var",!0),i.isConditional&&e.WriteProperty("c",!0),i.externalArgs>0&&e.WriteIntProperty("exArgs",i.externalArgs),e.WriteObjectEnd();return}let a=(0, $.asOrNull)(t,cu.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let r=(0, $.asOrNull)(t,de.BoolValue);if(r){e.WriteBool(r.value);return}let o=(0, $.asOrNull)(t,de.IntValue);if(o){e.WriteInt(o.value);return}let l=(0, $.asOrNull)(t,de.FloatValue);if(l){e.WriteFloat(l.value);return}let u=(0, $.asOrNull)(t,de.StringValue);if(u){u.isNewline?e.Write(` `,!1):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(u.value),e.WriteStringEnd());return}let h=(0, $.asOrNull)(t,de.ListValue);if(h){this.WriteInkList(e,h);return}let c=(0, $.asOrNull)(t,de.DivertTargetValue);if(c){if(e.WriteObjectStart(),c.value===null)return (0, ut.throwNullException)("divTargetVal.value");e.WriteProperty("^->",c.value.componentsString),e.WriteObjectEnd();return}let f=(0, $.asOrNull)(t,de.VariablePointerValue);if(f){e.WriteObjectStart(),e.WriteProperty("^var",f.value),e.WriteIntProperty("ci",f.contextIndex),e.WriteObjectEnd();return}if((0, $.asOrNull)(t,uu.Glue)){e.Write("<>");return}let m=(0, $.asOrNull)(t,F.ControlCommand);if(m){e.Write(s._controlCommandNames[m.commandType]);return}let S=(0, $.asOrNull)(t,eo.NativeFunctionCall);if(S){let g=S.name;g=="^"&&(g="L^"),e.Write(g);return}let b=(0, $.asOrNull)(t,Za.VariableReference);if(b){e.WriteObjectStart();let g=b.pathStringForCount;g!=null?e.WriteProperty("CNT?",g):e.WriteProperty("VAR?",b.name),e.WriteObjectEnd();return}let w=(0, $.asOrNull)(t,du.VariableAssignment);if(w){e.WriteObjectStart();let g=w.isGlobal?"VAR=":"temp=";e.WriteProperty(g,w.variableName),w.isNewDeclaration||e.WriteProperty("re",!0),e.WriteObjectEnd();return}if((0, $.asOrNull)(t,fu.Void)){e.Write("void");return}let y=(0, $.asOrNull)(t,pu.Tag);if(y){e.WriteObjectStart(),e.WriteProperty("#",y.text),e.WriteObjectEnd();return}let v=(0, $.asOrNull)(t,gu.Choice);if(v){this.WriteChoice(e,v);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(e[n]);if(i===null)return (0, ut.throwNullException)("inkObject");t.set(n,i);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let n in e)e.hasOwnProperty(n)&&t.set(n,parseInt(e[n]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return de.Value.Create(e);if(typeof e=="string"){let t=e.toString(),n=t[0];if(n=="^")return new de.StringValue(t.substring(1));if(n==` `&&t.length==1)return new de.StringValue(` `);if(t=="<>")return new uu.Glue;for(let i=0;i->")return F.ControlCommand.PopTunnel();if(t=="~ret")return F.ControlCommand.PopFunction();if(t=="void")return new fu.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new de.DivertTargetValue(new yp.Path(n.toString()));if(t["^var"]){n=t["^var"];let h=new de.VariablePointerValue(n.toString());return "ci"in t&&(n=t.ci,h.contextIndex=parseInt(n)),h}let i=!1,a=!1,r=Ft.PushPopType.Function,o=!1;if((n=t["->"])?i=!0:(n=t["f()"])?(i=!0,a=!0,r=Ft.PushPopType.Function):(n=t["->t->"])?(i=!0,a=!0,r=Ft.PushPopType.Tunnel):(n=t["x()"])&&(i=!0,o=!0,a=!1,r=Ft.PushPopType.Function),i){let h=new hu.Divert;h.pushesToStack=a,h.stackPushType=r,h.isExternal=o;let c=n.toString();return (n=t.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!t.c,o&&(n=t.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=t["*"]){let h=new cu.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=t.flg)&&(h.flags=parseInt(n)),h}if(n=t["VAR?"])return new Za.VariableReference(n.toString());if(n=t["CNT?"]){let h=new Za.VariableReference;return h.pathStringForCount=n.toString(),h}let l=!1,u=!1;if((n=t["VAR="])?(l=!0,u=!0):(n=t["temp="])&&(l=!0,u=!1),l){let h=n.toString(),c=!t.re,f=new du.VariableAssignment(h,c);return f.isGlobal=u,f}if(t["#"]!==void 0)return n=t["#"],new pu.Tag(n.toString());if(n=t.list){let h=n,c=new Ar.InkList;if(n=t.origins){let f=n;c.SetInitialOriginNames(f);}for(let f in h)if(h.hasOwnProperty(f)){let p=h[f],m=new Ar.InkListItem(f),S=parseInt(p);c.Add(m,S);}return new de.ListValue(c)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,n){return JSON.stringify(e,(i,a)=>t?.some(r=>r===i)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=!1){if(e.WriteArrayStart(),t===null)return (0, ut.throwNullException)("container");for(let l of t.content)this.WriteRuntimeObject(e,l);let i=t.namedOnlyContent,a=t.countFlags,r=t.name!=null&&!n,o=i!=null||a>0||r;if(o&&e.WriteObjectStart(),i!=null)for(let[l,u]of i){let h=l,c=(0, $.asOrNull)(u,Nr.Container);e.WritePropertyStart(h),this.WriteRuntimeContainer(e,c,!0),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),r&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new Nr.Container;t.content=this.JArrayToRuntimeObjList(e,!0);let n=e[e.length-1];if(n!=null){let i=new Map;for(let a in n)if(a=="#f")t.countFlags=parseInt(n[a]);else if(a=="#n")t.name=n[a].toString();else {let r=this.JTokenToRuntimeObject(n[a]),o=(0, $.asOrNull)(r,Nr.Container);o&&(o.name=a),i.set(a,r);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new gu.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, ut.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of n){let r=Ar.InkListItem.fromSerializedKey(i),o=a;if(r.itemName===null)return (0, ut.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(r.originName?r.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(r.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of n.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let i={};for(let[a,r]of n.items){let o=Ar.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, ut.throwNullException)("item.itemName");i[o.itemName]=r;}t[n.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),r=t[i],o=new Map;for(let u in r)if(t.hasOwnProperty(i)){let h=r[u];o.set(u,parseInt(h));}let l=new Sp.ListDefinition(a,o);n.push(l);}return new bp.ListDefinitionsOrigin(n)}};Fr.JsonSerialisation=Ir;Ir._controlCommandNames=(()=>{let s=[];s[F.ControlCommand.CommandType.EvalStart]="ev",s[F.ControlCommand.CommandType.EvalOutput]="out",s[F.ControlCommand.CommandType.EvalEnd]="/ev",s[F.ControlCommand.CommandType.Duplicate]="du",s[F.ControlCommand.CommandType.PopEvaluatedValue]="pop",s[F.ControlCommand.CommandType.PopFunction]="~ret",s[F.ControlCommand.CommandType.PopTunnel]="->->",s[F.ControlCommand.CommandType.BeginString]="str",s[F.ControlCommand.CommandType.EndString]="/str",s[F.ControlCommand.CommandType.NoOp]="nop",s[F.ControlCommand.CommandType.ChoiceCount]="choiceCnt",s[F.ControlCommand.CommandType.Turns]="turn",s[F.ControlCommand.CommandType.TurnsSince]="turns",s[F.ControlCommand.CommandType.ReadCount]="readc",s[F.ControlCommand.CommandType.Random]="rnd",s[F.ControlCommand.CommandType.SeedRandom]="srnd",s[F.ControlCommand.CommandType.VisitIndex]="visit",s[F.ControlCommand.CommandType.SequenceShuffleIndex]="seq",s[F.ControlCommand.CommandType.StartThread]="thread",s[F.ControlCommand.CommandType.Done]="done",s[F.ControlCommand.CommandType.End]="end",s[F.ControlCommand.CommandType.ListFromInt]="listInt",s[F.ControlCommand.CommandType.ListRange]="range",s[F.ControlCommand.CommandType.ListRandom]="lrnd",s[F.ControlCommand.CommandType.BeginTag]="#",s[F.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e{Object.defineProperty(vn,"__esModule",{value:!0});vn.CallStack=void 0;var to=st(),mu=se(),_p=yn(),Cu=Vt(),Ep=j(),Tp=nt(),mn=on(),xp=Ht(),vu=bt(),no=Q(),Cn=class s{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){xp.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=mn.Pointer.Null,arguments[0]instanceof _p.Story){let e=arguments[0];this._startOfRoot=mn.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new s.Thread),this._threads[0].callstack.push(new s.Element(to.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let i of n){let a=i,r=new s.Thread(a,t);this._threads.push(r);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=mn.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let n of this._threads)n.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==to.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let i=new s.Element(e,this.currentElement.currentPointer,!1);i.evaluationStackHeightWhenPushed=t,i.functionStartInOutputStream=n,this.callStack.push(i);}CanPop(e=null){return this.canPop?e==null?!0:this.currentElement.type==e:!1}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let n=this.callStack[t-1],i=(0, vu.tryGetValueFromMap)(n.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let r=(0, vu.tryGetValueFromMap)(a.temporaryVariables,e,null);r.exists&&Ep.ListValue.RetainListOriginsForAssignment(r.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new Tp.StringBuilder;for(let t=0;t");}}}return e.toString()}};vn.CallStack=Cn;(function(s){class e{constructor(i,a,r=!1){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=r,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}s.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=mn.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let r=i.callstack;for(let l of r){let u=l,h=parseInt(u.type),c=mn.Pointer.Null,f,p=u.cPath;if(typeof p<"u"){f=p.toString();let w=a.ContentAtPath(new mu.Path(f));if(c.container=w.container,c.index=parseInt(u.idx),w.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+f+". Has the story changed since this save data was created?");w.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let m=!!u.exp,S=new e(h,c,m),b=u.temp;typeof b<"u"?S.temporaryVariables=Cu.JsonSerialisation.JObjectToDictionaryRuntimeObjs(b):S.temporaryVariables.clear(),this.callstack.push(S);}let o=i.previousContentObject;if(typeof o<"u"){let l=new mu.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let i=new t;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, no.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",a.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",a.currentPointer.index);}i.WriteProperty("exp",a.inExpressionEvaluation),i.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),Cu.JsonSerialisation.WriteDictionaryRuntimeObjs(i,a.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, no.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}s.Thread=t;})(Cn||(vn.CallStack=Cn={}));});var Su=C(kr=>{Object.defineProperty(kr,"__esModule",{value:!0});kr.VariablesState=void 0;var Y=j(),wp=zt(),yu=Vt(),ee=k(),Sn=bt(),Ue=Q();function Pp(){return class{}}var Vr=class s extends Pp(){variableChangedEvent(e,t){for(let n of this.variableChangedEventCallbacks)n(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=!0,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=!1;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let n=this._globalVariables.get(t);this.variableChangedEvent(t,n);}if(this.patch!=null)for(let t of this.patch.changedVariables){let n=this.patch.TryGetGlobal(t,null);n.exists&&e.set(t,n);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,n]of e)this.variableChangedEvent(t,n);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(e),typeof n>"u"&&(n=this._defaultGlobalVariables.get(e)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new wp.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=Y.Value.Create(t);if(n==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,n);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=!1,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,r){return a in i?i[a]=r:i.$(a,r),!0}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Ue.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,n]of this._defaultGlobalVariables){let i=e[t];if(typeof i<"u"){let a=yu.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Ue.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let i=t,a=n;if(s.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let r=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,r))continue}e.WritePropertyStart(i),yu.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Ue.throwNullException)("obj1");if(t===null)return (0, Ue.throwNullException)("obj2");if(e.constructor!==t.constructor)return !1;let n=(0, ee.asOrNull)(e,Y.BoolValue);if(n!==null)return n.value===(0, ee.asOrThrows)(t,Y.BoolValue).value;let i=(0, ee.asOrNull)(e,Y.IntValue);if(i!==null)return i.value===(0, ee.asOrThrows)(t,Y.IntValue).value;let a=(0, ee.asOrNull)(e,Y.FloatValue);if(a!==null)return a.value===(0, ee.asOrThrows)(t,Y.FloatValue).value;let r=(0, ee.asOrNull)(e,Y.Value),o=(0, ee.asOrNull)(t,Y.Value);if(r!==null&&o!==null)return (0, ee.isEquatable)(r.valueObject)&&(0, ee.isEquatable)(o.valueObject)?r.valueObject.Equals(o.valueObject):r.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let n=this.GetRawVariableWithName(e,t),i=(0, ee.asOrNull)(n,Y.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(e){let t=(0, Sn.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let n=null;if(t==0||t==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(e,null),i.exists)||(i=(0, Sn.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Sn.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Ue.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(e,t),n}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let n=e.variableName;if(n===null)return (0, Ue.throwNullException)("name");let i=-1,a=!1;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let r=(0, ee.asOrNull)(t,Y.VariablePointerValue);r!==null&&(t=this.ResolveVariablePointer(r));}else {let r=null;do r=(0, ee.asOrNull)(this.GetRawVariableWithName(n,i),Y.VariablePointerValue),r!=null&&(n=r.variableName,i=r.contextIndex,a=i==0);while(r!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, ee.asOrThrows)(e,Y.ListValue),i=(0, ee.asOrThrows)(t,Y.ListValue);n.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(e,t){let n=null;if(this.patch===null&&(n=(0, Sn.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, Sn.tryGetValueFromMap)(this._globalVariables,e,null))),Y.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, Ue.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&n!==null&&t!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Ue.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let n=this.GetRawVariableWithName(e.variableName,t),i=(0, ee.asOrNull)(n,Y.VariablePointerValue);return i??new Y.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};kr.VariablesState=Vr;Vr.dontSaveDefaultValues=!0;});var so=C(Rr=>{Object.defineProperty(Rr,"__esModule",{value:!0});Rr.PRNG=void 0;var ro=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};Rr.PRNG=ro;});var bu=C(Dr=>{Object.defineProperty(Dr,"__esModule",{value:!0});Dr.StatePatch=void 0;var ao=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:!0}:{result:t,exists:!1}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:!0}:{result:t,exists:!1}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:!0}:{result:t,exists:!1}}};Dr.StatePatch=ao;});var oo=C(_n=>{Object.defineProperty(_n,"__esModule",{value:!0});_n.SimpleJson=void 0;var bn=class s{static TextToDictionary(e){return new s.Reader(e).ToDictionary()}static TextToArray(e){return new s.Reader(e).ToArray()}};_n.SimpleJson=bn;(function(s){class e{constructor(i){this._rootObject=JSON.parse(i);}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}s.Reader=e;class t{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(!0);let i={};if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===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,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let r=arguments[1];r(this);}else {let r=arguments[1];this.Write(r);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===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(!0);let i=[];if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===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,a=!0){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(!1),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(!1),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(!1),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(!1),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(!1),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(!1),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,a=!0){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=t,function(n){(function(r){r[r.None=0]="None",r[r.Object=1]="Object",r[r.Array=2]="Array",r[r.Property=3]="Property",r[r.PropertyName=4]="PropertyName",r[r.String=5]="String";})(n.State||(n.State={}));class a{constructor(o){this.type=s.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;}(t=s.Writer||(s.Writer={}));})(bn||(_n.SimpleJson=bn={}));});var Eu=C(Wr=>{Object.defineProperty(Wr,"__esModule",{value:!0});Wr.Flow=void 0;var _u=io(),Lr=Vt(),Op=Q(),lo=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new _u.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=Lr.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=Lr.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let i=n.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),e.WriteProperty("outputStream",n=>Lr.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=!1;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, Op.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(t||(t=!0,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let i of this.currentChoices)Lr.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let a=e[`${n.originalThreadIndex}`];n.threadAtGeneration=new _u.CallStack.Thread(a,t);}}}};Wr.Flow=lo;});var wu=C(jr=>{Object.defineProperty(jr,"__esModule",{value:!0});jr.StoryState=void 0;var Np=io(),Ap=Su(),K=j(),He=st(),Ip=wr(),uo=mr(),Tu=se(),ie=Z(),ho=nt(),Ke=Vt(),Fp=so(),Vp=rt(),kt=on(),En=bt(),U=k(),kp=Ht(),be=Q(),Rp=yn(),Dp=bu(),xu=oo(),qr=Eu(),Lp=le(),co=class s{ToJson(e=!1){let t=new xu.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=!1){return this.ToJson(e)}LoadJson(e){let t=xu.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let n=this.story.ContentAtPath(new Tu.Path(e)).container;if(n===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(n,0),t.exists)return t.result}return t=(0, En.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, be.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(e,0);if(i.exists)return i.result}let t=e.path.toString(),n=(0, En.tryGetValueFromMap)(this._visitCounts,t,null);return n.exists?n.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let i=this.VisitCountForContainer(e);i++,this._patch.SetVisitCount(e,i);return}let t=e.path.toString(),n=(0, En.tryGetValueFromMap)(this._visitCounts,t,null);n.exists?this._visitCounts.set(t,n.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(e,0);if(i.exists)return this.currentTurnIndex-i.result}let t=e.path.toString(),n=(0, En.tryGetValueFromMap)(this._turnIndices,t,0);return n.exists?this.currentTurnIndex-n.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, be.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, be.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new ho.StringBuilder,t=!1;for(let n of this.outputStream){let i=(0, U.asOrNull)(n,K.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, U.asOrNull)(n,ie.ControlCommand);a!==null&&(a.commandType==ie.ControlCommand.CommandType.BeginTag?t=!0:a.commandType==ie.ControlCommand.CommandType.EndTag&&(t=!1));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=!1;}return this._currentText}CleanOutputWhitespace(e){let t=new ho.StringBuilder,n=-1,i=0;for(let a=0;a0&&n!=i&&t.Append(" "),n=-1),r==` `&&(i=a+1),o||t.Append(r);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=!1,t=new ho.StringBuilder;for(let n of this.outputStream){let i=(0, U.asOrNull)(n,ie.ControlCommand);if(i!=null){if(i.commandType==ie.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=!0;}else if(i.commandType==ie.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=!1;}}else if(e){let a=(0, U.asOrNull)(n,K.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, U.asOrNull)(n,Ip.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let n=this.CleanOutputWhitespace(t.toString());this._currentTags.push(n),t.Clear();}this._outputStreamTagsDirty=!1;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=!1;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=kt.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=!1,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=!0,this.story=e,this._currentFlow=new qr.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=!0,this._evaluationStack=[],this._variablesState=new Ap.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new Fp.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=kt.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,n=(0, En.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new qr.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=!0),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, be.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=!0;}CopyAndStartPatching(e){let t=new s(this.story);if(t._patch=new Dp.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new Np.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let n of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(n.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[n,i]of this._namedFlows)t._namedFlows.set(n,i),t._aliveFlowNamesDirty=!0;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,!0);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,!1);this._patch=null;}}ApplyCountChanges(e,t,n){(n?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,n]of this._namedFlows)e.WriteProperty(t,i=>n.WriteJson(i));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>Ke.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, be.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Ke.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Ke.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",Rp.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,n=t.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)1){let l=t.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=Ke.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Ke.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let r=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(r,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=!0,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Ke.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let r=new Tu.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(r);}this._visitCounts=Ke.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Ke.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, U.asOrNull)(e,K.StringValue);if(t!==null){let n=this.TrySplittingHeadTailWhitespace(t);if(n!==null){for(let i of n)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, be.throwNullException)("single.value");let n=-1,i=-1;for(let h=0;h=0;h--){let c=t[h];if(c==` `)a==-1&&(a=h),r=h;else {if(c==" "||c==" ")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=t.length;if(n!=-1){if(n>0){let h=new K.StringValue(t.substring(0,n));o.push(h);}o.push(new K.StringValue(` `)),l=i+1;}if(a!=-1&&(u=r),u>l){let h=t.substring(l,u);o.push(new K.StringValue(h));}if(a!=-1&&r>i&&(o.push(new K.StringValue(` `)),a=0;u--){let h=this.outputStream[u],c=h instanceof ie.ControlCommand?h:null;if((h instanceof uo.Glue?h:null)!=null){o=u;break}else if(c!=null&&c.commandType==ie.ControlCommand.CommandType.BeginString){u>=a&&(a=-1);break}}let l=-1;if(o!=-1&&a!=-1?l=Math.min(a,o):o!=-1?l=o:l=a,l!=-1){if(n.isNewline)i=!1;else if(n.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let u=this.callStack.elements;for(let h=u.length-1;h>=0;h--){let c=u[h];if(c.type==He.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=!1);}if(i){if(e===null)return (0, be.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let n=this.outputStream[t],i=(0, U.asOrNull)(n,ie.ControlCommand),a=(0, U.asOrNull)(n,K.StringValue);if(i!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t=0;e--){let t=this.outputStream[e];if(t instanceof uo.Glue)this.outputStream.splice(e,1);else if(t instanceof ie.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof ie.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof K.StringValue){if(n.isNewline)return !0;if(n.isNonWhitespace)break}}return !1}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof K.StringValue)return !0;return !1}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, U.asOrNull)(this.outputStream[e],ie.ControlCommand);if(t instanceof ie.ControlCommand&&t.commandType==ie.ControlCommand.CommandType.BeginString)return !0}return !1}PushEvaluationStack(e){let t=(0, U.asOrNull)(e,K.ListValue);if(t){let n=t.value;if(n===null)return (0, be.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, be.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, be.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, be.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, U.nullIfUndefined)(t)}else {if(e>this.evaluationStack.length)throw new Error("trying to pop too many objects");let t=this.evaluationStack.splice(this.evaluationStack.length-e,e);return (0, U.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=kt.Pointer.Null,this.previousPointer=kt.Pointer.Null,this.didSafeExit=!0;}TrimWhitespaceFromFunctionEnd(){kp.Debug.Assert(this.callStack.currentElement.type==He.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let n=this.outputStream[t],i=(0, U.asOrNull)(n,K.StringValue),a=(0, U.asOrNull)(n,ie.ControlCommand);if(i!=null){if(a)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==He.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(e);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(He.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=kt.Pointer.StartOf(e),this.PassArgumentsToEvaluationStack(t);}PassArgumentsToEvaluationStack(e){if(e!==null)for(let t=0;te;){let n=this.PopEvaluationStack();t===null&&(t=n);}if(this.PopCallStack(He.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof Vp.Void)return null;let n=(0, U.asOrThrows)(t,K.Value);return n.valueType==K.ValueType.DivertTarget?n.valueObject.toString():n.valueObject}return null}AddError(e,t){t?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(e)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(e));}OutputStreamDirty(){this._outputStreamTextDirty=!0,this._outputStreamTagsDirty=!0;}};jr.StoryState=co;});var Pu=C(Mr=>{Object.defineProperty(Mr,"__esModule",{value:!0});Mr.Stopwatch=void 0;var fo=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=fo;});var Nu=C(Br=>{Object.defineProperty(Br,"__esModule",{value:!0});Br.ErrorType=void 0;var Ou;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(Ou||(Br.ErrorType=Ou={}));});var yn=C(dt=>{Object.defineProperty(dt,"__esModule",{value:!0});dt.Story=dt.InkList=void 0;var te=J(),po=ae(),go=Vt(),Wp=wu(),O=Z(),_e=st(),qp=ui(),jp=Xa(),Au=Ae(),T=j(),mo=se(),Tn=rt(),Gr=wr(),Mp=Ge(),Bp=At(),Gp=Ne(),ht=zt(),Co=so(),ct=nt(),Jp=Qa(),$p=Pu(),ze=on(),xn=le(),N=k(),V=Q(),Iu=oo(),Fu=Nu(),Up=le();Object.defineProperty(dt,"InkList",{enumerable:!0,get:function(){return Up.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var Rt=class s extends po.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, V.throwNullException)("this._state");for(let t of this._state.currentChoices)t.isInvisibleDefault||(t.index=e.length,e.push(t));return e}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=!1,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=!1,this._temporaryEvaluationContainer=null,this._asyncContinueActive=!1,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=!1,this._recursiveContinueCount=0,this._asyncSaving=!1,this._profiler=null;let e,t=null,n=null;if(arguments[0]instanceof te.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let i=arguments[0];n=Iu.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new Jp.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let i=n,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let r=parseInt(a);if(r>s.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(rgo.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[i,a]of n.items){let r=xn.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(r.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new Wp.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, V.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, V.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new mo.Path("global decl"),!1),this.ContinueInternal(),this.state.currentPointer=e;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(e){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+e);this.state.SwitchFlow_Internal(e);}RemoveFlow(e){this.state.RemoveFlow_Internal(e);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(e){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(e);}ContinueInternal(e=0){this._profiler!=null&&this._profiler.PreContinue();let t=e>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!t&&(this._asyncContinueActive=!1);else {if(this._asyncContinueActive=t,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=!1,this._state.ResetOutput(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation();}let n=new $p.Stopwatch;n.Start();let i=!1;this._sawLookaheadUnsafeFunctionAfterNewline=!1;do{try{i=this.ContinueSingleStep();}catch(r){if(!(r instanceof ht.StoryException))throw r;this.AddError(r.message,void 0,r.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(_e.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(_e.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=!1,this._sawLookaheadUnsafeFunctionAfterNewline=!1,this._recursiveContinueCount==1&&(a=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=!1,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,Fu.ErrorType.Error);if(this.state.hasWarning)for(let r of this.state.currentWarnings)this.onError(r,Fu.ErrorType.Warning);this.ResetErrors();}else {let r=new ct.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 ht.StoryException(r.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, V.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, V.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==s.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),!0;e==s.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),!1}CalculateNewlineOutputStateChange(e,t,n,i){if(e===null)return (0, V.throwNullException)("prevText");if(t===null)return (0, V.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==` `;if(n==i&&e.length==t.length&&a)return s.OutputStateChange.NoChange;if(!a)return s.OutputStateChange.NewlineRemoved;if(i>n)return s.OutputStateChange.ExtendedBeyondNewline;for(let r=e.length;r0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+i.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(!1);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, V.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let e=this._state;return this._state=this._state.CopyAndStartPatching(!0),this._asyncSaving=!0,e}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=!1;}Step(){let e=!0,t=this.state.currentPointer.copy();if(t.isNull)return;let n=(0, N.asOrNull)(t.Resolve(),te.Container);for(;n&&(this.VisitContainer(n,!0),n.content.length!=0);)t=ze.Pointer.StartOf(n),n=(0, N.asOrNull)(t.Resolve(),te.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=t.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(e=!1);let r=(0, N.asOrNull)(i,qp.ChoicePoint);if(r){let l=this.ProcessChoice(r);l&&this.state.generatedChoices.push(l),i=null,e=!1;}if(i instanceof te.Container&&(e=!1),e){let l=(0, N.asOrNull)(i,T.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);i=new T.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, N.asOrNull)(i,O.ControlCommand);o&&o.commandType==O.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let r=e.Resolve(),o=(0, N.asOrNull)(r,te.Container)||(0, N.asOrNull)(e.container,te.Container);for(;o;)this._prevContainers.push(o),o=(0, N.asOrNull)(o.parent,te.Container);}let n=t.Resolve();if(n==null)return;let i=(0, N.asOrNull)(n.parent,te.Container),a=!0;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let r=i.content.length>0&&n==i.content[0]&&a;r||(a=!1),this.VisitContainer(i,r),n=i,i=(0, N.asOrNull)(i.parent,te.Container);}}PopChoiceStringAndTags(e){let t=(0, N.asOrThrows)(this.state.PopEvaluationStack(),T.StringValue);for(;this.state.evaluationStack.length>0&&(0, N.asOrNull)(this.state.PeekEvaluationStack(),Gr.Tag)!=null;){let n=(0, N.asOrNull)(this.state.PopEvaluationStack(),Gr.Tag);n&&e.push(n.text);}return t.value}ProcessChoice(e){let t=!0;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=!1);}let n="",i="",a=[];if(e.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=!1),!t)return null;let r=new jp.Choice;return r.targetPath=e.pathOnChoice,r.sourcePath=e.path.toString(),r.isInvisibleDefault=e.isInvisibleDefault,r.threadAtGeneration=this.state.callStack.ForkThread(),r.tags=a.reverse(),r.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),r}IsTruthy(e){let t=!1;if(e instanceof T.Value){let n=e;if(n instanceof T.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)"),!1}return n.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return !1;if(e instanceof Au.Divert){let t=e;if(t.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return !0}if(t.hasVariableTarget){let n=t.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 T.DivertTargetValue)){let r=(0, N.asOrNull)(i,T.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";r instanceof T.IntValue&&r.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, N.asOrThrows)(i,T.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),!0;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),!0}else if(e instanceof O.ControlCommand){let t=e;switch(t.commandType){case O.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===!1,"Already in expression evaluation?"),this.state.inExpressionEvaluation=!0;break;case O.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===!0,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=!1;break;case O.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let g=this.state.PopEvaluationStack();if(!(g instanceof Tn.Void)){let _=new T.StringValue(g.toString());this.state.PushToOutputStream(_);}}break;case O.ControlCommand.CommandType.NoOp:break;case O.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case O.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case O.ControlCommand.CommandType.PopFunction:case O.ControlCommand.CommandType.PopTunnel:let n=t.commandType==O.ControlCommand.CommandType.PopFunction?_e.PushPopType.Function:_e.PushPopType.Tunnel,i=null;if(n==_e.PushPopType.Tunnel){let g=this.state.PopEvaluationStack();i=(0, N.asOrNull)(g,T.DivertTargetValue),i===null&&this.Assert(g instanceof Tn.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let g=new Map;g.set(_e.PushPopType.Function,"function return statement (~ return)"),g.set(_e.PushPopType.Tunnel,"tunnel onwards statement (->->)");let _=g.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(_="end of flow (-> END or choice)");let I="Found "+g.get(n)+", when expected "+_;this.Error(I);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case O.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(t),this.Assert(this.state.inExpressionEvaluation===!0,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=!1;break;case O.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case O.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let g=[],_=0;for(let R=this.state.outputStream.length-1;R>=0;--R){let B=this.state.outputStream[R];_++;let pe=(0, N.asOrNull)(B,O.ControlCommand);if(pe!=null){if(pe.commandType==O.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}B instanceof T.StringValue&&g.push(B);}this.state.PopFromOutputStream(_);let I=new ct.StringBuilder;for(let R of g.reverse())I.Append(R.toString());let fe=new Gr.Tag(this.state.CleanOutputWhitespace(I.toString()));this.state.PushEvaluationStack(fe);}else this.state.PushToOutputStream(t);break}case O.ControlCommand.CommandType.EndString:{let g=[],_=[],I=0;for(let R=this.state.outputStream.length-1;R>=0;--R){let B=this.state.outputStream[R];I++;let pe=(0, N.asOrNull)(B,O.ControlCommand);if(pe&&pe.commandType==O.ControlCommand.CommandType.BeginString)break;B instanceof Gr.Tag&&_.push(B),B instanceof T.StringValue&&g.push(B);}this.state.PopFromOutputStream(I);for(let R of _)this.state.PushToOutputStream(R);g=g.reverse();let fe=new ct.StringBuilder;for(let R of g)fe.Append(R.toString());this.state.inExpressionEvaluation=!0,this.state.PushEvaluationStack(new T.StringValue(fe.toString()));break}case O.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new T.IntValue(a));break;case O.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new T.IntValue(this.state.currentTurnIndex+1));break;case O.ControlCommand.CommandType.TurnsSince:case O.ControlCommand.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof T.DivertTargetValue)){let g="";r instanceof T.IntValue&&(g=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+r+g);break}let o=(0, N.asOrThrows)(r,T.DivertTargetValue),l=(0, N.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,te.Container),u;l!=null?t.commandType==O.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(t.commandType==O.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new T.IntValue(u));break;case O.ControlCommand.CommandType.Random:{let g=(0, N.asOrNull)(this.state.PopEvaluationStack(),T.IntValue),_=(0, N.asOrNull)(this.state.PopEvaluationStack(),T.IntValue);if(_==null||!(_ instanceof T.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(g==null||!(g instanceof T.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(g.value===null)return (0, V.throwNullException)("maxInt.value");if(_.value===null)return (0, V.throwNullException)("minInt.value");let I=g.value-_.value+1;(!isFinite(I)||I>Number.MAX_SAFE_INTEGER)&&(I=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),I<=0&&this.Error("RANDOM was called with minimum as "+_.value+" and maximum as "+g.value+". The maximum must be larger");let fe=this.state.storySeed+this.state.previousRandom,B=new Co.PRNG(fe).next(),pe=B%I+_.value;this.state.PushEvaluationStack(new T.IntValue(pe)),this.state.previousRandom=B;break}case O.ControlCommand.CommandType.SeedRandom:let h=(0, N.asOrNull)(this.state.PopEvaluationStack(),T.IntValue);if(h==null||!(h instanceof T.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, V.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new Tn.Void);break;case O.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new T.IntValue(c));break;case O.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new T.IntValue(f));break;case O.ControlCommand.CommandType.StartThread:break;case O.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=!0,this.state.currentPointer=ze.Pointer.Null);break;case O.ControlCommand.CommandType.End:this.state.ForceEnd();break;case O.ControlCommand.CommandType.ListFromInt:let p=(0, N.asOrNull)(this.state.PopEvaluationStack(),T.IntValue),m=(0, N.asOrThrows)(this.state.PopEvaluationStack(),T.StringValue);if(p===null)throw new ht.StoryException("Passed non-integer when creating a list element from a numerical value.");let S=null;if(this.listDefinitions===null)return (0, V.throwNullException)("this.listDefinitions");let b=this.listDefinitions.TryListGetDefinition(m.value,null);if(b.exists){if(p.value===null)return (0, V.throwNullException)("minInt.value");let g=b.result.TryGetItemWithValue(p.value,xn.InkListItem.Null);g.exists&&(S=new T.ListValue(g.result,p.value));}else throw new ht.StoryException("Failed to find LIST called "+m.value);S==null&&(S=new T.ListValue),this.state.PushEvaluationStack(S);break;case O.ControlCommand.CommandType.ListRange:let w=(0, N.asOrNull)(this.state.PopEvaluationStack(),T.Value),d=(0, N.asOrNull)(this.state.PopEvaluationStack(),T.Value),y=(0, N.asOrNull)(this.state.PopEvaluationStack(),T.ListValue);if(y===null||d===null||w===null)throw new ht.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(y.value===null)return (0, V.throwNullException)("targetList.value");let v=y.value.ListWithSubRange(d.valueObject,w.valueObject);this.state.PushEvaluationStack(new T.ListValue(v));break;case O.ControlCommand.CommandType.ListRandom:{let g=this.state.PopEvaluationStack();if(g===null)throw new ht.StoryException("Expected list for LIST_RANDOM");let _=g.value,I=null;if(_===null)throw (0, V.throwNullException)("list");if(_.Count==0)I=new xn.InkList;else {let fe=this.state.storySeed+this.state.previousRandom,B=new Co.PRNG(fe).next(),pe=B%_.Count,pt=_.entries();for(let Wo=0;Wo<=pe-1;Wo++)pt.next();let Lo=pt.next().value,Fn={Key:xn.InkListItem.fromSerializedKey(Lo[0]),Value:Lo[1]};if(Fn.Key.originName===null)return (0, V.throwNullException)("randomItem.Key.originName");I=new xn.InkList(Fn.Key.originName,this),I.Add(Fn.Key,Fn.Value),this.state.previousRandom=B;}this.state.PushEvaluationStack(new T.ListValue(I));break}default:this.Error("unhandled ControlCommand: "+t);break}return !0}else if(e instanceof Mp.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),!0}else if(e instanceof Bp.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);n=new T.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(t.name),n==null&&(this.Warning("Variable not found: '"+t.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),n=new T.IntValue(0));return this.state.PushEvaluationStack(n),!0}else if(e instanceof Gp.NativeFunctionCall){let t=e,n=this.state.PopEvaluationStack(t.numberOfParameters),i=t.Call(n);return this.state.PushEvaluationStack(i),!0}return !1}ChoosePathString(e,t=!0,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,n),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==_e.PushPopType.Function){let i="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(i="("+a.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace: `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new mo.Path(e));}IfAsyncWeCant(e){if(this._asyncContinueActive)throw new Error("Can't "+e+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(e,t=!0){this.state.SetChosenPath(e,t),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(e){e=e;let t=this.currentChoices;this.Assert(e>=0&&et&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, V.throwNullException)("funcName");let n=this._externals.get(e),i=null,a=typeof n<"u";if(a&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+e+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+e+"()"),a&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=!0;return}if(!a)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(e),this.Assert(i!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(_e.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=ze.Pointer.StartOf(i);return}else this.Assert(!1,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let r=[];for(let u=0;u{this.Assert(i.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let r=0,o=i.length;r1?"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(e!=null){for(let i of e.content){let a=i;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(i,n);}for(let[,i]of e.namedContent)this.ValidateExternalBindings((0, N.asOrNull)(i,po.InkObject),n);}else if(t!=null){let i=(0, N.asOrNull)(t,Au.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, V.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.add(a);}}}ObserveVariable(e,t){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(e))throw new Error("Cannot observe variable '"+e+"' because it wasn't declared in the ink story.");this._variableObservers.has(e)?this._variableObservers.get(e).push(t):this._variableObservers.set(e,[t]);}ObserveVariables(e,t){for(let n=0,i=e.length;n=t.container.content.length;){e=!1;let n=(0, N.asOrNull)(t.container.parent,te.Container);if(!(n instanceof te.Container))break;let i=n.content.indexOf(t.container);if(i==-1)break;if(t=new ze.Pointer(n,i),t.index++,e=!0,t.container===null)return (0, V.throwNullException)("pointer.container")}return e||(t=ze.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(i=>i.isInvisibleDefault);if(t.length==0||e.length>t.length)return !1;let n=t[0];return n.targetPath===null?(0, V.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, V.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,!1),!0)}NextSequenceShuffleIndex(){let e=(0, N.asOrNull)(this.state.PopEvaluationStack(),T.IntValue);if(!(e instanceof T.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, V.throwNullException)("seqContainer");if(e.value===null)return (0, V.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, N.asOrThrows)(this.state.PopEvaluationStack(),T.IntValue).value;if(a===null)return (0, V.throwNullException)("seqCount");let r=a/n,o=a%n,l=t.path.toString(),u=0;for(let p=0,m=l.length;p=0;--n)if(t=this.state.callStack.elements[n].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.outputStream.length-1;n>=0;--n)if(e=this.state.outputStream[n].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};dt.Story=Rt;Rt.inkVersionCurrent=21;(function(s){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(s.OutputStateChange||(s.OutputStateChange={}));})(Rt||(dt.Story=Rt={}));});var ku=C(Kr=>{Object.defineProperty(Kr,"__esModule",{value:!0});Kr.Story=void 0;var Hp=Mn(),Kp=wi(),Jr=J(),$r=Z(),wn=Ln(),Ur=Ie(),Vu=wt(),zp=Wa(),Xp=nr(),Yp=Ja(),Qp=yn(),Dt=We(),Zp=$e(),eg=Ge(),Pn=k(),tg=hn(),ng=cn(),ig=ot(),Hr=class s extends Ur.FlowBase{get flowLevel(){return Vu.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(e,t=!1){super(null,e,null,!1,t),this._errorHandler=null,this._hadError=!1,this._hadWarning=!1,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=!1,this.ExportRuntime=(n=null)=>{var i,a;this._errorHandler=n,this.constants=new Map;for(let h of this.FindAll(Kp.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let f=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(f,h,!1);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(Xp.ListDefinition)())!((i=h.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=h.identifier)===null||a===void 0?void 0:a.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let r=this.runtimeObject,o=new Jr.Container;o.AddContent($r.ControlCommand.EvalStart());let l=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),o.AddContent(c.listDefinition.runtimeObject),l.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(o);}let f=new eg.VariableAssignment(h,!0);f.isGlobal=!0,o.AddContent(f);}o.AddContent($r.ControlCommand.EvalEnd()),o.AddContent($r.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",r.AddToNamedContentOnly(o)),r.AddContent($r.ControlCommand.Done());let u=new Qp.Story(r,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(r),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,a=null)=>{let r=null;if(n)return (r=this._listDefs.get(n))?r.ItemNamed(i):null;{let o=null,l=null;for(let[,u]of this._listDefs.entries()){let h=u.ItemNamed(i);h&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,!1):(o=h,l=u));}return o}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let a of n.content){let r=(0, Pn.asOrNull)(a,Jr.Container);r&&i.add(r);}if(n.namedContent)for(let[,a]of n.namedContent){let r=(0, Pn.asOrNull)(a,Jr.Container);r&&i.add(r);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let i=(0, Pn.asOrNull)(n.parent,Jr.Container);if(i){let a=i.content.indexOf(n);i.content.splice(a,1);let r=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,r!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=r),i.InsertContent(o,a),a+=1;}},this.Error=(n,i,a)=>{let r=a?wn.ErrorType.Warning:wn.ErrorType.Error,o="";if(i instanceof Hp.AuthorWarning?(o+="TODO: ",r=wn.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(o+=`'${i.debugMetadata.fileName}' `),o+=`line ${i.debugMetadata.startLineNumber}: `),o+=n,n=o,this._errorHandler!==null)this._errorHandler(n,r);else throw new Error(n);this._hadError=r===wn.ErrorType.Error,this._hadWarning=r===wn.ErrorType.Warning;},this.ResetError=()=>{this._hadError=!1,this._hadWarning=!1;},this.IsExternal=n=>this.externals.has(n),this.AddExternal=n=>{this.externals.has(n.name)?this.Error(`Duplicate EXTERNAL definition of '${n.name}'`,n,!1):n.name&&this.externals.set(n.name,n);},this.DontFlattenContainer=n=>{this._dontFlattenContainers.add(n);},this.NameConflictError=(n,i,a,r)=>{n.Error(`${r} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,i,a,r="")=>{var o;let l=r||n.typeName;if(s.IsReservedKeyword(i?.name)){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(ng.FunctionCall.IsBuiltIn(i?.name||"")){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(i?.name||"",Vu.FlowLevel.Knot),h=(0, Pn.asOrNull)(u,Ur.FlowBase);if(h&&(h!==n||a===Dt.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,l);return}if(a{switch(s){case"true":case"false":case"not":case"return":case"else":case"VAR":case"CONST":case"temp":case"LIST":case"function":return !0}return !1};});var Du=C(zr=>{Object.defineProperty(zr,"__esModule",{value:!0});zr.StringExpression=void 0;var Ru=Z(),rg=Ce(),sg=$e(),ag=k(),vo=class s extends rg.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof sg.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(Ru.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(Ru.ControlCommand.EndString());},this.toString=()=>{let t="";for(let n of this.content)t+=n;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, ag.asOrNull)(e,s);if(t===null||!this.isSingleString||!t.isSingleString)return !1;let n=this.toString(),i=t.toString();return n===i}};zr.StringExpression=vo;});var Wu=C(Lt=>{Object.defineProperty(Lt,"__esModule",{value:!0});Lt.LegacyTag=Lt.Tag=void 0;var og=q(),Lu=Z(),yo=class extends og.ParsedObject{constructor(e,t=!1){super(),this.GenerateRuntimeObject=()=>this.isStart?Lu.ControlCommand.BeginTag():Lu.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};Lt.Tag=yo;var lg=Va(),So=class extends lg.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};Lt.LegacyTag=So;});var qu=C(Xr=>{Object.defineProperty(Xr,"__esModule",{value:!0});Xr.DefaultFileHandler=void 0;var bo=class{constructor(e){this.rootPath=e,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};Xr.DefaultFileHandler=bo;});var xo=C(es=>{Object.defineProperty(es,"__esModule",{value:!0});es.InkParser=void 0;var ug=ll(),hg=Mn(),cg=Os(),Te=bl(),X=sn(),dg=xt(),fg=Al(),pg=Ei(),On=la(),he=Li(),gg=wi(),Yr=Ql(),mg=Zl(),ft=Nt(),_o=Ot(),Cg=Ce(),vg=eu(),ju=tu(),Qr=cn(),yg=un(),Sg=nu(),bg=mr(),Zr=ru(),Mu=Wa(),_g=su(),Eg=Ma(),Bu=ou(),Tg=nr(),xg=Ja(),wg=ra(),Gu=q(),Pg=ot(),Ju=zs(),$u=Ca(),z=pa(),re=$a(),Og=Ha(),Uu=ku(),Nn=Du(),qe=qs(),Wt=Wu(),je=$e(),Hu=ya(),Eo=xa(),To=It(),Ng=ws(),Xe=k(),An=ki(),qt=ii(),Ku=Ln(),Ag=qu(),D=class s extends qe.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,n=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let r=this.StatementsAtLevel(re.StatementLevel.Top);return new Uu.Story(r,this._rootParser!==this)},this.SeparatedList=(r,o)=>{let l=this.Parse(r);if(l===null)return null;let u=[];u.push(l);do{let h=this.BeginRule();if(o()===null){this.FailRule(h);break}let f=this.Parse(r);if(f===null){this.FailRule(h);break}this.SucceedRule(h),u.push(f);}while(!0);return u},this.CreateDebugMetadata=(r,o)=>{let l=new mg.DebugMetadata;return l.startLineNumber=(r?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(r?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(r,o,l)=>{let u=(0, Xe.asOrNull)(r,Gu.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let h=Array.isArray(r)?r:null;if(h!==null)for(let f of h)(0, Xe.asOrNull)(f,Gu.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,l)));let c=(0, Xe.asOrNull)(r,An.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(r,o,l=0,u=!1)=>{let c=u?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${l+1}: ${r}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,u?Ku.ErrorType.Warning:Ku.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 o=this.ParseUntilCharactersFromString(` \r`);return o?new hg.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=r=>{let o=s.ListAllCharacterRanges();for(let l of o)r.AddCharacters(l.ToCharacterSet());},this._parsingChoice=!1,this.Choice=()=>{let r=!0,o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!o){if(o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),o===null)return null;r=!1;}let l=this.Parse(this.BracketedName);this.Whitespace(),l!=null&&this.Newline();let u=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=!0;let h=null,c=this.Parse(this.MixedTextAndLogic);c&&(h=new he.ContentList(c));let f=null,p=null,m=this.ParseString("[")!==null;if(m){this.EndTagIfNecessary(h);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(f=new he.ContentList(d)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let y=this.Parse(this.MixedTextAndLogic);y!==null&&(p=new he.ContentList(y));}this.Whitespace(),this.EndTagIfNecessary(p??h);let S=this.Parse(this.MultiDivert);this._parsingChoice=!1,this.Whitespace();let b=!h&&!p&&!f;if(b&&S===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&m&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),p||(p=new he.ContentList),this.EndTagIfNecessary(p),S!==null)for(let d of S){let y=(0, Xe.asOrNull)(d,ft.Divert);y&&y.isEmpty||p.AddContent(d);}p.AddContent(new je.Text(` `));let w=new dg.Choice(h,f,p);return l&&(w.identifier=l),w.indentationDepth=o.length,w.hasWeaveStyleInlineBrackets=m,w.condition=u,w.onceOnly=r,w.isInvisibleDefault=b,w},this.ChoiceCondition=()=>{let r=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return r===null?null:r.length===1?r[0]:new wg.MultipleConditionExpression(r)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),qe.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 o=Number(r),l=this.Parse(this.BracketedName),u=new yg.Gather(l,o);return this.Newline(),u},this.GatherDashes=()=>{this.Whitespace();let r=0;for(;this.ParseDashNotArrow()!==null;)r+=1,this.Whitespace();return r===0?null:r},this.ParseDashNotArrow=()=>{let r=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(r):this.FailRule(r)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),r)},this.InnerConditionalContent=r=>{if(r===void 0){let c=this.Parse(this.ConditionExpression),f=this.Parse(()=>this.InnerConditionalContent(c));return f===null?null:f}let o,l=r!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(r){let c=this.StatementsAtLevel(re.StatementLevel.InnerBlock);if(c!==null){o=[new On.ConditionalSingleBranch(c)];let p=this.Parse(this.SingleMultilineCondition);p&&(p.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",p),p.isElse=!0),o.push(p));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&r){let c=new On.ConditionalSingleBranch(null);c.isTrueBranch=!0,o.unshift(c);}if(r){let c=!1;for(let f=0;f2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",p):f===0?p.isTrueBranch=!0:p.isElse=!0;}}else {for(let c=0;c{let r=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,!1);if(r===null||r.length===0)return null;let o=[];if(r.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let l=new On.ConditionalSingleBranch(r[0]);if(l.isTrueBranch=!0,o.push(l),r.length>1){let u=new On.ConditionalSingleBranch(r[1]);u.isElse=!0,o.push(u);}}return o},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,o=this.Parse(this.ElseExpression)!==null;o||(r=this.Parse(this.ConditionExpression));let l=this.StatementsAtLevel(re.StatementLevel.InnerBlock);r===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new je.Text("")]),this.MultilineWhitespace();let u=new On.ConditionalSingleBranch(l);return u.ownExpression=r,u.isElse=o,u},this.ConditionExpression=()=>{let r=this.Parse(this.Expression);return r===null||(this.DisallowIncrement(r),this.Whitespace(),this.ParseString(":")===null)?null:r},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:qe.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(r,o)=>{if(r.length>0){let l=r.length-1,u=r[l];if(u instanceof je.Text){let h=u;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),o?h.text+=" ":h.text.length===0&&(r.splice(l,1),this.TrimEndWhitespace(r,!1));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let r=this.Parse(this.MixedTextAndLogic);if(!r||!r.length)return null;let o=r[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),r.length===0?null:(r[r.length-1]instanceof ft.Divert||this.TrimEndWhitespace(r,!1),this.EndTagIfNecessary(r),r.length>0&&r[0]instanceof Wt.Tag&&r[0].isStart||r.push(new je.Text(` `)),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 o=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let l=this.Parse(this.MultiDivert);l!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,!0),o.push(...l));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let r=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(r===null&&(r=""),o!==null&&(r+=String(o)),l){let u=this.ParseSingleCharacter();r+=u;}}else break}while(!0);return r!==null?new je.Text(r):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new X.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new X.CharacterSet(`{}| \r\\#`),this._notTextEndCharactersChoice=new X.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new X.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let r=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let l=this.ParseUntil(r,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let r=[],o=this.Parse(this.StartThread);if(o)return r=[o],r;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;r=[],this.EndTagIfNecessary(r);for(let u=0;u->"){u===0||u===l.length-1||u===l.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let f=new Hu.TunnelOnwards;if(u) 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 ft.Divert(null));return r.isThread=!0,r},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let r=this.Parse(this.DotSeparatedDivertPathComponents);if(!r)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new Pg.Path(r);return new ft.Divert(l,o)},this.SingleDivert=()=>{let r=this.Parse(this.MultiDivert);if(!r||r.length!==1||r[0]instanceof Hu.TunnelOnwards)return null;let l=r[0];return l.isTunnel?null:l},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let r=0;for(;this.ParseString("->")!==null;)r+=1;return r===0?null:r===1?"->":(r===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let r=this.ParseTempKeyword();this.Whitespace();let o=null;if(r?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let l=this.ParseString("+")!==null,u=this.ParseString("-")!==null;if(l&&u&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return r&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return l||u?new Zr.IncDecExpression(o,h,l):new Eo.VariableAssignment({variableIdentifier:o,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),!0):(this.FailRule(r),!1)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new Ju.ReturnType(o)},this.Expression=(r=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>r){let h=`right side of '${u.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(o,u),h);if(c===null)return this.FailRule(l),null;o=this.SucceedRule(l,c);continue}this.FailRule(l);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let r=this.Parse(this.ExpressionDivertTarget);if(r!==null)return r;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&o!==null&&(l=this.ExpressionUnary()),l===null)return null;o!==null&&(l=Ng.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof To.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new Zr.IncDecExpression(c.identifier,h);}}return l},this.ExpressionNot=()=>{let r=this.Identifier();return r==="not"?r:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let r=this.Parse(this.SingleDivert);return !r||r&&r.isThread?null:(this.Whitespace(),new _o.DivertTarget(r))},this.ExpressionInt=()=>{let r=this.ParseInt();return r===null?null:new qt.NumberExpression(r,"int")},this.ExpressionFloat=()=>{let r=this.ParseFloat();return r===null?null:new qt.NumberExpression(r,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=!0;let o=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=!1,o===null?o=[new je.Text("")]:o.find(l=>l instanceof ft.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Nn.StringExpression(o)},this.ExpressionBool=()=>{let r=this.Parse(this.Identifier);return r==="true"?new qt.NumberExpression(!0,"bool"):r==="false"?new qt.NumberExpression(!1,"bool"):null},this.ExpressionFunctionCall=()=>{let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new Qr.FunctionCall(r,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,r);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let r=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return r===null||Uu.Story.IsReservedKeyword(r[0].name)?null:new To.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,o)=>{if(!r)return null;this.Whitespace();let l=this.Parse(()=>this.Expression(o.precedence));return l?new cg.BinaryExpression(r,l,o.type):null},this.ParseInfixOperator=()=>{for(let r of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(r.type)!==null){if(r.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,r)}this.FailRule(o);}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 Bu.List(r)},this.ListMember=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${r}`);r.name+=`.${l?.name}`;}return this.Whitespace(),r},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,!0),this.RegisterBinaryOperator("or",1,!0),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,!0),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,!0),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,!0);},this.RegisterBinaryOperator=(r,o,l=!1)=>{let u=new _g.InfixOperator(r,o,l);this._binaryOperators.push(u),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,r.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let r=this.Expect(()=>this.ParseUntilCharactersFromString(` \r`),"filename for include statement");r=r.replace(new RegExp(/[ \t]+$/g),"");let o=this.fileHandler.ResolveInkFilename(r);if(this.FilenameIsAlreadyOpen(o))return this.Error(`Recursive INCLUDE detected: '${o}' is already open.`),this.ParseUntilCharactersFromString(`\r `),new Mu.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o);}catch(h){this.Error(`Failed to load: '${r}'. Error:${h}`);}return u!=null&&(l=new s(u,r,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new Mu.IncludedFile(l)},this.FilenameIsAlreadyOpen=r=>this._rootParser._openFilenames.includes(r),this.AddOpenFilename=r=>{this._rootParser._openFilenames.push(r);},this.RemoveOpenFilename=r=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(r),1);},this.KnotDefinition=()=>{let r=this.Parse(this.KnotDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(re.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new Eg.Knot(r.name,l,r.args,r.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata),o,l=r?.name==="function";l?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=r,o===null&&(this.Error(`Expected the name of the ${l?"function":"knot"}`),o=new An.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new ju.FlowDecl(o,u,l)},this.KnotTitleEquals=()=>{let r=this.ParseCharactersFromString("=");return r===null||r.length<=1?null:r},this.StitchDefinition=()=>{let r=this.Parse(this.StitchDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(re.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new Og.Stitch(r.name,l,r.args,r.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let r=this.ParseString("function")!==null;r&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new ju.FlowDecl(o,l,r)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new X.CharacterSet("="),null),[new je.Text("")]),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 o=this.ParseDivertArrow();this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(r==null&&l===null)return null;let u=new ug.Argument;return o!==null&&(u.isDivertTarget=!0),r!==null&&r.name==="ref"?(l===null&&this.Error("Expected an parameter name after 'ref'"),u.identifier=l,u.isByReference=!0):(u.isDivertTarget?u.identifier=l:u.identifier=r,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=!1),u},this.ExternalDeclaration=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new An.Identifier("");this.Whitespace();let l=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);l===null&&(l=[]);let u=l.map(h=>{var c;return (c=h.identifier)===null||c===void 0?void 0:c.name}).filter(Xe.filterUndef);return new vg.ExternalDeclaration(o,u)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let r=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(r,"expression after '~'",this.SkipToNextLine);if(o===null)return new he.ContentList;o instanceof Cg.Expression&&!(o instanceof Qr.FunctionCall||o instanceof Zr.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like: ~ return ~ var x = blah ~ x++ ~ myFunction()`);let l=(0, Xe.asOrNull)(o,Qr.FunctionCall);return l&&(l.shouldPopReturnedValue=!0),o.Find(Qr.FunctionCall)()!==null&&(o=new he.ContentList(o,new je.Text(` `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u?(u instanceof qt.NumberExpression||u instanceof Nn.StringExpression||u instanceof _o.DivertTarget||u instanceof To.VariableReference||u instanceof Bu.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):u instanceof Nn.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new Eo.VariableAssignment({assignedExpression:u,isGlobalDeclaration:!0,variableIdentifier:o})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let l=this.Expect(this.ListDefinition,"list item names");return l?(l.identifier=new An.Identifier(o.name),new Eo.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let r=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return r===null?null:new Tg.ListDefinition(r)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let r=this.ParseString("(")!==null,o=r;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),r&&this.ParseString(")")!=null&&(o=!1,this.Whitespace());let u=null;if(this.ParseString("=")!==null){this.Whitespace();let h=this.Expect(this.ExpressionInt,"value to be assigned to list item");h!==null&&(u=h.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=!1));}return o&&this.Error("Expected closing ')'"),new xg.ListElementDefinition(l,r,u)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l instanceof qt.NumberExpression||l instanceof _o.DivertTarget||l instanceof Nn.StringExpression?l instanceof Nn.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new gg.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new Sg.Glue(new bg.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let r=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let l=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(l===null)return this.parsingStringExpression=r,null;this.DisallowIncrement(l);let u=(0, Xe.asOrNull)(l,he.ContentList);return u||(u=new he.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=r,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let r=this.ParseObject(this.SequenceTypeAnnotation);if(r!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new $u.Sequence(u,r)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let l=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let u of l){let h=this.BeginRule(),c=this.ParseObject(u);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let r=this.Parse(this.Expression);return r&&(r.outputWhenComplete=!0),r},this.IdentifierWithMetadata=()=>{let r=this.Identifier();return r===null?null:new An.Identifier(r)},this.Identifier=()=>{let r=this.ParseCharactersFromCharSet(this.identifierCharSet);if(r===null)return null;let o=!0;for(let l of r)if(!(l>="0"&&l<="9")){o=!1;break}return o?null:r},this._sequenceTypeSymbols=new X.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let r=z.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(r=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new $u.Sequence(l,r)},this.SequenceTypeAnnotation=()=>{let r=this.Parse(this.SequenceTypeSymbolAnnotation);if(r===null&&(r=this.Parse(this.SequenceTypeWordAnnotation)),r===null)return null;switch(r){case z.SequenceType.Once:case z.SequenceType.Cycle:case z.SequenceType.Stopping:case z.SequenceType.Shuffle:case z.SequenceType.Shuffle|z.SequenceType.Stopping:case z.SequenceType.Shuffle|z.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${r}`),z.SequenceType.Stopping}return r},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new X.CharacterSet("!&~$ "));let r=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case"!":r|=z.SequenceType.Once;break;case"&":r|=z.SequenceType.Cycle;break;case"~":r|=z.SequenceType.Shuffle;break;case"$":r|=z.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 o=0;for(let l of r)o|=l;return o},this.SequenceTypeSingleWord=()=>{let r=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case"once":r=z.SequenceType.Once;break;case"cycle":r=z.SequenceType.Cycle;break;case"shuffle":r=z.SequenceType.Shuffle;break;case"stopping":r=z.SequenceType.Stopping;break}return r===null?null:r},this.InnerSequenceObjects=()=>{let r=this.Parse(this.Newline)!==null,o=null;return r?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let r=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,!1);if(r===null)return null;let o=[],l=!1;for(let u of r)if(u==="|")l||o.push(new he.ContentList),l=!1;else {let h=u;h===null?this.Error(`Expected content, but got ${u} (this is an ink compiler bug!)`):o.push(new he.ContentList(h)),l=!0;}return l||o.push(new he.ContentList),o},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(re.StatementLevel.InnerBlock);return r===null?this.MultilineWhitespace():r.unshift(new je.Text(` `)),new he.ContentList(r)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=r=>(r===re.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 o=this._statementRulesAtLevel[r],l=this.OneOf(o);return r===re.StatementLevel.Top&&l instanceof Ju.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=r=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[r],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let r=Object.values(re.StatementLevel);this._statementRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]);for(let o of r){let l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=re.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>re.StatementLevel.InnerBlock&&l.push(this.Gather),o>=re.StatementLevel.Knot&&l.push(this.StitchDefinition),l.push(this.Line(this.ListDeclaration)),l.push(this.Line(this.VariableDeclaration)),l.push(this.Line(this.ConstDeclaration)),l.push(this.Line(this.ExternalDeclaration)),l.push(this.Line(this.IncludeStatement)),l.push(this.LogicLine),l.push(this.LineOfMixedTextAndLogic),o<=re.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=re.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=re.StatementLevel.InnerBlock&&(u.push(this.ParseDashNotArrow),u.push(this.String("}"))),this._statementRulesAtLevel[o]=l,this._statementBreakRulesAtLevel[o]=u;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(` \r`),this.ParseNewline(),qe.ParseSuccess),this.Line=r=>()=>{let o=this.ParseObject(r);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let r=null;if(this.tagActive){let o=new he.ContentList;o.AddContent(new Wt.Tag(!1)),o.AddContent(new Wt.Tag(!0)),r=o;}else r=new Wt.Tag(!0);return this.tagActive=!0,this.Whitespace(),r},this._inlineWhitespaceChars=new X.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?qe.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?qe.ParseSuccess:null),this.MultilineWhitespace=()=>{let r=this.OneOrMore(this.Newline);return r===null?null:r.length>=1?qe.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?qe.ParseSuccess:null,this.Spaced=r=>()=>{this.Whitespace();let o=this.ParseObject(r);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let r=!1;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)r=!0;return r?qe.ParseSuccess:null},this.MultiSpaced=r=>()=>{this.AnyWhitespace();let o=this.ParseObject(r);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new Ag.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let r=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(r);}}else this._rootParser=i;}PreProcessInputString(e){return new fg.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(Yr.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(Yr.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(Yr.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(Yr.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new X.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(e){this.tagActive&&(e!=null&&(e instanceof he.ContentList?e.AddContent(new Wt.Tag(!1)):e.push(new Wt.Tag(!1))),this.tagActive=!1);}};es.InkParser=D;D.LatinBasic=Te.CharacterRange.Define("A","z",new X.CharacterSet().AddRange("[","`"));D.LatinExtendedA=Te.CharacterRange.Define("\u0100","\u017F");D.LatinExtendedB=Te.CharacterRange.Define("\u0180","\u024F");D.Greek=Te.CharacterRange.Define("\u0370","\u03FF",new X.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));D.Cyrillic=Te.CharacterRange.Define("\u0400","\u04FF",new X.CharacterSet().AddRange("\u0482","\u0489"));D.Armenian=Te.CharacterRange.Define("\u0530","\u058F",new X.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));D.Hebrew=Te.CharacterRange.Define("\u0590","\u05FF",new X.CharacterSet);D.Arabic=Te.CharacterRange.Define("\u0600","\u06FF",new X.CharacterSet);D.Korean=Te.CharacterRange.Define("\uAC00","\uD7AF",new X.CharacterSet);D.Latin1Supplement=Te.CharacterRange.Define("\x80","\xFF",new X.CharacterSet);D.Chinese=Te.CharacterRange.Define("\u4E00","\u9FFF",new X.CharacterSet);D.ListAllCharacterRanges=()=>[D.LatinBasic,D.LatinExtendedA,D.LatinExtendedB,D.Arabic,D.Armenian,D.Cyrillic,D.Greek,D.Hebrew,D.Korean,D.Latin1Supplement,D.Chinese];});var zu=C(ts=>{Object.defineProperty(ts,"__esModule",{value:!0});ts.GenerateStoryStats=void 0;var Ig=xt(),Fg=Nt(),Vg=un(),kg=Ma(),Rg=Ha(),Dg=$e();function Lg(s){let e=s.FindAll(Dg.Text)(),t=0;for(let l of e){let u=0,h=!0;for(let c of l.text)c==" "||c==" "||c==` `||c=="\r"?h=!0:h&&(u++,h=!1);t+=u;}let n=s.FindAll(kg.Knot)(),i=s.FindAll(Rg.Stitch)(),a=s.FindAll(Ig.Choice)(),r=s.FindAll(Vg.Gather)(l=>l.debugMetadata!=null),o=s.FindAll(Fg.Divert)();return {words:t,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:i.length,gathers:r.length,diverts:o.length-1,choices:a.length}}ts.GenerateStoryStats=Lg;});var Xu=C(ns=>{Object.defineProperty(ns,"__esModule",{value:!0});ns.JsonFileHandler=void 0;var wo=class{constructor(e){this.fileHierarchy=e,this.ResolveInkFilename=t=>{if(Object.keys(this.fileHierarchy).includes(t))return t;throw new Error(`Cannot locate ${t}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=t=>{if(Object.keys(this.fileHierarchy).includes(t))return this.fileHierarchy[t];throw new Error(`Cannot open ${t}.`)};}};ns.JsonFileHandler=wo;});var Qu=C(ne=>{Object.defineProperty(ne,"__esModule",{value:!0});ne.Compiler=ne.Story=ne.InkList=ne.JsonFileHandler=ne.StatementLevel=ne.InkParser=ne.CompilerOptions=void 0;var Wg=us(),qg=al(),Po=Ln(),jg=xo(),Mg=j(),Bg=k(),Gg=zu(),Jg=us();Object.defineProperty(ne,"CompilerOptions",{enumerable:!0,get:function(){return Jg.CompilerOptions}});var $g=xo();Object.defineProperty(ne,"InkParser",{enumerable:!0,get:function(){return $g.InkParser}});var Ug=$a();Object.defineProperty(ne,"StatementLevel",{enumerable:!0,get:function(){return Ug.StatementLevel}});var Hg=Xu();Object.defineProperty(ne,"JsonFileHandler",{enumerable:!0,get:function(){return Hg.JsonFileHandler}});var Yu=yn();Object.defineProperty(ne,"InkList",{enumerable:!0,get:function(){return Yu.InkList}});Object.defineProperty(ne,"Story",{enumerable:!0,get:function(){return Yu.Story}});var Oo=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(e,t=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new jg.InkParser(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),this.errors.length===0?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var n;for(let i of this.runtimeStory.state.outputStream){let a=(0, Bg.asOrNull)(i,Mg.StringValue);if(a!==null){let r=new qg.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(r);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, Gg.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let i=0,a=null;for(let r of this.debugSourceRanges){if(r.debugMetadata!==null&&(a=r.debugMetadata),n>=i&&n{switch(i){case Po.ErrorType.Author:this._authorMessages.push(n);break;case Po.ErrorType.Warning:this._warnings.push(n);break;case Po.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=e,this._options=t||new Wg.CompilerOptions;}};ne.Compiler=Oo;});var jo="\xA7SPACE\xA7",Mo="\xA7DOUBLE_QUOTES\xA7",Bo="\xA7QUOTES\xA7",Go="SPECIAL_\xA7QUOTES\xA7",Jo="\xA7CURLY_BRACKETS1\xA7",$o="\xA7CURLY_BRACKETS2\xA7",Uo=["show","edit","remove","move"],_h=["add","play","pause","resume","remove","volume"],et=class s{static _customHashtagScript=e=>!1;static runCustomHashtagScript(e,t){return s._customHashtagScript(e,t,s.convertListStringToObj)}static set customHashtagScript(e){s._customHashtagScript=e;}static async generateOrRunOperationFromHashtagScript(e,t,n){try{e=e.replaceAll('\\"',Mo),e=e.replaceAll("\\'",Bo),e=e.replaceAll("\\`",Go),e=e.replaceAll("\\{",Jo),e=e.replaceAll("\\}",$o),e=e.replaceAll("{"," { "),e=e.replaceAll("}"," } "),e=e.replaceAll(Jo,"{"),e=e.replaceAll($o,"}");let i=[],a,r="";for(let u=0;u{h%2===1&&(i[h]=u.replaceAll(" ",jo));}),e=i.join(""),i=e.split(" ").filter(u=>u!==""),i=i.map(u=>u.replaceAll(jo," ").replaceAll(Mo,'"').replaceAll(Bo,"'").replaceAll(Go,"`")),s.runCustomHashtagScript(i,n))return;let o=i.length>1?s.removeExtraDoubleQuotes(i[1]):"",l=i.length>0?s.removeExtraDoubleQuotes(i[0]):"";switch(o){case"image":return s.getImageOperationFromComment(i,"image");case"video":if(Uo.includes(l))return s.getImageOperationFromComment(i,"video");if(l==="pause"||l==="resume")return {type:"video",operationType:l,alias:s.removeExtraDoubleQuotes(i[2])};case"sound":return s.getSoundOperationFromComment(i);case"input":if(l==="request"){let u={type:"input",operationType:"request"};if(i.length>2)try{let h=i.slice(2),c=s.convertListStringToObj(h);"type"in c&&typeof c.type=="string"&&(u.valueType=c.type),"default"in c&&(u.defaultValue=c.default);}catch{}return u}default:if(o)switch(l){case"call":case"jump":t.labelToOpen={label:o,type:l},t.goNextStep=void 0;break;case"fade":case"move":case"rotate":case"zoom":case"shake":let u={};if(i.length>2)try{u=s.convertListStringToObj(i.slice(2));}catch{}if(l=="move"&&!("destination"in u)&&(!("x"in u)||!("y"in u))){console.error("[Pixi\u2019VN Ink] The move operation must have a x and y or destination property",e);return}else l=="move"&&"x"in u&&"y"in u&&(u.destination={x:u.x,y:u.y},delete u.x,delete u.y);return {alias:o,type:l,props:u}}else switch(l){case"pause":"dialogue"in t&&delete t.dialogue,"goNextStep"in t&&delete t.goNextStep;break}}}catch(i){throw console.error("[Pixi\u2019VN Ink] Error parsing ink hashtag-script",e),i}}static getImageOperationFromComment(e,t){let n=s.removeExtraDoubleQuotes(e[0]);if(!Uo.includes(n))return;let i=s.removeExtraDoubleQuotes(e[2]);if(n==="show"){let a={type:t,operationType:"show",alias:i,url:s.removeExtraDoubleQuotes(e[3])};if(e.length>4){let r=e.slice(4);if(e.includes("with")){let o=e.slice(e.indexOf("with")+1);r=e.slice(4,e.indexOf("with"));let l=s.getTransition(o);l!==void 0&&(a.transition=l);}if(r.length>0){let o=s.convertListStringToObj(r);a.props=o;}}return a}else {if(n==="edit")return {type:t,operationType:"edit",alias:i,props:s.convertListStringToObj(e.slice(3))};if(n==="remove"){let a={type:t,operationType:"remove",alias:i};if(e.length>4&&e[3]==="with"){let r=e.slice(4),o=s.getTransition(r);o!==void 0&&(a.transition=o);}return a}}}static getSoundOperationFromComment(e){let t=s.removeExtraDoubleQuotes(e[0]);if(!_h.includes(t))return;let n=s.removeExtraDoubleQuotes(e[2]);if(t==="add"){let i={type:"sound",operationType:"add",alias:n,url:s.removeExtraDoubleQuotes(e[3])};if(e.length>4){let a=s.getSoundOption(e.slice(4));a!==void 0&&(i.props=a);}return i}else if(t==="play"){let i={type:"sound",operationType:"play",alias:n};if(e.length>3){let a=s.getSoundPlayOptions(e.slice(3));a!==void 0&&(i.props=a);}return i}else {if(t==="pause"||t==="resume")return {type:"sound",operationType:t,alias:n};if(t==="remove")return {type:"sound",operationType:"remove",alias:n};if(t==="volume"){let i=parseFloat(e[3]);return {type:"sound",operationType:"volume",alias:n,value:i}}}}static getTransition(e){if(!["dissolve","fade","movein","moveout","zoomin","zoomout","pushin","pushout"].includes(e[0]))return;let n={type:e[0]};if(e.length>1)try{let i=s.convertListStringToObj(e.slice(1));n.props=i;}catch{}return n}static getSoundOption(e){try{return s.convertListStringToObj(e)}catch{return}}static getSoundPlayOptions(e){try{return s.convertListStringToObj(e)}catch{return}}static convertListStringToObj(e){let t=[],n=0,i="";for(let r=0;r0?(n--,i+=o,n===0&&(t.push(i),i="")):n>0?i+=o:t.push(o);}let a="{";t.forEach((r,o)=>{if(o%2===0)a+=`"${r}": `;else {switch(r){case"null":case"undefined":case"true":case"false":a+=`${r}`;break;default:s.containExtraDoubleQuotes(r)?(r=s.removeExtraDoubleQuotes(r),a+=`"${r}"`):r.startsWith("{")&&r.endsWith("}")?a+=`${r}`:r.startsWith('"')&&r.endsWith('"')?a+=`${r}`:isNaN(parseFloat(r))?a+=`"${r}"`:a+=`${r}`;}otypeof Ze<"u"?Ze:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof Ze<"u"?Ze:e)[t]}):s)(function(s){if(typeof Ze<"u")return Ze.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')}),rl=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Jh=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mh(e))!Gh.call(s,i)&&i!==t&&il(s,i,{get:()=>e[i],enumerable:!(n=jh(e,i))||n.enumerable});return s},$h=(s,e,t)=>(t=s!=null?qh(Bh(s)):{},Jh(il(t,"default",{value:s,enumerable:!0}),s)),Uh=rl((s,e)=>{(function(t,n){typeof s=="object"?e.exports=s=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(s,function(){var t=t||function(n,i){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof tl=="function")try{a=tl("crypto");}catch{}var r=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||function(){function d(){}return function(y){var v;return d.prototype=y,v=new d,d.prototype=null,v}}(),l={},u=l.lib={},h=u.Base=function(){return {extend:function(d){var y=o(this);return d&&y.mixIn(d),(!y.hasOwnProperty("init")||this.init===y.init)&&(y.init=function(){y.$super.init.apply(this,arguments);}),y.init.prototype=y,y.$super=this,y},create:function(){var d=this.extend();return d.init.apply(d,arguments),d},init:function(){},mixIn:function(d){for(var y in d)d.hasOwnProperty(y)&&(this[y]=d[y]);d.hasOwnProperty("toString")&&(this.toString=d.toString);},clone:function(){return this.init.prototype.extend(this)}}}(),c=u.WordArray=h.extend({init:function(d,y){d=this.words=d||[],y!=i?this.sigBytes=y:this.sigBytes=d.length*4;},toString:function(d){return (d||p).stringify(this)},concat:function(d){var y=this.words,v=d.words,g=this.sigBytes,_=d.sigBytes;if(this.clamp(),g%4)for(var I=0;I<_;I++){var fe=v[I>>>2]>>>24-I%4*8&255;y[g+I>>>2]|=fe<<24-(g+I)%4*8;}else for(var R=0;R<_;R+=4)y[g+R>>>2]=v[R>>>2];return this.sigBytes+=_,this},clamp:function(){var d=this.words,y=this.sigBytes;d[y>>>2]&=4294967295<<32-y%4*8,d.length=n.ceil(y/4);},clone:function(){var d=h.clone.call(this);return d.words=this.words.slice(0),d},random:function(d){for(var y=[],v=0;v>>2]>>>24-_%4*8&255;g.push((I>>>4).toString(16)),g.push((I&15).toString(16));}return g.join("")},parse:function(d){for(var y=d.length,v=[],g=0;g>>3]|=parseInt(d.substr(g,2),16)<<24-g%8*4;return new c.init(v,y/2)}},m=f.Latin1={stringify:function(d){for(var y=d.words,v=d.sigBytes,g=[],_=0;_>>2]>>>24-_%4*8&255;g.push(String.fromCharCode(I));}return g.join("")},parse:function(d){for(var y=d.length,v=[],g=0;g>>2]|=(d.charCodeAt(g)&255)<<24-g%4*8;return new c.init(v,y)}},S=f.Utf8={stringify:function(d){try{return decodeURIComponent(escape(m.stringify(d)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(d){return m.parse(unescape(encodeURIComponent(d)))}},b=u.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new c.init,this._nDataBytes=0;},_append:function(d){typeof d=="string"&&(d=S.parse(d)),this._data.concat(d),this._nDataBytes+=d.sigBytes;},_process:function(d){var y,v=this._data,g=v.words,_=v.sigBytes,I=this.blockSize,fe=I*4,R=_/fe;d?R=n.ceil(R):R=n.max((R|0)-this._minBufferSize,0);var B=R*I,pe=n.min(B*4,_);if(B){for(var pt=0;pt{(function(t,n){typeof s=="object"?e.exports=s=n(Uh()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(s,function(t){return function(){var n=t,i=n.lib,a=i.WordArray,r=i.Hasher,o=n.algo,l=[],u=o.SHA1=r.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(h,c){for(var f=this._hash.words,p=f[0],m=f[1],S=f[2],b=f[3],w=f[4],d=0;d<80;d++){if(d<16)l[d]=h[c+d]|0;else {var y=l[d-3]^l[d-8]^l[d-14]^l[d-16];l[d]=y<<1|y>>>31;}var v=(p<<5|p>>>27)+w+l[d];d<20?v+=(m&S|~m&b)+1518500249:d<40?v+=(m^S^b)+1859775393:d<60?v+=(m&S|m&b|S&b)-1894007588:v+=(m^S^b)-899497514,w=b,b=S,S=m<<30|m>>>2,m=p,p=v;}f[0]=f[0]+p|0,f[1]=f[1]+m|0,f[2]=f[2]+S|0,f[3]=f[3]+b|0,f[4]=f[4]+w|0;},_doFinalize:function(){var h=this._data,c=h.words,f=this._nDataBytes*8,p=h.sigBytes*8;return c[p>>>5]|=128<<24-p%32,c[(p+64>>>9<<4)+14]=Math.floor(f/4294967296),c[(p+64>>>9<<4)+15]=f,h.sigBytes=c.length*4,this._process(),this._hash},clone:function(){var h=r.clone.call(this);return h._hash=this._hash.clone(),h}});n.SHA1=r._createHelper(u),n.HmacSHA1=r._createHmacHelper(u);}(),t.SHA1});}),Kh=$h(Hh()),$t="___param___",tt=class P{static _beforeToTranslate=void 0;static _translate=e=>e;static _afterToTranslate=void 0;static t(e){return Array.isArray(e)?e.map(t=>P.translate(`${t}`)):P.translate(`${e}`)}static set beforeToTranslate(e){P._beforeToTranslate=e;}static set translate(e){P._translate=e;}static get translate(){return e=>{let t=e;return P._beforeToTranslate&&(t=P._beforeToTranslate(t)),t=P._translate(t),P._afterToTranslate&&(t=P._afterToTranslate(t)),t}}static set afterToTranslate(e){P._afterToTranslate=e;}static addKey(e,t,n){let i=n.defaultValue||"empty_string";typeof t=="string"&&(t=[t]),Array.isArray(t)&&t.forEach(a=>{e[a]===void 0&&(i==="empty_string"?e[a]="":i==="copy_key"&&(P._beforeToTranslate?e[a]=P._beforeToTranslate(a):e[a]=a));});}static getConditionalsThenElse(e,t=[]){if(typeof e=="object"&&e&&"type"in e)if(e.type==="ifelse")e.then&&P.getConditionalsThenElse(e.then,t),e.else&&P.getConditionalsThenElse(e.else,t);else if(e.type==="stepswitch"){if(e.elements)if(Array.isArray(e.elements))e.elements.forEach(n=>{P.getConditionalsThenElse(n,t);});else if(e.elements.type==="ifelse"){let n=[];P.getConditionalsThenElse(e.elements,n),n.forEach(i=>{t.push(...i);});}else if(e.elements.type==="stepswitch"){let n=[];P.getConditionalsThenElse(e.elements,n),n.forEach(i=>{t.push(...i);});}else P.getConditionalsThenElse(e.elements,t);}else e.type==="resulttocombine"?(e.firstItem&&P.getConditionalsThenElse(e.firstItem,t),e.secondConditionalItem&&e.secondConditionalItem.forEach(n=>{P.getConditionalsThenElse(n,t);})):t.push(e);else e&&t.push(e);return t}static generateJsonTranslation(e,t={},n={}){return e.forEach(i=>{if(i.choices){let a=[];Array.isArray(i.choices)?a=[i.choices]:a=P.getConditionalsThenElse(i.choices),a.forEach(r=>r.forEach(o=>{if("type"in o){let l=[];o.type==="ifelse"||o.type==="stepswitch"?P.getConditionalsThenElse(o,l):l=[o],l.map(u=>P.getConditionalsThenElse(u.text)).forEach(u=>{Array.isArray(u)&&u.forEach(h=>{Array.isArray(h)?h.forEach(c=>{typeof c=="string"?P.addKey(t,c,n):P.getConditionalsThenElse(c).forEach(f=>{Array.isArray(f)?f.forEach(p=>{typeof p=="string"&&P.addKey(t,p,n);}):typeof f=="string"&&P.addKey(t,f,n);});}):typeof h=="string"&&P.addKey(t,h,n);});});}}));}if(i.dialogue){let a=[];Array.isArray(i.dialogue)?a=[i.dialogue]:a=P.getConditionalsThenElse(i.dialogue),a.forEach(r=>{typeof r=="string"?P.addKey(t,r,n):"text"in r&&Array.isArray(r.text)&&r.text.forEach(o=>{typeof o=="string"?P.addKey(t,o,n):P.getConditionalsThenElse(o).forEach(l=>{typeof l=="string"?P.addKey(t,l,n):Array.isArray(l)&&l.forEach(u=>{typeof u=="string"?P.addKey(t,u,n):P.getConditionalsThenElse(u).forEach(h=>{typeof h=="string"&&P.addKey(t,h,n);});});});});});}i.conditionalStep&&P.getConditionalsThenElse(i.conditionalStep).forEach(a=>{Array.isArray(a)?P.generateJsonTranslation(a,t,n):P.generateJsonTranslation([a],t,n);});}),t}},De=tt;function zh(s,e){return Math.floor(Math.random()*(e-s+1)+s)}function Xh(s){if(Array.isArray(s)||!s)return s;if(s&&typeof s=="object"&&"type"in s)switch(s.type){case"resulttocombine":return Yh(s);case"ifelse":return x(s.condition)?x(s.then):x(s.else);case"stepswitch":let e=x(s.elements)||[];if(e.length===0){console.error("[Pixi\u2019VN Json] getValueFromConditionalStatements elements.length === 0");return}switch(s.choiceType){case"random":let t=zh(0,e.length-1);return x(e[t]);case"loop":let n=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounter(s.nestedId)-1;return n>e.length-1&&(n=n%e.length),x(e[n]);case"sequential":let i,a=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounter(s.nestedId)-1;return s.end=="lastItem"&&(i=x(e[e.length-1])),a>e.length-1?i:x(e[a]);case"sequentialrandom":let r=pixiVn.NarrationManagerStatic.getRandomNumber(0,e.length-1,{nestedId:s.nestedId,onceOnly:!0});if(r==null&&s.end=="lastItem"){let o=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounterData(s.nestedId);if(!o||!o?.usedRandomNumbers){console.warn("[Pixi\u2019VN Json] getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let l=o.usedRandomNumbers[`0-${e.length-1}`];return x(e[l[l.length-1]])}if(r==null){console.warn("[Pixi\u2019VN Json] getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return x(e[r])}}return s}function as(s){if(s.conditionalStep){let e=pixiVn.createExportableElement(x(s.conditionalStep));if(e?.glueEnabled===void 0&&delete e?.glueEnabled,e?.goNextStep===void 0&&delete e?.goNextStep,e?.end===void 0&&delete e?.end,e?.choices===void 0&&delete e?.choices,e?.dialogue===void 0&&delete e?.dialogue,e?.labelToOpen===void 0&&delete e?.labelToOpen,e?.operations===void 0&&delete e?.operations,e){let t={...s,conditionalStep:void 0,...e};return as(t)}else pixiVn.getFlag(pixiVn.storage.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY)&&pixiVn.setFlag(pixiVn.storage.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,!1);}return s}function Yh(s){let e=s.firstItem,t=[];s.secondConditionalItem?.forEach(i=>{if(Array.isArray(i))i.forEach(a=>{let r=x(a);t.push(r);});else {let a=x(i);t.push(a);}});let n=e?[e,...t]:t;if(n.length===0){console.warn("[Pixi\u2019VN Json] combinateResult toCheck.length === 0");return}if(typeof n[0]=="string")return De.t(n).join("");if(typeof n[0]=="object"){let i=n,a,r=i.map((b,w)=>{b=as(b);let d=x(b.dialogue)||"";return w===0?(a=x(b.glueEnabled)||!1,d):(typeof d=="object"&&"text"in d&&(d=d.character+": "+d.text),a===!1&&(d=` `+d),a=x(b.glueEnabled)||!1,d)}),o=x(r[0]),l=typeof o=="object"&&"character"in o?o.character:void 0,u=r.map(b=>{let w;b&&typeof b=="object"&&"text"in b?w=b.text:w=b;let d;return Array.isArray(w)?d=w.map(y=>{let v=x(y);return De.t(`${v}`)}).join(""):d=x(w)||"",De.t(d)}).join(""),h=i.find(b=>b.end),c=i.find(b=>b.choices),f=!1,p=!1;i.length>0&&(i[0].glueEnabled&&i[0].goNextStep&&i[0].dialogue===void 0&&pixiVn.setFlag(pixiVn.storage.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,!0),f=i[i.length-1].glueEnabled,p=i.reverse().find(b=>!(b.operations&&(!b.dialogue||!b.choices)))?.goNextStep);let m=i.find(b=>b.labelToOpen),S=[];return i.forEach(b=>{b.operations&&S.forEach(w=>{S.push(w);});}),{dialogue:l?{character:l,text:u}:u,end:h?.end,choices:c?.choices,glueEnabled:f,goNextStep:p,labelToOpen:m?.labelToOpen,operations:S}}}function Qh(s){if(!s)return !1;if(typeof s!="object"||!("type"in s))return !!s;switch(s.type){case"compare":let e=x(s.leftValue),t=x(s.rightValue);switch(s.operator){case"==":return e===t;case"!=":return e!==t;case"<":return e":return e>t;case">=":return e>=t;case"CONTAINS":return e.toString().includes(t.toString())}break;case"valueCondition":return !!x(s.value);case"union":return ec(s)}return !!s}function Zh(s){if(s&&typeof s=="object"&&"type"in s&&s.type==="value"&&s.storageOperationType==="get")switch(s.storageType){case"storage":case"tempstorage":return pixiVn.storage.getVariable(s.key);case"flagStorage":return pixiVn.getFlag(s.key);case"label":return pixiVn.narration.getTimesLabelOpened(s.label);case"choice":return pixiVn.narration.getTimesChoiceMade(s.index);case"logic":return x(s.operation);case"params":let e=pixiVn.storage.getVariable(`${$t}${pixiVn.narration.openedLabels.length-1}`)||[];if(e&&e.length>s.key)return e[s.key];console.warn("[Pixi\u2019VN Json] getValue params not found");return}return s}function ec(s){if(s.unionType==="not")return !x(s.condition);let e=s.unionType==="and";for(let t=0;t=s.key&&(n[s.key]=t),pixiVn.storage.setTempVariable(`${$t}${pixiVn.narration.openedLabels.length-1}`,n);break}}function x(s){let e=Xh(s);if(e&&typeof e=="object"&&"type"in e)switch(e.type){case"value":return Zh(e);case"arithmetic":case"arithmeticsingle":return nc(e);case"compare":case"valueCondition":case"union":return Qh(e)}return e}function nc(s){let e=x(s.leftValue);switch(s.type){case"arithmetic":let t=x(s.rightValue);switch(s.operator){case"*":return e*t;case"/":return e/t;case"+":return e+t;case"-":return e-t;case"%":return e%t;case"POW":return Math.pow(e,t);case"RANDOM":return pixiVn.narration.getRandomNumber(e,t)}case"arithmeticsingle":switch(s.operator){case"INT":return parseInt(e);case"FLOOR":return Math.floor(e);case"FLOAT":return parseFloat(e)}break}}async function os(s,e){let t=x(s);if(t)switch(t.type){case"sound":switch(t.operationType){case"add":pixiVn.sound.add(t.alias,{...t.props,url:t.url});break;case"play":pixiVn.sound.play(t.alias,t.props);break;case"remove":pixiVn.sound.remove(t.alias);break;case"pause":pixiVn.sound.pause(t.alias);break;case"resume":pixiVn.sound.resume(t.alias);break;case"volume":pixiVn.sound.volume(t.alias,t.value);break}break;case"assets":switch(t.operationType){case"load":await pixiVn.Assets.load(t.assets);break}break;case"image":switch(t.operationType){case"show":let o=new pixiVn.CanvasImage(t.props,t.url);if(t.transition)switch(t.transition.type){case"fade":await pixiVn.showWithFadeTransition(t.alias,o,t.transition.props,t.transition.priority);break;case"dissolve":await pixiVn.showWithDissolveTransition(t.alias,o,t.transition.props,t.transition.priority);break;case"movein":case"moveout":await pixiVn.moveIn(t.alias,o,t.transition.props,t.transition.priority);break;case"zoomin":case"zoomout":await pixiVn.zoomIn(t.alias,o,t.transition.props,t.transition.priority);break;case"pushin":case"pushout":await pixiVn.pushIn(t.alias,o,t.transition.props,t.transition.priority);break}else pixiVn.canvas.add(t.alias,o),await o.load();break;case"edit":let l=pixiVn.canvas.find(t.alias);l?t.props&&(l.memory={...l.memory,...t.props}):console.error(`[Pixi\u2019VN Json] Image with alias ${t.alias} not found.`);break;case"remove":if(t.transition)switch(t.transition.type){case"fade":pixiVn.removeWithFadeTransition(t.alias,t.transition.props,t.transition.priority);break;case"dissolve":pixiVn.removeWithDissolveTransition(t.alias,t.transition.props,t.transition.priority);break;case"movein":case"moveout":pixiVn.moveOut(t.alias,t.transition.props,t.transition.priority);break;case"zoomin":case"zoomout":pixiVn.zoomOut(t.alias,t.transition.props,t.transition.priority);break;case"pushin":case"pushout":pixiVn.pushOut(t.alias,t.transition.props,t.transition.priority);break}else pixiVn.canvas.remove(t.alias);break}break;case"video":switch(t.operationType){case"show":let o=new pixiVn.CanvasVideo(t.props,t.url);if(t.transition)switch(t.transition.type){case"fade":await pixiVn.showWithFadeTransition(t.alias,o,t.transition.props,t.transition.priority);break;case"dissolve":await pixiVn.showWithDissolveTransition(t.alias,o,t.transition.props,t.transition.priority);break;case"movein":case"moveout":await pixiVn.moveIn(t.alias,o,t.transition.props,t.transition.priority);break;case"zoomin":case"zoomout":await pixiVn.zoomIn(t.alias,o,t.transition.props,t.transition.priority);break}else pixiVn.canvas.add(t.alias,o),await o.load();break;case"edit":let l=pixiVn.canvas.find(t.alias);l?t.props&&(l.memory={...l.memory,...t.props}):console.error(`[Pixi\u2019VN Json] Video with alias ${t.alias} not found.`);break;case"remove":if(t.transition)switch(t.transition.type){case"fade":pixiVn.removeWithFadeTransition(t.alias,t.transition.props,t.transition.priority);break;case"dissolve":pixiVn.removeWithDissolveTransition(t.alias,t.transition.props,t.transition.priority);break;case"movein":case"moveout":pixiVn.moveOut(t.alias,t.transition.props,t.transition.priority);break;case"zoomin":case"zoomout":pixiVn.zoomOut(t.alias,t.transition.props,t.transition.priority);break}else pixiVn.canvas.remove(t.alias);break;case"pause":let u=pixiVn.canvas.find(t.alias);u?u.paused=!0:console.error(`[Pixi\u2019VN Json] Video with alias ${t.alias} not found.`);break;case"resume":let h=pixiVn.canvas.find(t.alias);h?h.paused=!1:console.error(`[Pixi\u2019VN Json] Video with alias ${t.alias} not found.`);break}break;case"value":tc(t);break;case"operationtoconvert":if(e){let o="";t.values.forEach(u=>{if(typeof u=="string")o+=u;else {let h=x(u);o+=`${h}`;}});let l=await e(o);l&&await os(l,e);}break;case"input":switch(t.operationType){case"request":pixiVn.narration.requestInput({type:t.valueType}),pixiVn.narration.inputValue=t.defaultValue;break}break;case"fade":let n=new pixiVn.FadeAlphaTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,n);break;case"move":let i=new pixiVn.MoveTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,i);break;case"rotate":let a=new pixiVn.RotateTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,a);break;case"zoom":let r=new pixiVn.ZoomTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,r);break;case"shake":await pixiVn.shakeEffect(t.alias,t.props,t.priority);break}}var ic=class extends pixiVn.LabelAbstract{constructor(s,e,t,n={}){super(s,t),this._steps=e,this.operationStringConvert=n.operationStringConvert,this.skipEmptyDialogs=n.skipEmptyDialogs||!1;}_steps;get steps(){return this._steps.map(s=>this.stepConverter(s))}operationStringConvert;skipEmptyDialogs=!1;getStepSha1(s){if(s<0||s>=this.steps.length)return;let e=this._steps[s];return (0, Kh.default)(e.toString().toLocaleLowerCase()).toString()}getDialogueText(s){let e="";if(Array.isArray(s)){let t=[];s.forEach(n=>{if(typeof n=="string")t.push(n);else if(n&&typeof n=="object"){let i=x(n);i?(i&&!Array.isArray(i)&&typeof i=="object"&&(i=x(i)||""),Array.isArray(i)?t=t.concat(i):t.push(`${i}`)):t.push(`${n}`);}}),e=t;}else {let t=x(s)||"";t&&!Array.isArray(t)&&typeof t=="object"&&(t=x(t)||""),e=t;}return `${e}`}getDialogue(s){if(s==null)return;let e=x(s);return e==null?"":typeof e=="object"&&"character"in e&&"text"in e?{character:e.character,text:tt.t(this.getDialogueText(e.text))}:tt.t(this.getDialogueText(e))}getChoices(s){return x(s)?.map(e=>x(e)).filter(e=>e!==void 0)}stepConverter(s){return async e=>{let t;if(typeof s=="function"?t=s():t=s,t=as(t),t.operations)for(let u of t.operations)await os(u,this.operationStringConvert?h=>this.operationStringConvert(h,t,e):void 0);let n=this.getChoices(t.choices),i=x(t.glueEnabled),a=this.getDialogue(t.dialogue),r=[];t.labelToOpen&&(Array.isArray(t.labelToOpen)||(t.labelToOpen=[t.labelToOpen]),t.labelToOpen.forEach(u=>{let h=x(u);h&&r.push(h);}));let o=x(t.goNextStep),l=x(t.end);if(n){let u=n.map(h=>{let c="";if(Array.isArray(h.text)){let f=[];h.text.forEach(p=>{if(typeof p=="string")f.push(tt.t(p));else if(p&&typeof p=="object"){let m=x(p);m&&!Array.isArray(m)&&typeof m=="object"&&(m=x(m)||""),m&&(Array.isArray(m)?f=f.concat(tt.t(m)):f.push(tt.t(m)));}}),c=f.join();}else typeof h.text=="string"&&(c=tt.t(h.text));return new pixiVn.ChoiceMenuOption(c,h.label,h.props,{type:h.type,oneTime:h.oneTime,onlyHaveNoChoice:h.onlyHaveNoChoice,autoSelect:h.autoSelect})});pixiVn.narration.choiceMenuOptions=u;}else pixiVn.narration.choiceMenuOptions=void 0;a!==void 0&&(pixiVn.narration.dialogue=a,this.skipEmptyDialogs&&typeof a=="string"&&(a===""||RegExp(/^\s+$/).test(a))&&(o=!0)),i?pixiVn.setFlag(pixiVn.storage.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,!0):i===!1&&pixiVn.setFlag(pixiVn.storage.keysSystem.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,!1);for(let u of r){let h=u.label;typeof h=="object"&&(h=x(h)||"");let c=u.params?.map(f=>x(f));e={...e,...u.props},u.type==="jump"?(pixiVn.narration.closeCurrentLabel(),pixiVn.storage.setTempVariable(`${$t}${pixiVn.narration.openedLabels.length}`,c),await pixiVn.narration.callLabel(h,e)):(pixiVn.storage.setTempVariable(`${$t}${pixiVn.narration.openedLabels.length}`,c),await pixiVn.narration.callLabel(h,e));}l==="game_end"?(pixiVn.narration.closeAllLabels(),await pixiVn.narration.goNext(e)):l==="label_end"&&pixiVn.narration.closeCurrentLabel(),o&&await pixiVn.narration.goNext(e);}}};function sl(s,e={}){let t=e?.operationStringConvert;try{typeof s=="string"&&(s=JSON.parse(s));}catch(n){console.error("[Pixi\u2019VN Json] Error parsing imported Pixi'VN JSON",n);return}if(typeof s!="object"){console.error("[Pixi\u2019VN Json] Error parsing imported Pixi'VN JSON: data is not an object");return}if(s.initialOperations){for(let n of s.initialOperations)os(n,t?i=>t(i,{},{}):void 0);pixiVn.StorageManagerStatic.saveStorageAsBasicStorage();}if(s.labels){let n=s.labels;for(let i in n)try{let a=n[i],r=new ic(i,a,void 0,e);pixiVn.saveLabel(r);}catch(a){console.error(`[Pixi\u2019VN Json] Error creating JSON label ${i}`,a);}}}var dh=bh(Qu());var L="_|_",is="global decl",Ye="___external_value___";function In(s,e){if(new RegExp(/.*\.[0-9]+\..*$/).test(s)&&(s=s.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!s.startsWith(".")))return s.replaceAll(".",L);if(!new RegExp(/^\.\^.*$/).test(s)&&s.includes("g-")){let n=s.split("g-");return No(e)+L+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(s);)t++,s=s.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(s)&&e){let n=s.substring(1);return No(e,t)+L+n.replaceAll(".",L)}return s.replaceAll(".",L)||No(e,t).replaceAll(".",L)}function No(s,e=0){let t=s.split(L);for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join(L)}var Zu="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Re(s){return s.startsWith("^")&&(s=s.substring(1)),s=s.replaceAll("\\\\",Zu),s=s.replaceAll("\\n",` `),s=s.replaceAll("\\t"," "),s=s.replaceAll(" "," "),s=s.replaceAll(Zu,"\\\\"),s}var eh=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],th=["+","-","/","*","%","POW","RANDOM"],nh=["INT","FLOOR","FLOAT"],ih=["==",">","<",">=","<=","!=","CONTAINS"];function jt(s,e,t){s=s.map(i=>{if(typeof i=="string"){if(i==="rnd")return "RANDOM";if(i==="?")return "CONTAINS"}return i});let n=[];return s.forEach(i=>{if(typeof i=="object"&&"CNT?"in i)if(new RegExp(/.*\.[0-9]\..*/).test(i["CNT?"])){let a=i["CNT?"].split("."),r=a.pop(),o=a.pop();if(o===void 0||r===void 0){console.error("[Pixi\u2019VN Ink] Error parsing ink file: Conditional statement is not valid",s);return}let l=parseInt(o),u=a.join(".");if(u.includes("^.")){let h=u.split("."),c=h[h.length-1].replaceAll(".",L);h.pop(),u=h.join(".")+"."+c,r.includes("c-")&&(u=u+L+r);}else u=u.replaceAll(".",L);n.push({type:"compare",leftValue:rh(In(u,e)),operator:">=",rightValue:{type:"value",value:l}});}else n.push(rh(In(i["CNT?"],e)));else if(typeof i=="object"&&"VAR?"in i)n.push(Mt(i["VAR?"],t));else if(i==="&&"||i==="||"){if(n.length>=2){let a={type:"union",unionType:i==="&&"?"and":"or",conditions:[n[n.length-2],n[n.length-1]]};n.pop(),n.pop(),n.push(a);}}else if(i==="!")if(n.length===0)console.error("[Pixi\u2019VN Ink] Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"union",unionType:"not",condition:n[n.length-1]};n[n.length-1]=a;}else if(i&&typeof i=="string"&&ih.includes(i))if(n.length<2)console.error("[Pixi\u2019VN Ink] Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"compare",operator:i,rightValue:n[n.length-1],leftValue:n[n.length-2]};n.pop(),n.pop(),n.push(a);}else if(i&&typeof i=="string"&&th.includes(i))if(n.length<2)console.error("[Pixi\u2019VN Ink] Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"arithmetic",operator:i,rightValue:n[n.length-1],leftValue:n[n.length-2]};n.pop(),n.pop(),n.push(a);}else if(i&&typeof i=="string"&&nh.includes(i)){let a={type:"arithmeticsingle",operator:i,leftValue:n[n.length-1]};n.pop(),n.push(a);}else i&&typeof i=="string"?i.startsWith("^")&&n.push(Re(i)):typeof i=="object"&&"^->"in i?i["^->"].includes("$r")||n.push(i["^->"]):n.push(i);}),n}function rh(s){return {type:"value",storageType:"label",storageOperationType:"get",label:s}}function sh(s,e,t){return jt(s,e,t)}function Mt(s,e,t="storage"){let n=e.indexOf(s);return n>=0?{type:"value",storageType:"params",storageOperationType:"get",key:n}:{type:"value",storageOperationType:"get",storageType:t,key:s}}function Ao(s,e,t,n="storage"){let i=e.indexOf(s);return i>=0?{type:"value",storageType:"params",storageOperationType:"set",key:i,value:t}:{type:"value",storageOperationType:"set",storageType:n,key:s,value:t}}function rs(s,e){e&&(typeof e=="string"?e.startsWith("^")&&s.push(Re(e)):typeof e=="object"&&"type"in e&&e.type!=="value"&&s.push(e));}function Io(s,e,t,n,i=!0,a=!1){return zg(s,e,t,n,i,a)}function zg(s,e,t,n,i,a=!1){if(e){if(a)Array.isArray(e)&&e.length>0&&s.push({operations:[{type:"operationtoconvert",values:e}],goNextStep:!0});else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type=="value"&&e.storageOperationType==="get"){if(!i&&s.length>0){let r=s[s.length-1];!r.glueEnabled&&!r.operations&&(r.glueEnabled=!0,r.labelToOpen||(r.goNextStep=!0)),s[s.length-1]=r;}typeof e=="string"?s.push(Xg(Re(e))):s.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")s.push({end:"game_end"});else if(e==="done")s.push({end:"label_end",goNextStep:!0});else if(e=="<>")if(s.length>0){let r=s[s.length-1];r.glueEnabled=!0,r.labelToOpen||(r.goNextStep=!0),s[s.length-1]=r;}else s.push({glueEnabled:!0,goNextStep:!0});}else if(typeof e=="object"){if("type"in e&&e.type!=="value"){if(!i&&s.length>0){let r=s[s.length-1];!r.glueEnabled&&!r.operations&&(r.glueEnabled=!0,r.labelToOpen||(r.goNextStep=!0)),s[s.length-1]=r;}s.push({conditionalStep:e});}else if("->"in e){let r=i?void 0:!0;if(!i&&s.length>0){let o=s[s.length-1];o.labelToOpen||(o.goNextStep=!0),s[s.length-1]=o;}if(e.params&&e.params.length===0&&(e.params=void 0),e.var)s.push({labelToOpen:{label:Mt(e["->"],n),type:"jump",params:e.params},glueEnabled:r});else {let o=In(e["->"],t);s.push({labelToOpen:{label:o,type:"jump",params:e.params},glueEnabled:r});}}"type"in e&&e.type=="value"&&e.storageOperationType==="set"&&(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=Re(e.value)),s.push({goNextStep:!0,operations:[e]}));}}}function Xg(s){let e;if(s.includes(": ")){let t=s.split(": "),n=t[0],i=t[1];pixiVn.getCharacterById(n)&&(e=n,s=i);}return e?{dialogue:{character:e,text:s}}:{dialogue:s}}function Fo(s,e,t,n=!0,i=!1){return Yg(s,e,t,n,i)}function Yg(s,e,t,n,i=!1){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type=="value"&&e.storageOperationType==="get"?typeof e=="string"?s.push(Re(e)):s.push(e):typeof e=="object"&&"type"in e&&s.push(e));}function ss(s,e,t){if(s.length===0){console.error("[Pixi\u2019VN Ink] Error parsing ink file: Arithmetic statement is not valid",s);return}let n=jt(s,e,t);if(n.length===1){let i=n[0];return i&&typeof i=="object"&&"type"in i?{type:"value",storageType:"logic",storageOperationType:"get",operation:i}:i}}function Bt(s,e,t,n="",i,a,r=void 0){let o=[],l="sequential",u=!1,h=!0;s.forEach(p=>{p==="%"&&(l="loop"),p==="seq"&&(l="random"),p==="MIN"&&(u=!0);});let c=s[s.length-1];return Object.keys(c).forEach(p=>{let m=c[p];if(Array.isArray(m)&&m.length>3){m=m.slice(1,m.length-2);let S=[];Qe(m,n,i,S,e,e,t,Gt,r,!0,a),S.length===1?o.push(S[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:S});}else Array.isArray(m)&&m.length===3&&(h=!1);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:h?"lastItem":void 0,nestedId:r}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:h?"lastItem":void 0,nestedId:r}:{type:"stepswitch",elements:o,choiceType:l}}function Vo(s="",e=""){let t=Array.isArray(s)?s:[s],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function Gt(s,e,t,n,i){if(s.length>0){let a={};ah(s,a,i);for(let[r,o]of Object.entries(a)){let l=t+L+r,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:"jump",oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=!0,u.autoSelect=!0),u.oneTime===!1&&delete u.oneTime;let h=ko(u,o.conditions,i,t)||u,c=e[e.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),e.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let f=c.choices;f&&Array.isArray(f)?f.push(h):console.error("[Pixi\u2019VN Ink] Unhandled case: choices is PixiVNJsonConditionalStatements | undefined",o,f),c.choices=f.sort((p,m)=>{try{let S=p.label.split("."),b=S[S.length-1].replaceAll(".",L),w=m.label.split("."),d=w[w.length-1].replaceAll(".",L);if(b.includes("c-")&&d.includes("c-")){let y=b.split("c-")[1],v=parseInt(y),g=d.split("c-")[1],_=parseInt(g);return v-_}}catch{}return 0});}else e.push({choices:[h]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function ah(s,e,t,n){let i=[],a="",r="",o=!1,l=[];for(let u=0;u{},n,{preDialog:{}},t);i.push(c);}else if(h&&typeof h=="object")if("*"in h&&typeof h["*"]&&typeof h["*"]=="string")h["*"].includes("c")&&(a="c"+h["*"].split("c")[1],h.flg&16&&(o=!0));else if("s"in h&&h.s instanceof Array){let c=oh(h.s),f=h.s.includes("<>");c&&(n&&e[n]?(e[n].preDialog={text:c,glue:f},e[n].text=Vo(c,e[n].text)):(i.push(c),r=c));}else "CNT?"in h&&l.push(h);else l.push(h);if(a){e[a]?e[a].text=Vo(i,e[a].text):e[a]={text:i,onetime:o,conditions:l},r&&(e[a].preDialog={text:r,glue:!1});let c=s.slice(u+1);ah(c,e,t,a);return}}}function oh(s){for(let e of s)if(typeof e=="string"){if(e.startsWith("^"))return Re(e)}else if(e instanceof Array){let t=oh(e);if(t)return t}}function ko(s,e,t,n,i){if(e.length===0)return;let a=jt(e,n,t);if(a.length===1){let r={type:"ifelse",condition:a[0],then:s,else:i};return r.else||delete r.else,r}else if(a.length>1){let r={type:"ifelse",condition:{type:"union",unionType:"and",conditions:a},then:s,else:i};return r.else||delete r.else,r}}function lh(s,e,t,n,i,a,r=void 0){if(s.length===0){console.error("[Pixi\u2019VN Ink] Error parsing ink file: Conditional statement is not valid",s);return}let o=[],l=[];if(s.forEach(c=>{Array.isArray(c)?l.push(c):typeof c=="string"&&c==="du"?i.du?o.push(i.du):i.du=o[o.length-1]:(typeof c!="string"||c!=="/ev")&&o.push(c);}),l.length===0){console.error("[Pixi\u2019VN Ink] Error parsing ink file: Conditional statement is not valid",l);return}let u=Ro(l[0],e,t,n+L+"then",i,a,`${r||""}then`),h;return l.length===2?h=Ro(l[1],e,t,n+L+"else",i,a,`${r||""}else`):l.length>2&&(l.shift(),l.push("nop"),l=[{b:l}],h=Ro(l,e,t,n+L+"else",i,a,`${r||""}else`)),i.du=void 0,ko(u,o,a,n,h)}function Ro(s,e,t,n,i,a,r=void 0){let o=[];for(let u of s)typeof u=="object"&&"b"in u&&(u.b=u.b.filter(h=>h!==null&&!(typeof h=="object"&&"->"in h&&new RegExp(/.*\.[0-9]/).test(h["->"]))),Qe(u.b,n,i,o,e,e,t,Gt,r,!0,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function Qe(s,e,t,n=[],i,a,r,o,l=void 0,u=!0,h=[]){let c=!1,f=[],p=!1,m=!1,S=[],b=[];if(t.preDialog[e]&&(u=!1,i(n,"^"+t.preDialog[e].text,e,h,u,m),t.preDialog[e].glue&&i(n,"<>",e,h,u,m),delete t.preDialog[e]),s.includes("visit")){let d=Bt(s,a,r,e,t,h,l);d&&(!u&&n.length>0&&i(n,"<>",e,h,u,m),i(n,d,e,h,u,m));return}let w=s[0];if(w&&typeof w=="object"&&"temp="in w){for(;s[0]&&typeof s[0]=="object"&&"temp="in s[0];)h.push(s[0]["temp="]),s.shift();h=h.reverse();}if(s.forEach((d,y)=>{if(m){if(typeof d=="string"&&d=="/#"){let v=[];Qe(b,e,t,v,Fo,Fo,r,o,l,u),i(n,v,e,h,u,m),m=!1,b=[];}else b.push(d);return}else if(c)if(Array.isArray(d))f.push(d);else if(d&&typeof d=="object")if("CNT?"in d)y>0&&s[y-1]=="ev"?(p=!0,S.push(d)):p?S.push(d):(f.push(d),u=!1);else if("VAR="in d||"temp="in d){let v=Ao("VAR="in d?d["VAR="]:d["temp="],h,s[y-1],"VAR="in d?"storage":"tempstorage");if(v.value&&typeof v.value=="string"&&v.value=="/str"&&(v.value=s[y-2]),v.value&&typeof v.value=="object"&&"^->"in v.value&&(v.value=v.value["^->"]),f.length>1){let g=ss(f,e,h);f=[],g&&typeof g=="object"&&"type"in g&&g.type=="value"&&"storageType"in g&&g.storageType=="logic"&&(v.value=g.operation);}(typeof v.key!="string"||!v.key.includes("$r"))&&(i(n,v,e,h,u,m),u=!0);}else "VAR?"in d?f.push(d):"^->"in d&&(d["^->"].includes("$r")||f.push(d));else if(typeof d=="string"&&d=="/ev")p&&S.push(d),c=!1,f.push(d);else if(typeof d=="string"&&d=="out"){if(f.length>0){let v=f[f.length-1];if(v&&typeof v=="object"&&"VAR?"in v){f.pop();let g=Mt(v["VAR?"],h,"storage");i(n,g,e,h,u,m);}else {let g=[];for(;f.length>0&&f[f.length-1]!="/ev";)g.push(f.pop());g=g.reverse();let _=ss(g,e,h);f=[],_&&typeof _=="object"&&"type"in _&&_.type=="value"&&"storageType"in _&&_.storageType=="logic"?i(n,{storageOperationType:"get",storageType:"logic",operation:_.operation,type:"value"},e,h,u,m):(i(n,"<>",e,h,u,m),_=`^${_}`,i(n,_,e,h,u,m));}u=!1;}}else f.push(d);else if(typeof d=="string")if(d.startsWith("^"))i(n,d,e,h,u,m),u=!1;else if(d=="ev")c=!0;else if(d==` `)u=!0;else if(d=="done"||d=="end")i(n,d,e,h,u,m),u=!1;else if(d=="<>")i(n,d,e,h,u,m),u=!1;else if(d=="nop"&&p){let v=lh(S,a,r,e,t,h,l);v&&i(n,v,e,h,u,m),p=!1,S=[];}else d=="#"&&(m=!0);else if(d instanceof Array)if(p)S.push(d);else if(d.length>1&&typeof d[d.length-2]=="object"&&d[d.length-2]&&"c"in d[d.length-2]&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"b"in d[d.length-1]){f.pop();let v=[],g=[];for(;f.length>0&&f[f.length-1]!="/ev";)v.push(f.pop());S=[...S,...v.reverse()],p=!0,g.push(d.pop()),g.push(d.pop()),S=[...S,...d],S.push(g);}else if(d.length>1&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"#n"in d[d.length-1]){let v=d.pop();if(!v){console.error("[Pixi\u2019VN Ink] Error parsing ink file: el is undefined");return}let g=v["#n"];delete v["#n"],d.push(v),i(n,{"->":e?e+L+g:g},e,h,u,m),r({[g]:d},e,t);}else Qe(d,e,t,n,i,a,r,o,l,u);else if(d&&typeof d=="object")if("->"in d&&typeof d["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->"])){let v=[];f.length>0&&(v=sh(["ev",...f],e,h)),d.params=v,i(n,d,e,h,u,m),u=!1;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(f.push(d),u=!1);else if("s"in d&&d.s instanceof Array)f.push(d),u=!1;else if("CNT?"in d)f.push(d),u=!1;else if("VAR="in d||"temp="in d){let v=[],g=Ao("VAR="in d?d["VAR="]:d["temp="],h,void 0,"VAR="in d?"storage":"tempstorage");if(g.key!=="$r"){for(f.pop(),f[f.length-1]=="/ev"&&f.pop();f.length>0&&f[f.length-1]!="/ev";)v.push(f.pop());v=v.reverse(),g.value=ss(v,e,h),f=[],(g.value!==void 0||g.value!==null)&&i(n,g,e,h,u,m),u=!1;}}else r(d,e,t);}),o(f,n,e,t,h),e.includes(L)&&n.length==2){let d=n[0],y=n[1];d&&y&&typeof d=="object"&&"dialogue"in d&&typeof y=="object"&&"labelToOpen"in y&&d.dialogue==" "&&y.labelToOpen&&(n.shift(),delete y.glueEnabled,n[0]=y);}}function uh(s){try{let e={};return hh(s,e),e}catch(e){console.error("[Pixi\u2019VN Ink] Error parsing ink file",e);}}function hh(s,e,t={externalSwitch:void 0}){for(let n of s)if(n)if(n instanceof Array)if(n.includes("visit")){let i=Bt(n,rs,(a,r,o)=>{},"",{preDialog:{}},[]);i&&(t.externalSwitch=i);}else hh(n,e,t);else typeof n=="object"&&(n&&"VAR="in n&&t.externalSwitch&&(e[Ye]||(e[Ye]=[]),e[Ye].push({operations:[{type:"value",value:t.externalSwitch,key:n["VAR="],storageType:"storage",storageOperationType:"set"}]})),ch(n,e));}function ch(s,e,t="",n={preDialog:{}}){if(s!==null){for(let[i,a]of Object.entries(s))if(a instanceof Array){let r=[],o={},l=(t?t+L:"")+i;Qe(a,l,n,r,Io,Io,(u,h,c)=>{ch(u,o,h,c);},Gt);for(let[u,h]of Object.entries(o))e[u]=h;r.length>0&&(e[l]=r);}}}function Do(s){let e={},t=Qg(s),n;try{n=JSON.parse(t);}catch{console.error("[Pixi\u2019VN Ink] Error parsing ink file");return}if(e.labels=uh(n.root),e.labels&&is in e.labels){let i=e.labels[is];delete e.labels[is],i.forEach(a=>{a.operations&&(e.initialOperations=e.initialOperations?[...e.initialOperations,...a.operations]:[...a.operations]);});}if(e.labels&&Ye in e.labels){let i=e.labels[Ye];delete e.labels[Ye],i.forEach(a=>{a.operations&&(e.initialOperations=e.initialOperations?[...e.initialOperations,...a.operations]:[...a.operations]);});}return e}function Qg(s){try{return new dh.Compiler(s).Compile().ToJson()||""}catch(e){return console.error("[Pixi\u2019VN Ink] Error compiling ink file",e),""}}async function fh(s){let e=[];if(Array.isArray(s)){for(let n of s){let i=await fh(n);e.concat(i);}return e}let t=Do(s);return t&&(sl(t,{operationStringConvert:et.generateOrRunOperationFromHashtagScript,skipEmptyDialogs:!0}),e.push(t)),e}function Zg(s){De.afterToTranslate=e=>ph(e,s);}function em(s){De.beforeToTranslate=e=>ph(e,s);}function ph(s,e){let t=s.match(/\[([^\]]+)\]/);if(t){let n=t[1],i=e(n);i&&(s=s.replace(t[0],i));}return s}function tm(s){De.translate=s;}function nm(s,e={},t={}){let n=[];return Array.isArray(s)?n=s:s.labels&&Object.values(s.labels).forEach(i=>{n=n.concat(i);}),De.generateJsonTranslation(n,e,t)}exports.convertInkText=Do;exports.generateJsonInkTranslation=nm;exports.importInkText=fh;exports.onInkHashtagScript=Eh;exports.onInkTranslate=tm;exports.onReplaceTextAfterTranslation=Zg;exports.onReplaceTextBeforeTranslation=em;