@drincs/pixi-vn-ink 0.9.5 → 0.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-54C4MLD7.mjs +48 -0
- package/dist/index.cjs +29 -29
- package/dist/index.d.cts +1 -5
- package/dist/index.d.ts +1 -5
- package/dist/index.mjs +1 -48
- package/dist/vite-listener.cjs +48 -0
- package/dist/vite-listener.d.cts +6 -0
- package/dist/vite-listener.d.ts +6 -0
- package/dist/vite-listener.mjs +1 -0
- package/package.json +10 -3
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import {b,a,d,c}from'./chunk-V6VCMMYR.mjs';import {RegisteredLabels,narration,LabelAbstract,NarrationManagerStatic}from'@drincs/pixi-vn/narration';import {storage,SYSTEM_RESERVED_STORAGE_KEYS}from'@drincs/pixi-vn/storage';import {canvas,VideoSprite,showVideo,ZoomTicker,RotateTicker,MoveTicker,FadeAlphaTicker,sound,Assets,narration as narration$1,ImageSprite,showImage,ImageContainer,showImageContainer,shakeEffect,pushOut,zoomOut,moveOut,removeWithDissolve,removeWithFade,pushIn,zoomIn,moveIn,showWithDissolve,showWithFade}from'@drincs/pixi-vn';import {RegisteredCharacters}from'@drincs/pixi-vn/characters';var Ts=b(Jn=>{Object.defineProperty(Jn,"__esModule",{value:true});Jn.CompilerOptions=void 0;var xs=class{constructor(t=null,e=[],n=false,i=null,a=null){this.sourceFilename=t,this.pluginNames=e,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=a;}};Jn.CompilerOptions=xs;});var Cl=b(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.DebugSourceRange=void 0;var Ps=class{constructor(t,e,n){this.length=t,this.debugMetadata=e,this.text=n;}};Un.DebugSourceRange=Ps;});var Kn=b(Hn=>{Object.defineProperty(Hn,"__esModule",{value:true});Hn.ErrorType=void 0;var vl;(function(r){r[r.Author=0]="Author",r[r.Warning=1]="Warning",r[r.Error=2]="Error";})(vl||(Hn.ErrorType=vl={}));});var yl=b(zn=>{Object.defineProperty(zn,"__esModule",{value:true});zn.Argument=void 0;var Os=class{constructor(t=null,e=null,n=null){this.identifier=t,this.isByReference=e,this.isDivertTarget=n;}get typeName(){return "Argument"}};zn.Argument=Os;});var D=b(X=>{Object.defineProperty(X,"__esModule",{value:true});X.filterUndef=X.isEquatable=X.nullIfUndefined=X.asINamedContentOrNull=X.asBooleanOrThrows=X.asNumberOrThrows=X.asOrThrows=X.asOrNull=void 0;function Fc(r,t){return r instanceof t?Sl(r):null}X.asOrNull=Fc;function kc(r,t){if(r instanceof t)return Sl(r);throw new Error(`${r} is not of type ${t}`)}X.asOrThrows=kc;function Rc(r){if(typeof r=="number")return r;throw new Error(`${r} is not a number`)}X.asNumberOrThrows=Rc;function Lc(r){if(typeof r=="boolean")return r;throw new Error(`${r} is not a boolean`)}X.asBooleanOrThrows=Lc;function Dc(r){return r.hasValidName&&r.name?r:null}X.asINamedContentOrNull=Dc;function Wc(r){return typeof r>"u"?null:r}X.nullIfUndefined=Wc;function jc(r){return typeof r=="object"&&typeof r.Equals=="function"}X.isEquatable=jc;function Sl(r,t){return r}function qc(r){return r!=null}X.filterUndef=qc;});var G=b(Xn=>{Object.defineProperty(Xn,"__esModule",{value:true});Xn.ParsedObject=void 0;var bl=D(),Ns=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=t=>{this.content===null&&(this.content=[]);let e=Array.isArray(t)?t:[t];for(let n of e)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(t))return t},this.InsertContent=(t,e)=>(this.content===null&&(this.content=[]),e.parent=this,this.content.splice(t,0,e),e),this.Find=t=>(e=null)=>{let n=(0, bl.asOrNull)(this,t);if(n!==null&&(e===null||e(n)===true))return n;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(t)(e);if(a)return a}return null},this.FindAll=t=>(e,n)=>{let i=Array.isArray(n)?n:[],a=(0, bl.asOrNull)(this,t);if(a!==null&&(!e||e(a)===true)&&i.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(t)(e,i);return i},this.Warning=(t,e=null)=>{this.Error(t,e,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let t=this;for(;t.parent;)t=t.parent;return t}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(t){this._runtimeObject=t;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let t=[],e=this.parent;for(;e;)t.push(e),e=e.parent;return t=t.reverse(),t}ResolveReferences(t){if(this.content!==null)for(let e of this.content)e.ResolveReferences(t);}Error(t,e=null,n=false){if(e===null&&(e=this),!(e._alreadyHadError&&!n||e._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(t,e,n);else throw new Error(`No parent object to send error to: ${t}`);n?e._alreadyHadWarning=true:e._alreadyHadError=true;}}};Xn.ParsedObject=Ns;});var Qn=b(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.AuthorWarning=void 0;var Mc=G(),As=class extends Mc.ParsedObject{constructor(t){super(),this.warningMessage=t,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Yn.AuthorWarning=As;});var dt=b(tn=>{Object.defineProperty(tn,"__esModule",{value:true});tn.Path=void 0;var xe=class r{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let t=arguments[0];this.componentsString=t;}else if(arguments[0]instanceof r.Component&&arguments[1]instanceof r){let t=arguments[0],e=arguments[1];this._components.push(t),this._components=this._components.concat(e._components);}else if(arguments[0]instanceof Array){let t=arguments[0],e=!!arguments[1];this._components=this._components.concat(t),this._isRelative=e;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let t=this._components.slice(1,this._components.length);return new r(t)}else return r.self}get length(){return this._components.length}get lastComponent(){let t=this._components.length-1;return t>=0?this._components[t]:null}get containsNamedComponent(){for(let t=0,e=this._components.length;t<e;t++)if(!this._components[t].isIndex)return true;return false}static get self(){let t=new r;return t._isRelative=true,t}GetComponent(t){return this._components[t]}PathByAppendingPath(t){let e=new r,n=0;for(let i=0;i<t._components.length&&t._components[i].isParent;++i)n++;for(let i=0;i<this._components.length-n;++i)e._components.push(this._components[i]);for(let i=n;i<t._components.length;++i)e._components.push(t._components[i]);return e}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(t){if(this._components.length=0,this._componentsString=t,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let e=this._componentsString.split(".");for(let n of e)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new r.Component(parseInt(n))):this._components.push(new r.Component(n));}toString(){return this.componentsString}Equals(t){if(t==null||t._components.length!=this._components.length||t.isRelative!=this.isRelative)return false;for(let e=0,n=t._components.length;e<n;e++)if(!t._components[e].Equals(this._components[e]))return false;return true}PathByAppendingComponent(t){let e=new r;return e._components.push(...this._components),e._components.push(t),e}};tn.Path=xe;xe.parentId="^";(function(r){class t{constructor(n){this.index=-1,this.name=null,typeof n=="string"?this.name=n:this.index=n;}get isIndex(){return this.index>=0}get isParent(){return this.name==r.parentId}static ToParent(){return new t(r.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}r.Component=t;})(xe||(tn.Path=xe={}));});var en=b(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.Debug=void 0;var _l;(function(r){function t(n,i,a){e(n instanceof i,a);}r.AssertType=t;function e(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}r.Assert=e;})(_l||(Zn.Debug=_l={}));});var nt=b(Te=>{Object.defineProperty(Te,"__esModule",{value:true});Te.throwNullException=Te.NullException=void 0;var ti=class extends Error{};Te.NullException=ti;function Bc(r){throw new ti(`${r} is null or undefined`)}Te.throwNullException=Bc;});var ft=b(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.InkObject=void 0;var Pe=dt(),nn=H(),Is=en(),Oe=D(),ei=nt(),Vs=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(t){this._debugMetadata=t;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(t){if(t===null)return null;let e=this.rootContentContainer;if(e){let n=e.ContentAtPath(t).obj;if(n){let i=n.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Pe.Path;else {let t=[],e=this,n=(0, Oe.asOrNull)(e.parent,nn.Container);for(;n!==null;){let i=(0, Oe.asINamedContentOrNull)(e);if(i!=null&&i.hasValidName){if(i.name===null)return (0, ei.throwNullException)("namedChild.name");t.unshift(new Pe.Path.Component(i.name));}else t.unshift(new Pe.Path.Component(n.content.indexOf(e)));e=n,n=(0, Oe.asOrNull)(n.parent,nn.Container);}this._path=new Pe.Path(t);}return this._path}ResolvePath(t){if(t===null)return (0, ei.throwNullException)("path");if(t.isRelative){let e=(0, Oe.asOrNull)(this,nn.Container);return e===null&&(Is.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),e=(0, Oe.asOrNull)(this.parent,nn.Container),Is.Debug.Assert(e!==null,"Expected parent to be a container"),Is.Debug.Assert(t.GetComponent(0).isParent),t=t.tail),e===null?(0, ei.throwNullException)("nearestContainer"):e.ContentAtPath(t)}else {let e=this.rootContentContainer;return e===null?(0, ei.throwNullException)("contentContainer"):e.ContentAtPath(t)}}ConvertPathToRelative(t){let e=this.path,n=Math.min(t.length,e.length),i=-1;for(let l=0;l<n;++l){let u=e.GetComponent(l),h=t.GetComponent(l);if(u.Equals(h))i=l;else break}if(i==-1)return t;let a=e.componentCount-1-i,s=[];for(let l=0;l<a;++l)s.push(Pe.Path.Component.ToParent());for(let l=i+1;l<t.componentCount;++l)s.push(t.GetComponent(l));return new Pe.Path(s,true)}CompactPathString(t){let e=null,n=null;return t.isRelative?(n=t.componentsString,e=this.path.PathByAppendingPath(t).componentsString):(n=this.ConvertPathToRelative(t).componentsString,e=t.componentsString),n.length<e.length?n:e}get rootContentContainer(){let t=this;for(;t.parent;)t=t.parent;return (0, Oe.asOrNull)(t,nn.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(t,e,n){t[e]&&(t[e]=null),t[e]=n,t[e]&&(t[e].parent=this);}Equals(t){return t===this}};ni.InkObject=Vs;});var he=b(ii=>{Object.defineProperty(ii,"__esModule",{value:true});ii.StringBuilder=void 0;var Fs=class{constructor(t){t=typeof t<"u"?t.toString():"",this.string=t;}get Length(){return this.string.length}Append(t){t!==null&&(this.string+=t);}AppendLine(t){typeof t<"u"&&this.Append(t),this.string+=`
|
|
2
|
+
`;}AppendFormat(t,...e){this.string+=t.replace(/{(\d+)}/g,(n,i)=>typeof e[i]<"u"?e[i]:n);}toString(){return this.string}Clear(){this.string="";}};ii.StringBuilder=Fs;});var gt=b(Ne=>{Object.defineProperty(Ne,"__esModule",{value:true});Ne.InkList=Ne.InkListItem=void 0;var kt=nt(),Gc=he(),pt=class r{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let t=arguments[0],e=arguments[1];this.originName=t,this.itemName=e;}else if(arguments[0]){let e=arguments[0].toString().split(".");this.originName=e[0],this.itemName=e[1];}}static get Null(){return new r(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(t){if(t instanceof r){let e=t;return e.itemName==this.itemName&&e.originName==this.originName}return false}copy(){return new r(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(t){let e=JSON.parse(t);if(!r.isLikeInkListItem(e))return r.Null;let n=e;return new r(n.originName,n.itemName)}static isLikeInkListItem(t){return !(typeof t!="object"||!t.hasOwnProperty("originName")||!t.hasOwnProperty("itemName")||typeof t.originName!="string"&&typeof t.originName!==null||typeof t.itemName!="string"&&typeof t.itemName!==null)}};Ne.InkListItem=pt;var ks=class r extends Map{constructor(){if(super(arguments[0]instanceof r?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof r){let t=arguments[0],e=t.originNames;e!==null&&(this._originNames=e.slice()),t.origins!==null&&(this.origins=t.origins.slice());}else if(typeof arguments[0]=="string"){let t=arguments[0],e=arguments[1];if(this.SetInitialOriginName(t),e.listDefinitions===null)return (0, kt.throwNullException)("originStory.listDefinitions");let n=e.listDefinitions.TryListGetDefinition(t,null);if(n.exists){if(n.result===null)return (0, kt.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+t)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let t=arguments[0];this.Add(t.Key,t.Value);}}static FromString(t,e){var n;if(t==null||t=="")return new r;let i=(n=e.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(t);if(i)return i.value===null?(0, kt.throwNullException)("listValue.value"):new r(i.value);throw new Error("Could not find the InkListItem from the string '"+t+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(t,e=null){if(t instanceof pt){let n=t;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, kt.throwNullException)("this.origins");for(let i of this.origins)if(i.name==n.originName){let a=i.TryGetValueForItem(n,0);if(a.exists){this.Add(n,a.result);return}else throw new Error("Could not add the item "+n+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(t!==null){let n=t,i=null;if(this.origins===null)return (0, kt.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, kt.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(e==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=r.FromString(n,e).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new pt(i.name,n),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(t){for(let[e]of this)if(pt.fromSerializedKey(e).itemName==t)return true;return false}ContainsKey(t){return this.has(t.serialized())}Add(t,e){let n=t.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${t}`);this.set(n,e);}Remove(t){return this.delete(t.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let t=this.maxItem.Key.originName,e=null;return this.origins.every(n=>n.name==t?(e=n,false):true),e}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[t]of this){let e=pt.fromSerializedKey(t);if(e.originName===null)return (0, kt.throwNullException)("item.originName");this._originNames.push(e.originName);}}return this._originNames}SetInitialOriginName(t){this._originNames=[t];}SetInitialOriginNames(t){t==null?this._originNames=null:this._originNames=t.slice();}get maxItem(){let t={Key:pt.Null,Value:0};for(let[e,n]of this){let i=pt.fromSerializedKey(e);(t.Key.isNull||n>t.Value)&&(t={Key:i,Value:n});}return t}get minItem(){let t={Key:pt.Null,Value:0};for(let[e,n]of this){let i=pt.fromSerializedKey(e);(t.Key.isNull||n<t.Value)&&(t={Key:i,Value:n});}return t}get inverse(){let t=new r;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let a=pt.fromSerializedKey(n);this.ContainsKey(a)||t.Add(a,i);}return t}get all(){let t=new r;if(this.origins!=null)for(let e of this.origins)for(let[n,i]of e.items){let a=pt.fromSerializedKey(n);t.set(a.serialized(),i);}return t}Union(t){let e=new r(this);for(let[n,i]of t)e.set(n,i);return e}Intersect(t){let e=new r;for(let[n,i]of this)t.has(n)&&e.set(n,i);return e}HasIntersection(t){for(let[e]of this)if(t.has(e))return true;return false}Without(t){let e=new r(this);for(let[n]of t)e.delete(n);return e}Contains(t){if(typeof t=="string")return this.ContainsItemNamed(t);let e=t;if(e.size==0||this.size==0)return false;for(let[n]of e)if(!this.has(n))return false;return true}GreaterThan(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>t.maxItem.Value}GreaterThanOrEquals(t){return this.Count==0?false:t.Count==0?true:this.minItem.Value>=t.minItem.Value&&this.maxItem.Value>=t.maxItem.Value}LessThan(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<t.minItem.Value}LessThanOrEquals(t){return t.Count==0?false:this.Count==0?true:this.maxItem.Value<=t.maxItem.Value&&this.minItem.Value<=t.minItem.Value}MaxAsList(){return this.Count>0?new r(this.maxItem):new r}MinAsList(){return this.Count>0?new r(this.minItem):new r}ListWithSubRange(t,e){if(this.Count==0)return new r;let n=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(t)?i=t:t instanceof r&&t.Count>0&&(i=t.minItem.Value),Number.isInteger(e)?a=e:e instanceof r&&e.Count>0&&(a=e.maxItem.Value);let s=new r;s.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=i&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(t){if(!(t instanceof r)||t.Count!=this.Count)return false;for(let[e]of this)if(!t.has(e))return false;return true}get orderedItems(){let t=new Array;for(let[e,n]of this){let i=pt.fromSerializedKey(e);t.push({Key:i,Value:n});}return t.sort((e,n)=>e.Key.originName===null?(0, kt.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, kt.throwNullException)("y.Key.originName"):e.Value==n.Value?e.Key.originName.localeCompare(n.Key.originName):e.Value<n.Value?-1:e.Value>n.Value?1:0),t}get singleItem(){for(let t of this.orderedItems)return t.Key;return null}toString(){let t=this.orderedItems,e=new Gc.StringBuilder;for(let n=0;n<t.length;n++){n>0&&e.Append(", ");let i=t[n].Key;if(i.itemName===null)return (0, kt.throwNullException)("item.itemName");e.Append(i.itemName);}return e.toString()}valueOf(){return NaN}};Ne.InkList=ks;});var rn=b(ri=>{Object.defineProperty(ri,"__esModule",{value:true});ri.StoryException=void 0;var Rs=class extends Error{constructor(t){super(t),this.useEndLineNumber=false,this.message=t,this.name="StoryException";}};ri.StoryException=Rs;});var Ae=b(zt=>{Object.defineProperty(zt,"__esModule",{value:true});zt.tryParseFloat=zt.tryParseInt=zt.tryGetValueFromMap=void 0;function $c(r,t,e){if(r===null)return {result:e,exists:false};let n=r.get(t);return typeof n>"u"?{result:e,exists:false}:{result:n,exists:true}}zt.tryGetValueFromMap=$c;function Jc(r,t=0){let e=parseInt(r);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}zt.tryParseInt=Jc;function Uc(r,t=0){let e=parseFloat(r);return Number.isNaN(e)?{result:t,exists:false}:{result:e,exists:true}}zt.tryParseFloat=Uc;});var $=b(J=>{Object.defineProperty(J,"__esModule",{value:true});J.ValueType=J.ListValue=J.VariablePointerValue=J.DivertTargetValue=J.StringValue=J.FloatValue=J.IntValue=J.BoolValue=J.Value=J.AbstractValue=void 0;var El=ft(),wl=dt(),ce=gt(),Hc=rn(),sn=D(),xl=Ae(),wt=nt(),si=class r extends El.InkObject{static Create(t,e){if(e){if(e===M.Int&&Number.isInteger(Number(t)))return new Lt(Number(t));if(e===M.Float&&!isNaN(t))return new Dt(Number(t))}if(typeof t=="boolean")return new Ie(!!t);if(typeof t=="string")return new Jt(String(t));if(Number.isInteger(Number(t)))return new Lt(Number(t));if(isNaN(t)){if(t instanceof wl.Path)return new ai((0, sn.asOrThrows)(t,wl.Path));if(t instanceof ce.InkList)return new oi((0, sn.asOrThrows)(t,ce.InkList))}else return new Dt(Number(t));return null}Copy(){return (0, sn.asOrThrows)(r.Create(this.valueObject),El.InkObject)}BadCastException(t){return new Hc.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+t)}};J.AbstractValue=si;var Rt=class extends si{constructor(t){super(),this.value=t;}get valueObject(){return this.value}toString(){return this.value===null?(0, wt.throwNullException)("Value.value"):this.value.toString()}};J.Value=Rt;var Ie=class extends Rt{constructor(t){super(t||false);}get isTruthy(){return !!this.value}get valueType(){return M.Bool}Cast(t){if(this.value===null)return (0, wt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==M.Int)return new Lt(this.value?1:0);if(t==M.Float)return new Dt(this.value?1:0);if(t==M.String)return new Jt(this.value?"true":"false");throw this.BadCastException(t)}toString(){return this.value?"true":"false"}};J.BoolValue=Ie;var Lt=class extends Rt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return M.Int}Cast(t){if(this.value===null)return (0, wt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==M.Bool)return new Ie(this.value!==0);if(t==M.Float)return new Dt(this.value);if(t==M.String)return new Jt(""+this.value);throw this.BadCastException(t)}};J.IntValue=Lt;var Dt=class extends Rt{constructor(t){super(t||0);}get isTruthy(){return this.value!=0}get valueType(){return M.Float}Cast(t){if(this.value===null)return (0, wt.throwNullException)("Value.value");if(t==this.valueType)return this;if(t==M.Bool)return new Ie(this.value!==0);if(t==M.Int)return new Lt(this.value);if(t==M.String)return new Jt(""+this.value);throw this.BadCastException(t)}};J.FloatValue=Dt;var Jt=class extends Rt{constructor(t){if(super(t||""),this._isNewline=this.value==`
|
|
3
|
+
`,this._isInlineWhitespace=true,this.value===null)return (0, wt.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(e=>e!=" "&&e!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return M.String}get isTruthy(){return this.value===null?(0, wt.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(t){if(t==this.valueType)return this;if(t==M.Int){let e=(0, xl.tryParseInt)(this.value);if(e.exists)return new Lt(e.result);throw this.BadCastException(t)}if(t==M.Float){let e=(0, xl.tryParseFloat)(this.value);if(e.exists)return new Dt(e.result);throw this.BadCastException(t)}throw this.BadCastException(t)}};J.StringValue=Jt;var ai=class extends Rt{constructor(t=null){super(t);}get valueType(){return M.DivertTarget}get targetPath(){return this.value===null?(0, wt.throwNullException)("Value.value"):this.value}set targetPath(t){this.value=t;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(t){if(t==this.valueType)return this;throw this.BadCastException(t)}toString(){return "DivertTargetValue("+this.targetPath+")"}};J.DivertTargetValue=ai;var Ls=class r extends Rt{constructor(t,e=-1){super(t),this._contextIndex=e;}get contextIndex(){return this._contextIndex}set contextIndex(t){this._contextIndex=t;}get variableName(){return this.value===null?(0, wt.throwNullException)("Value.value"):this.value}set variableName(t){this.value=t;}get valueType(){return M.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(t){if(t==this.valueType)return this;throw this.BadCastException(t)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new r(this.variableName,this.contextIndex)}};J.VariablePointerValue=Ls;var oi=class r extends Rt{get isTruthy(){return this.value===null?(0, wt.throwNullException)("this.value"):this.value.Count>0}get valueType(){return M.List}Cast(t){if(this.value===null)return (0, wt.throwNullException)("Value.value");if(t==M.Int){let e=this.value.maxItem;return e.Key.isNull?new Lt(0):new Lt(e.Value)}else if(t==M.Float){let e=this.value.maxItem;return e.Key.isNull?new Dt(0):new Dt(e.Value)}else if(t==M.String){let e=this.value.maxItem;return e.Key.isNull?new Jt(""):new Jt(e.Key.toString())}if(t==this.valueType)return this;throw this.BadCastException(t)}constructor(t,e){super(null),!t&&!e?this.value=new ce.InkList:t instanceof ce.InkList?this.value=new ce.InkList(t):t instanceof ce.InkListItem&&typeof e=="number"&&(this.value=new ce.InkList({Key:t,Value:e}));}static RetainListOriginsForAssignment(t,e){let n=(0, sn.asOrNull)(t,r),i=(0, sn.asOrNull)(e,r);if(i&&i.value===null)return (0, wt.throwNullException)("newList.value");if(n&&n.value===null)return (0, wt.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};J.ListValue=oi;var M;(function(r){r[r.Bool=-1]="Bool",r[r.Int=0]="Int",r[r.Float=1]="Float",r[r.List=2]="List",r[r.String=3]="String",r[r.DivertTarget=4]="DivertTarget",r[r.VariablePointer=5]="VariablePointer";})(M||(J.ValueType=M={}));});var Tl=b(li=>{Object.defineProperty(li,"__esModule",{value:true});li.SearchResult=void 0;var Kc=H(),Ds=class r{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof Kc.Container?this.obj:null}copy(){let t=new r;return t.obj=this.obj,t.approximate=this.approximate,t}};li.SearchResult=Ds;});var H=b(on=>{Object.defineProperty(on,"__esModule",{value:true});on.Container=void 0;var zc=$(),Pl=nt(),Xc=he(),Ve=ft(),Yc=Tl(),Ol=dt(),Nl=en(),Qc=Ae(),Xt=D(),an=class r extends Ve.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(t){this.AddContent(t);}get namedOnlyContent(){let t=new Map;for(let[e,n]of this.namedContent){let i=(0, Xt.asOrThrows)(n,Ve.InkObject);t.set(e,i);}for(let e of this.content){let n=(0, Xt.asINamedContentOrNull)(e);n!=null&&n.hasValidName&&t.delete(n.name);}return t.size==0&&(t=null),t}set namedOnlyContent(t){let e=this.namedOnlyContent;if(e!=null)for(let[n]of e)this.namedContent.delete(n);if(t!=null)for(let[,n]of t){let i=(0, Xt.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let t=0;return this.visitsShouldBeCounted&&(t|=r.CountFlags.Visits),this.turnIndexShouldBeCounted&&(t|=r.CountFlags.Turns),this.countingAtStartOnly&&(t|=r.CountFlags.CountStartOnly),t==r.CountFlags.CountStartOnly&&(t=0),t}set countFlags(t){let e=t;(e&r.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(e&r.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(e&r.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let t=[],e=this;for(;e instanceof r;)e.content.length>0&&(t.push(new Ol.Path.Component(0)),e=e.content[0]);return new Ol.Path(t)}AddContent(t){if(t instanceof Array){let e=t;for(let n of e)this.AddContent(n);}else {let e=t;if(this._content.push(e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}}TryAddNamedContent(t){let e=(0, Xt.asINamedContentOrNull)(t);e!=null&&e.hasValidName&&this.AddToNamedContentOnly(e);}AddToNamedContentOnly(t){Nl.Debug.AssertType(t,Ve.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let e=(0, Xt.asOrThrows)(t,Ve.InkObject);if(e.parent=this,t.name===null)return (0, Pl.throwNullException)("namedContentObj.name");this.namedContent.set(t.name,t);}ContentAtPath(t,e=0,n=-1){n==-1&&(n=t.length);let i=new Yc.SearchResult;i.approximate=false;let a=this,s=this;for(let o=e;o<n;++o){let l=t.GetComponent(o);if(a==null){i.approximate=true;break}let u=a.ContentWithPathComponent(l);if(u==null){i.approximate=true;break}let h=(0, Xt.asOrNull)(u,r);if(o<n-1&&h==null){i.approximate=true;break}s=u,a=h;}return i.obj=s,i}InsertContent(t,e){if(this.content.splice(e,0,t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}AddContentsOfContainer(t){this.content.push(...t.content);for(let e of t.content)e.parent=this,this.TryAddNamedContent(e);}ContentWithPathComponent(t){if(t.isIndex)return t.index>=0&&t.index<this.content.length?this.content[t.index]:null;if(t.isParent)return this.parent;{if(t.name===null)return (0, Pl.throwNullException)("component.name");let e=(0, Qc.tryGetValueFromMap)(this.namedContent,t.name,null);return e.exists?(0, Xt.asOrThrows)(e.result,Ve.InkObject):null}}BuildStringOfHierarchy(){let t;if(arguments.length==0)return t=new Xc.StringBuilder,this.BuildStringOfHierarchy(t,0,null),t.toString();t=arguments[0];let e=arguments[1],n=arguments[2];function i(){for(let o=0;o<4*e;++o)t.Append(" ");}i(),t.Append("["),this.hasValidName&&t.AppendFormat(" ({0})",this.name),this==n&&t.Append(" <---"),t.AppendLine(),e++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof r?o.BuildStringOfHierarchy(t,e,n):(i(),o instanceof zc.StringValue?(t.Append('"'),t.Append(o.toString().replace(`
|
|
4
|
+
`,"\\n")),t.Append('"')):t.Append(o.toString())),s!=this.content.length-1&&t.Append(","),!(o instanceof r)&&o==n&&t.Append(" <---"),t.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, Xt.asOrThrows)(o,Ve.InkObject))>=0||a.set(s,o);if(a.size>0){i(),t.AppendLine("-- named: --");for(let[,s]of a)Nl.Debug.AssertType(s,r,"Can only print out named Containers"),s.BuildStringOfHierarchy(t,e,n),t.AppendLine();}e--,i(),t.Append("]");}};on.Container=an;(function(r){(function(e){e[e.Start=0]="Start",e[e.Visits=1]="Visits",e[e.Turns=2]="Turns",e[e.CountStartOnly=4]="CountStartOnly";})(r.CountFlags||(r.CountFlags={}));})(an||(on.Container=an={}));});var it=b(un=>{Object.defineProperty(un,"__esModule",{value:true});un.ControlCommand=void 0;var Zc=ft(),ln=class r extends Zc.InkObject{get commandType(){return this._commandType}constructor(t=r.CommandType.NotSet){super(),this._commandType=t;}Copy(){return new r(this.commandType)}static EvalStart(){return new r(r.CommandType.EvalStart)}static EvalOutput(){return new r(r.CommandType.EvalOutput)}static EvalEnd(){return new r(r.CommandType.EvalEnd)}static Duplicate(){return new r(r.CommandType.Duplicate)}static PopEvaluatedValue(){return new r(r.CommandType.PopEvaluatedValue)}static PopFunction(){return new r(r.CommandType.PopFunction)}static PopTunnel(){return new r(r.CommandType.PopTunnel)}static BeginString(){return new r(r.CommandType.BeginString)}static EndString(){return new r(r.CommandType.EndString)}static NoOp(){return new r(r.CommandType.NoOp)}static ChoiceCount(){return new r(r.CommandType.ChoiceCount)}static Turns(){return new r(r.CommandType.Turns)}static TurnsSince(){return new r(r.CommandType.TurnsSince)}static ReadCount(){return new r(r.CommandType.ReadCount)}static Random(){return new r(r.CommandType.Random)}static SeedRandom(){return new r(r.CommandType.SeedRandom)}static VisitIndex(){return new r(r.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new r(r.CommandType.SequenceShuffleIndex)}static StartThread(){return new r(r.CommandType.StartThread)}static Done(){return new r(r.CommandType.Done)}static End(){return new r(r.CommandType.End)}static ListFromInt(){return new r(r.CommandType.ListFromInt)}static ListRange(){return new r(r.CommandType.ListRange)}static ListRandom(){return new r(r.CommandType.ListRandom)}static BeginTag(){return new r(r.CommandType.BeginTag)}static EndTag(){return new r(r.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};un.ControlCommand=ln;(function(r){(function(e){e[e.NotSet=-1]="NotSet",e[e.EvalStart=0]="EvalStart",e[e.EvalOutput=1]="EvalOutput",e[e.EvalEnd=2]="EvalEnd",e[e.Duplicate=3]="Duplicate",e[e.PopEvaluatedValue=4]="PopEvaluatedValue",e[e.PopFunction=5]="PopFunction",e[e.PopTunnel=6]="PopTunnel",e[e.BeginString=7]="BeginString",e[e.EndString=8]="EndString",e[e.NoOp=9]="NoOp",e[e.ChoiceCount=10]="ChoiceCount",e[e.Turns=11]="Turns",e[e.TurnsSince=12]="TurnsSince",e[e.ReadCount=13]="ReadCount",e[e.Random=14]="Random",e[e.SeedRandom=15]="SeedRandom",e[e.VisitIndex=16]="VisitIndex",e[e.SequenceShuffleIndex=17]="SequenceShuffleIndex",e[e.StartThread=18]="StartThread",e[e.Done=19]="Done",e[e.End=20]="End",e[e.ListFromInt=21]="ListFromInt",e[e.ListRange=22]="ListRange",e[e.ListRandom=23]="ListRandom",e[e.BeginTag=24]="BeginTag",e[e.EndTag=25]="EndTag",e[e.TOTAL_VALUES=26]="TOTAL_VALUES";})(r.CommandType||(r.CommandType={}));})(ln||(un.ControlCommand=ln={}));});var xt=b(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.Expression=void 0;var Al=H(),Ws=it(),td=G(),js=class extends td.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let t=new Al.Container;return t.AddContent(Ws.ControlCommand.EvalStart()),this.GenerateIntoContainer(t),this.outputWhenComplete&&t.AddContent(Ws.ControlCommand.EvalOutput()),t.AddContent(Ws.ControlCommand.EvalEnd()),t},this.GenerateConstantIntoContainer=t=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new Al.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let e of this._prototypeRuntimeConstantExpression.content){let n=e.Copy();n&&t.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(t){return false}};ui.Expression=js;});var de=b(hi=>{Object.defineProperty(hi,"__esModule",{value:true});hi.Void=void 0;var ed=ft(),qs=class extends ed.InkObject{toString(){return "Void"}};hi.Void=qs;});var Wt=b(di=>{Object.defineProperty(di,"__esModule",{value:true});di.NativeFunctionCall=void 0;var w=$(),hn=rn(),nd=de(),ci=gt(),id=ft(),Tt=D(),mt=nt(),I=class r extends id.InkObject{static CallWithName(t){return new r(t)}static CallExistsWithName(t){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(t)}get name(){return this._name===null?(0, mt.throwNullException)("NativeFunctionCall._name"):this._name}set name(t){this._name=t,this._isPrototype||(r._nativeFunctions===null?(0, mt.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=r._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(t){this._numberOfParameters=t;}Call(t){if(this._prototype)return this._prototype.Call(t);if(this.numberOfParameters!=t.length)throw new Error("Unexpected number of parameters");let e=false;for(let a of t){if(a instanceof nd.Void)throw new hn.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 w.ListValue&&(e=true);}if(t.length==2&&e)return this.CallBinaryListOperation(t);let n=this.CoerceValuesToSingleType(t),i=n[0].valueType;return i==w.ValueType.Int?this.CallType(n):i==w.ValueType.Float?this.CallType(n):i==w.ValueType.String?this.CallType(n):i==w.ValueType.DivertTarget?this.CallType(n):i==w.ValueType.List?this.CallType(n):null}CallType(t){let e=(0, Tt.asOrThrows)(t[0],w.Value),n=e.valueType,i=e,a=t.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){let o=w.ValueType[n];throw new hn.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, Tt.asOrThrows)(t[1],w.Value),u=s;if(i.value===null||l.value===null)return (0, mt.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(i.value,l.value);return w.Value.Create(h)}else {let o=s;if(i.value===null)return (0, mt.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(i.value);return this.name===r.Int?w.Value.Create(l,w.ValueType.Int):this.name===r.Float?w.Value.Create(l,w.ValueType.Float):w.Value.Create(l,e.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+t.length)}CallBinaryListOperation(t){if((this.name=="+"||this.name=="-")&&t[0]instanceof w.ListValue&&t[1]instanceof w.IntValue)return this.CallListIncrementOperation(t);let e=(0, Tt.asOrThrows)(t[0],w.Value),n=(0, Tt.asOrThrows)(t[1],w.Value);if((this.name=="&&"||this.name=="||")&&(e.valueType!=w.ValueType.List||n.valueType!=w.ValueType.List)){if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(w.ValueType.Int);if(i===null)return (0, mt.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, Tt.asBooleanOrThrows)(i(e.isTruthy?1:0,n.isTruthy?1:0));return new w.BoolValue(a)}if(e.valueType==w.ValueType.List&&n.valueType==w.ValueType.List)return this.CallType([e,n]);throw new hn.StoryException("Can not call use "+this.name+" operation on "+w.ValueType[e.valueType]+" and "+w.ValueType[n.valueType])}CallListIncrementOperation(t){let e=(0, Tt.asOrThrows)(t[0],w.ListValue),n=(0, Tt.asOrThrows)(t[1],w.IntValue),i=new ci.InkList;if(e.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of e.value){let o=ci.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, mt.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(w.ValueType.Int);if(n.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(s,n.value),h=null;if(e.value.origins===null)return (0, mt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of e.value.origins)if(c.name==o.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(u,ci.InkListItem.Null);c.exists&&i.Add(c.result,u);}}return new w.ListValue(i)}CoerceValuesToSingleType(t){let e=w.ValueType.Int,n=null;for(let a of t){let s=(0, Tt.asOrThrows)(a,w.Value);s.valueType>e&&(e=s.valueType),s.valueType==w.ValueType.List&&(n=(0, Tt.asOrNull)(s,w.ListValue));}let i=[];if(w.ValueType[e]==w.ValueType[w.ValueType.List])for(let a of t){let s=(0, Tt.asOrThrows)(a,w.Value);if(s.valueType==w.ValueType.List)i.push(s);else if(s.valueType==w.ValueType.Int){let o=parseInt(s.valueObject);if(n=(0, Tt.asOrThrows)(n,w.ListValue),n.value===null)return (0, mt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, mt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,ci.InkListItem.Null);if(u.exists){let h=new w.ListValue(u.result,o);i.push(h);}else throw new hn.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=w.ValueType[s.valueType];throw new hn.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of t){let o=(0, Tt.asOrThrows)(a,w.Value).Cast(e);i.push(o);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)r.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let t=arguments[0];r.GenerateNativeFunctionsIfNecessary(),this.name=t;}else if(arguments.length===2){let t=arguments[0],e=arguments[1];this._isPrototype=true,this.name=t,this.numberOfParameters=e;}}static Identity(t){return t}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,i)=>n+i),this.AddIntBinaryOp(this.Subtract,(n,i)=>n-i),this.AddIntBinaryOp(this.Multiply,(n,i)=>n*i),this.AddIntBinaryOp(this.Divide,(n,i)=>Math.floor(n/i)),this.AddIntBinaryOp(this.Mod,(n,i)=>n%i),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,i)=>n==i),this.AddIntBinaryOp(this.Greater,(n,i)=>n>i),this.AddIntBinaryOp(this.Less,(n,i)=>n<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddIntBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddIntBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddIntBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddIntBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddIntBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddIntUnaryOp(this.Floor,r.Identity),this.AddIntUnaryOp(this.Ceiling,r.Identity),this.AddIntUnaryOp(this.Int,r.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,i)=>n+i),this.AddFloatBinaryOp(this.Subtract,(n,i)=>n-i),this.AddFloatBinaryOp(this.Multiply,(n,i)=>n*i),this.AddFloatBinaryOp(this.Divide,(n,i)=>n/i),this.AddFloatBinaryOp(this.Mod,(n,i)=>n%i),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,i)=>n==i),this.AddFloatBinaryOp(this.Greater,(n,i)=>n>i),this.AddFloatBinaryOp(this.Less,(n,i)=>n<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddFloatBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddFloatBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddFloatBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddFloatBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,r.Identity),this.AddStringBinaryOp(this.Add,(n,i)=>n+i),this.AddStringBinaryOp(this.Equal,(n,i)=>n===i),this.AddStringBinaryOp(this.NotEquals,(n,i)=>n!==i),this.AddStringBinaryOp(this.Has,(n,i)=>n.includes(i)),this.AddStringBinaryOp(this.Hasnt,(n,i)=>!n.includes(i)),this.AddListBinaryOp(this.Add,(n,i)=>n.Union(i)),this.AddListBinaryOp(this.Subtract,(n,i)=>n.Without(i)),this.AddListBinaryOp(this.Has,(n,i)=>n.Contains(i)),this.AddListBinaryOp(this.Hasnt,(n,i)=>!n.Contains(i)),this.AddListBinaryOp(this.Intersect,(n,i)=>n.Intersect(i)),this.AddListBinaryOp(this.Equal,(n,i)=>n.Equals(i)),this.AddListBinaryOp(this.Greater,(n,i)=>n.GreaterThan(i)),this.AddListBinaryOp(this.Less,(n,i)=>n.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,i)=>n.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(n,i)=>n.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(n,i)=>!n.Equals(i)),this.AddListBinaryOp(this.And,(n,i)=>n.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(n,i)=>n.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let t=(n,i)=>n.Equals(i),e=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,w.ValueType.DivertTarget,t),this.AddOpToNativeFunc(this.NotEquals,2,w.ValueType.DivertTarget,e);}}AddOpFuncForType(t,e){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(t,e);}static AddOpToNativeFunc(t,e,n,i){if(this._nativeFunctions===null)return (0, mt.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(t);a||(a=new r(t,e),this._nativeFunctions.set(t,a)),a.AddOpFuncForType(n,i);}static AddIntBinaryOp(t,e){this.AddOpToNativeFunc(t,2,w.ValueType.Int,e);}static AddIntUnaryOp(t,e){this.AddOpToNativeFunc(t,1,w.ValueType.Int,e);}static AddFloatBinaryOp(t,e){this.AddOpToNativeFunc(t,2,w.ValueType.Float,e);}static AddFloatUnaryOp(t,e){this.AddOpToNativeFunc(t,1,w.ValueType.Float,e);}static AddStringBinaryOp(t,e){this.AddOpToNativeFunc(t,2,w.ValueType.String,e);}static AddListBinaryOp(t,e){this.AddOpToNativeFunc(t,2,w.ValueType.List,e);}static AddListUnaryOp(t,e){this.AddOpToNativeFunc(t,1,w.ValueType.List,e);}toString(){return 'Native "'+this.name+'"'}};di.NativeFunctionCall=I;I.Add="+";I.Subtract="-";I.Divide="/";I.Multiply="*";I.Mod="%";I.Negate="_";I.Equal="==";I.Greater=">";I.Less="<";I.GreaterThanOrEquals=">=";I.LessThanOrEquals="<=";I.NotEquals="!=";I.Not="!";I.And="&&";I.Or="||";I.Min="MIN";I.Max="MAX";I.Pow="POW";I.Floor="FLOOR";I.Ceiling="CEILING";I.Int="INT";I.Float="FLOAT";I.Has="?";I.Hasnt="!?";I.Intersect="^";I.ListMin="LIST_MIN";I.ListMax="LIST_MAX";I.All="LIST_ALL";I.Count="LIST_COUNT";I.ValueOfList="LIST_VALUE";I.Invert="LIST_INVERT";I._nativeFunctions=null;});var pi=b(fi=>{Object.defineProperty(fi,"__esModule",{value:true});fi.NumberExpression=void 0;var rd=xt(),Ms=$(),sd=D(),Bs=class r extends rd.Expression{constructor(t,e){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new Ms.IntValue(this.value)):this.isFloat()?n.AddContent(new Ms.FloatValue(this.value)):this.isBool()&&n.AddContent(new Ms.BoolValue(this.value));},this.toString=()=>String(this.value),typeof t=="number"&&!Number.isNaN(t)||typeof t=="boolean")this.value=t,this.subtype=e;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(t){let e=(0, sd.asOrNull)(t,r);return e?e.subtype==this.subtype&&e.value==this.value:false}};fi.NumberExpression=Bs;});var Gs=b(gi=>{Object.defineProperty(gi,"__esModule",{value:true});gi.UnaryExpression=void 0;var ad=xt(),od=Wt(),Fe=pi(),ld=D(),cn=class extends ad.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(t,e){super(),this.op=e,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(od.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(t);}get typeName(){return "UnaryExpression"}};gi.UnaryExpression=cn;cn.WithInner=(r,t)=>{let e=(0, ld.asOrNull)(r,Fe.NumberExpression);if(e){if(t==="-"){if(e.isInt())return new Fe.NumberExpression(-e.value,"int");if(e.isFloat())return new Fe.NumberExpression(-e.value,"float")}else if(t=="!"||t=="not"){if(e.isInt())return new Fe.NumberExpression(e.value==0,"bool");if(e.isFloat())return new Fe.NumberExpression(e.value==0,"bool");if(e.isBool())return new Fe.NumberExpression(!e.value,"bool")}throw new Error("Unexpected operation or number type")}return new cn(r,t)};});var Js=b(mi=>{Object.defineProperty(mi,"__esModule",{value:true});mi.BinaryExpression=void 0;var ud=xt(),hd=Wt(),cd=Gs(),dd=D(),$s=class extends ud.Expression{constructor(t,e,n){super(),this.opName=n,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(hd.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(t),this.rightExpression=this.AddContent(e),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(t){if(super.ResolveReferences(t),this.NativeNameForOp(this.opName)==="?"){let e=(0, dd.asOrNull)(this.leftExpression,cd.UnaryExpression);e!==null&&(e.op==="not"||e.op==="!")&&this.Error(`Using 'not' or '!' here negates '${e.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};mi.BinaryExpression=$s;});var fn=b(Ci=>{Object.defineProperty(Ci,"__esModule",{value:true});Ci.CharacterSet=void 0;var dn=class{constructor(t){this.set=new Set,this.Add=e=>this.set.add(e),this.AddRange=(e,n)=>{for(let i=e.charCodeAt(0);i<=n.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=e=>{if(typeof e=="string"||Array.isArray(e))for(let n of e)this.Add(n);else for(let n of e.set)this.Add(n);return this},t&&this.AddCharacters(t);}};Ci.CharacterSet=dn;dn.FromRange=(r,t)=>new dn().AddRange(r,t);});var Vl=b(vi=>{Object.defineProperty(vi,"__esModule",{value:true});vi.CharacterRange=void 0;var Il=fn(),pn=class{constructor(t,e,n=[]){if(this._start=t,this._end=e,this._correspondingCharSet=new Il.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 Il.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}};vi.CharacterRange=pn;pn.Define=(r,t,e=[])=>new pn(r,t,e);});var Si=b(yi=>{Object.defineProperty(yi,"__esModule",{value:true});yi.ChoicePoint=void 0;var fd=ft(),pd=dt(),Us=nt(),Hs=class extends fd.InkObject{constructor(t=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=t;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let t=this.choiceTarget;t&&(this._pathOnChoice=t.path);}return this._pathOnChoice}set pathOnChoice(t){this._pathOnChoice=t;}get choiceTarget(){return this._pathOnChoice===null?(0, Us.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Us.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(t){this.pathOnChoice=new pd.Path(t);}get flags(){let t=0;return this.hasCondition&&(t|=1),this.hasStartContent&&(t|=2),this.hasChoiceOnlyContent&&(t|=4),this.isInvisibleDefault&&(t|=8),this.onceOnly&&(t|=16),t}set flags(t){this.hasCondition=(t&1)>0,this.hasStartContent=(t&2)>0,this.hasChoiceOnlyContent=(t&4)>0,this.isInvisibleDefault=(t&8)>0,this.onceOnly=(t&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Us.throwNullException)("ChoicePoint.pathOnChoice");let e=this.pathOnChoice.toString();return "Choice: -> "+e}};yi.ChoicePoint=Hs;});var fe=b(bi=>{Object.defineProperty(bi,"__esModule",{value:true});bi.PushPopType=void 0;var Fl;(function(r){r[r.Tunnel=0]="Tunnel",r[r.Function=1]="Function",r[r.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Fl||(bi.PushPopType=Fl={}));});var gn=b(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.Pointer=void 0;var gd=dt(),Ks=class r{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 gd.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 r(this.container,this.index)}static StartOf(t){return new r(t,0)}static get Null(){return new r(null,-1)}};_i.Pointer=Ks;});var jt=b(wi=>{Object.defineProperty(wi,"__esModule",{value:true});wi.Divert=void 0;var md=dt(),Cd=fe(),vd=he(),yd=ft(),zs=gn(),kl=H(),Ei=nt(),Xs=class r extends yd.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let t=this.targetPointer.Resolve();t&&(this._targetPath=t.path);}return this._targetPath}set targetPath(t){this._targetPath=t,this._targetPointer=zs.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let t=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, Ei.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, Ei.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(t===null)return (0, Ei.throwNullException)("targetObj");this._targetPointer.container=t.parent instanceof kl.Container?t.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=zs.Pointer.StartOf(t instanceof kl.Container?t:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(t){t==null?this.targetPath=null:this.targetPath=new md.Path(t);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(t){super(),this._targetPath=null,this._targetPointer=zs.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof t<"u"&&(this.pushesToStack=true,this.stackPushType=t);}Equals(t){let e=t;return e instanceof r&&this.hasVariableTarget==e.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==e.variableDivertName:this.targetPath===null?(0, Ei.throwNullException)("this.targetPath"):this.targetPath.Equals(e.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let t=new vd.StringBuilder,e=this.targetPath.toString();return t.Append("Divert"),this.isConditional&&t.Append("?"),this.pushesToStack&&(this.stackPushType==Cd.PushPopType.Function?t.Append(" function"):t.Append(" tunnel")),t.Append(" -> "),t.Append(this.targetPathString),t.Append(" ("),t.Append(e),t.Append(")"),t.toString()}}};wi.Divert=Xs;});var Ut=b(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.SymbolType=void 0;var Rl;(function(r){r[r.Knot=0]="Knot",r[r.List=1]="List",r[r.ListItem=2]="ListItem",r[r.Var=3]="Var",r[r.SubFlowAndWeave=4]="SubFlowAndWeave",r[r.Arg=5]="Arg",r[r.Temp=6]="Temp";})(Rl||(xi.SymbolType=Rl={}));});var Yt=b(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.VariableAssignment=void 0;var Sd=ft(),Ys=class extends Sd.InkObject{constructor(t,e){super(),this.variableName=t||null,this.isNewDeclaration=!!e,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};Ti.VariableAssignment=Ys;});var ke=b(Oi=>{Object.defineProperty(Oi,"__esModule",{value:true});Oi.Choice=void 0;var bd=Si(),Pi=H(),Qt=it(),Qs=jt(),Ll=$(),_d=G(),Ed=Ut(),Dl=Yt(),Zs=class extends _d.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get condition(){return this._condition}set condition(t){this._condition=t,t&&this.AddContent(t);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(t,e,n){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new Pi.Container,this._runtimeChoice=new bd.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Qt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Ll.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Dl.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Qt.ControlCommand.BeginString()),this._divertToStartContentOuter=new Qs.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Qs.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Pi.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Qt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Qt.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Qt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Qt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Pi.Container,this.startContent){this._returnToR2=new Ll.DivertTargetValue,this._innerContentContainer.AddContent(Qt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Qt.ControlCommand.EvalEnd());let i=new Dl.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Qs.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Pi.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=t,this.choiceOnlyContent=e,this.innerContent=n,this.indentationDepth=1,t&&this.AddContent(this.startContent),e&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(t){var e;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(t),this.identifier&&(((e=this.identifier)===null||e===void 0?void 0:e.name)||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,Ed.SymbolType.SubFlowAndWeave);}};Oi.Choice=Zs;});var Wl=b(Ai=>{Object.defineProperty(Ai,"__esModule",{value:true});Ai.StringParserElement=void 0;var Ni=class r{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=t=>{r._uniqueIdCounter++,this.uniqueId=r._uniqueIdCounter,this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.customFlags=t.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=t=>{this.characterIndex=t.characterIndex,this.characterInLineIndex=t.characterInLineIndex,this.lineIndex=t.lineIndex,this.reportedErrorInScope=t.reportedErrorInScope,this.customFlags=t.customFlags;};}};Ai.StringParserElement=Ni;Ni._uniqueIdCounter=1e3;});var ql=b(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.StringParserState=void 0;var jl=Wl(),ta=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(t){this.currentElement.lineIndex=t;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(t){this.currentElement.characterIndex=t;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(t){this.currentElement.characterInLineIndex=t;}get customFlags(){return this.currentElement.customFlags}set customFlags(t){this.currentElement.customFlags=t;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new jl.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let e=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(e),n.uniqueId},this.Pop=e=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=e)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=e=>{if(this.currentElement.uniqueId!=e)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let e=this._stack[this._numElements-2],n=this._stack[this._numElements-1];e.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let e of this._stack)e.reportedErrorInScope=true;};let t=200;for(let e=0;e<t;e++)this._stack[e]=new jl.StringParserElement;this._numElements=1;}};Ii.StringParserState=ta;});var na=b(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.StringParser=pe.ParseSuccess=void 0;var ea=fn(),wd=ql();pe.ParseSuccess=Symbol("ParseSuccessStruct");var mn=class r{constructor(t){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=n=>(this.state.Pop(n),null),this.CancelRule=n=>{this.state.Pop(n);},this.SucceedRule=(n,i=null)=>{let a=this.state.Peek(n),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,s,a),this.state.Squash();let o=i;return o===null&&(o=r.ParseSuccess),o},this.Expect=(n,i=null,a=null)=>{let s=this.ParseObject(n);if(s===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&&(s=a());}return s},this.Error=(n,i=false)=>{this.ErrorOnLine(n,this.lineIndex+1,i);},this.ErrorWithParsedObject=(n,i,a=false)=>{this.ErrorOnLine(n,i.debugMetadata?i.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(n,i,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,i-1,a);else throw new Error(`${s} on line ${i}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
|
|
5
|
+
\r`)),this.SetFlag=(n,i)=>{i?this.state.customFlags|=n:this.state.customFlags&=~n;},this.GetFlag=n=>!!(this.state.customFlags&n),this.ParseObject=n=>{let i=this.BeginRule(),a=this.state.stackHeight,s=n();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return s===null?this.FailRule(i):(this.SucceedRule(i,s),s)},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?r.ParseSuccess:i},this.Exclude=n=>()=>this.ParseObject(n)&&r.ParseSuccess,this.OptionalExclude=n=>()=>(this.ParseObject(n),r.ParseSuccess),this.String=n=>()=>this.ParseString(n),this.TryAddResultToList=(n,i,a=true)=>{if(n!==r.ParseSuccess){if(a&&Array.isArray(n)){let s=n;if(s!==null){for(let o of s)i.push(o);return}}i.push(n);}},this.Interleave=(n,i,a=null,s=true)=>{let o=this.BeginRule(),l=[],u=this.ParseObject(n);if(u===null)return this.FailRule(o);this.TryAddResultToList(u,l,s);let h=null,c=null;do{if(a!==null&&this.Peek(a)!==null||(h=this.ParseObject(i),h===null))break;if(this.TryAddResultToList(h,l,s),c=null,h!==null){if(c=this.ParseObject(n),c===null)break;this.TryAddResultToList(c,l,s);}}while((h!==null||c!==null)&&!(h===r.ParseSuccess&&c==r.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,s=this.characterInLineIndex,o=this.lineIndex,l=true;for(let u=0;u<n.length;u+=1){let h=n[u];if(this._chars[a]!==h){l=false;break}h===`
|
|
6
|
+
`&&(o++,s=-1),a++,s++;}return this.index=a,this.characterInLineIndex=s,this.lineIndex=o,l?this.SucceedRule(i,n):this.FailRule(i)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){let n=this._chars[this.index];return n===`
|
|
7
|
+
`&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,i=-1)=>this.ParseCharactersFromString(n,false,i),this.ParseUntilCharactersFromCharSet=(n,i=-1)=>this.ParseCharactersFromCharSet(n,false,i),this.ParseCharactersFromString=(n,i=-1,a=-1)=>{let s=new ea.CharacterSet(n);return typeof i=="number"?this.ParseCharactersFromCharSet(s,true,i):this.ParseCharactersFromCharSet(s,i,a)},this.ParseCharactersFromCharSet=(n,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,h=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===i&&h<a;)this._chars[o]===`
|
|
8
|
+
`&&(u+=1,l=-1),o+=1,l+=1,h+=1;return this.index=o,this.characterInLineIndex=l,this.lineIndex=u,this.index>s?this._chars.slice(s,this.index).join(""):null},this.Peek=n=>{let 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 s=this.ParseCharactersFromCharSet(r.numbersCharacterSet);if(s===null)return this.index=n,this.characterInLineIndex=i,null;let o;return Number.isNaN(Number(s))?(this.Error("Failed to read integer value: "+s+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(o=Number(s),a?-o:o)},this.ParseFloat=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let s=this.ParseCharactersFromCharSet(r.numbersCharacterSet);return +`${a}.${s}`}return this.index=n,this.characterInLineIndex=i,null},this.ParseNewline=()=>{let n=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
|
|
9
|
+
`)===null?this.FailRule(n):this.SucceedRule(n,`
|
|
10
|
+
`)};let e=this.PreProcessInputString(t);this.state=new wd.StringParserState,t?this._chars=e.split(""):this._chars=[],this.inputString=e;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(t){return t}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(t){this.state.lineIndex=t;}set characterInLineIndex(t){this.state.characterInLineIndex=t;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(t){this.state.characterIndex=t;}ParseUntil(t,e=null,n=null){let i=this.BeginRule(),a=new ea.CharacterSet;e!==null&&(a.set=new Set([...a.set.values(),...e.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let s="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(s+=l),o=this.Peek(t),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(e!==null&&e.set.has(u)){s+=u,u===`
|
|
11
|
+
`&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(i,String(s)):this.FailRule(i)}};pe.StringParser=mn;mn.ParseSuccess=pe.ParseSuccess;mn.numbersCharacterSet=new ea.CharacterSet("0123456789");});var Ml=b(Vi=>{Object.defineProperty(Vi,"__esModule",{value:true});Vi.CommentEliminator=void 0;var ia=fn(),xd=na(),ra=class extends xd.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new ia.CharacterSet(`/\r
|
|
12
|
+
`),this._commentBlockEndCharacter=new ia.CharacterSet("*"),this._newlineCharacters=new ia.CharacterSet(`
|
|
13
|
+
\r`),this.Process=()=>{let t=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return t!==null?t.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let t=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return t!==null?t.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>this.ParseString("//")===null?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(this.ParseString("/*")===null)return null;let t=this.lineIndex,e=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),e!=null?`
|
|
14
|
+
`.repeat(this.lineIndex-t):null};}PreProcessInputString(t){return t}};Vi.CommentEliminator=ra;});var ki=b(Fi=>{Object.defineProperty(Fi,"__esModule",{value:true});Fi.Conditional=void 0;var Td=H(),Bl=it(),Pd=G(),sa=class extends Pd.ParsedObject{constructor(t,e){super(),this.initialCondition=t,this.branches=e,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new Td.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(Bl.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Bl.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(t){let e=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=e;}super.ResolveReferences(t);}};Fi.Conditional=sa;});var Zt=b(Ri=>{Object.defineProperty(Ri,"__esModule",{value:true});Ri.Text=void 0;var Od=G(),Nd=$(),aa=class extends Od.ParsedObject{constructor(t){super(),this.text=t,this.GenerateRuntimeObject=()=>new Nd.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Ri.Text=aa;});var Di=b(Li=>{Object.defineProperty(Li,"__esModule",{value:true});Li.ConstantDeclaration=void 0;var Ad=G(),Id=Ut(),oa=class extends Ad.ParsedObject{get constantName(){var t;return (t=this.constantIdentifier)===null||t===void 0?void 0:t.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(t,e){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=t,e&&(this._expression=this.AddContent(e));}get typeName(){return "CONST"}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.constantIdentifier,Id.SymbolType.Var);}};Li.ConstantDeclaration=oa;});var Re=b(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.FlowLevel=void 0;var Gl;(function(r){r[r.Story=0]="Story",r[r.Knot=1]="Knot",r[r.Stitch=2]="Stitch",r[r.WeavePoint=3]="WeavePoint";})(Gl||(Wi.FlowLevel=Gl={}));});var Cn=b(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.Gather=void 0;var Vd=H(),Fd=G(),kd=Ut(),la=class extends Fd.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(t,e){super(),this.indentationDepth=e,this.GenerateRuntimeObject=()=>{let n=new Vd.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let i of this.content)n.AddContent(i.runtimeObject);return n},this.toString=()=>{var n,i;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},t&&(this.identifier=t);}get typeName(){return "Gather"}ResolveReferences(t){super.ResolveReferences(t),this.identifier&&(this.identifier.name||"").length>0&&t.CheckForNamingCollisions(this,this.identifier,kd.SymbolType.SubFlowAndWeave);}};ji.Gather=la;});var ge=b(Mi=>{Object.defineProperty(Mi,"__esModule",{value:true});Mi.Path=void 0;var qi=D(),$l=qt(),Le=Re(),Rd=me(),ua=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Le.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(t=>t.name).filter(qi.filterUndef).join(".")),this._dotSeparatedComponents}constructor(t,e){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Le.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(n);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=n=>{let i=this.firstComponent,a=n;for(;a;){let s=a===n,o=this.GetChildFromContext(a,i,null,s);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<this.components.length;++a){let s=this.components[a].name,o,l=(0, qi.asOrNull)(i,$l.FlowBase);if(l!==null?o=l.flowLevel+1:o=Le.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,s,o),i===null)break}return i},this.GetChildFromContext=(n,i,a,s=false)=>{let o=a===null,l=(0, qi.asOrNull)(n,Rd.Weave);if(i&&l!==null&&(o||a===Le.FlowLevel.WeavePoint))return l.WeavePointNamed(i);let u=(0, qi.asOrNull)(n,$l.FlowBase);if(i&&u!==null){let h=s||u.flowLevel===Le.FlowLevel.Knot;return u.ContentWithNameAtLevel(i,a,h)}return null},Object.values(Le.FlowLevel).includes(t)?(this._baseTargetLevel=t,this.components=e||[]):Array.isArray(t)?(this._baseTargetLevel=null,this.components=t||[]):(this._baseTargetLevel=null,this.components=[t]);}get typeName(){return "Path"}};Mi.Path=ua;});var da=b(Bi=>{Object.defineProperty(Bi,"__esModule",{value:true});Bi.ReturnType=void 0;var Ld=G(),Dd=H(),ha=it(),Wd=de(),ca=class extends Ld.ParsedObject{constructor(t=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let e=new Dd.Container;return this.returnedExpression?e.AddContent(this.returnedExpression.runtimeObject):(e.AddContent(ha.ControlCommand.EvalStart()),e.AddContent(new Wd.Void),e.AddContent(ha.ControlCommand.EvalEnd())),e.AddContent(ha.ControlCommand.PopFunction()),e},t&&(this.returnedExpression=this.AddContent(t));}get typeName(){return "ReturnType"}};Bi.ReturnType=ca;});var vn=b(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.ClosestFlowBase=void 0;function jd(r){let t=r.parent;for(;t;){if(t.hasOwnProperty("iamFlowbase")&&t.iamFlowbase())return t;t=t.parent;}return null}Gi.ClosestFlowBase=jd;});var Ji=b($i=>{Object.defineProperty($i,"__esModule",{value:true});$i.Identifier=void 0;var fa=class r{constructor(t){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=t;}get typeName(){return "Identifier"}static Done(){return new r("DONE")}};$i.Identifier=fa;});var qt=b(Ui=>{Object.defineProperty(Ui,"__esModule",{value:true});Ui.FlowBase=void 0;var qd=ke(),pa=We(),Md=De(),Mt=Re(),Bd=Cn(),Gd=G(),$d=ge(),Jd=da(),Ud=H(),Hd=jt(),Kd=Yt(),ga=Ut(),zd=me(),Xd=vn(),Yd=Ji(),Jl=D(),ma=class r extends Gd.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e=null,n=null,i=false,a=false){super(),this.isFunction=i,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(s,o)=>{var l,u;let h=[],c=[];this._subFlowsByName=new Map;for(let p of s){let g=(0, Jl.asOrNull)(p,r);g?(this._firstChildFlow===null&&(this._firstChildFlow=g),c.push(p),!((l=g.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=g.identifier)===null||u===void 0?void 0:u.name,g)):h.push(p);}o&&h.push(new Bd.Gather(null,1),new pa.Divert(new $d.Path(Yd.Identifier.Done())));let f=[];return h.length>0&&(this._rootWeave=new zd.Weave(h,0),f.push(this._rootWeave)),c.length>0&&f.push(...c),f},this.ResolveVariableWithName=(s,o)=>{var l;let u={},h=o===null?this:(0, Xd.ClosestFlowBase)(o);if(h){if(h.args!==null){for(let c of h.args)if(((l=c.identifier)===null||l===void 0?void 0:l.name)===s)return u.found=true,u.isArgument=true,u.ownerFlow=h,u}if(h!==this.story&&h.variableDeclarations.has(s))return u.found=true,u.ownerFlow=h,u.isTemporary=true,u}return this.story.variableDeclarations.has(s)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let l=this.variableDeclarations.get(o),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${u}`,s,false);return}this.variableDeclarations.set(s.variableName,s);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,s]of this._subFlowsByName)s.hasOwnProperty("ResolveWeavePointNaming")&&s.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var s;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===Mt.FlowLevel.Knot||this.flowLevel===Mt.FlowLevel.Stitch)&&(o=this.Find(Jd.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 Ud.Container;l.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(l.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(l);let u=0;for(;this.content!==null&&u<this.content.length;){let h=this.content[u];if(h instanceof r){let c=h,f=c.runtimeObject;u===0&&!c.hasParameters&&this.flowLevel===Mt.FlowLevel.Knot&&(this._startingSubFlowDivert=new Hd.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let p=f,g=l.namedContent.get(p.name)||null;if(g){let y=`${this.GetType()} already contains flow named '${p.name}' (at ${g.debugMetadata})`;this.Error(y,c);}l.AddToNamedContentOnly(p);}else h&&l.AddContent(h.runtimeObject);u+=1;}return this.flowLevel!==Mt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let l=this.args.length-1;l>=0;--l){let u=((o=this.args[l].identifier)===null||o===void 0?void 0:o.name)||null,h=new Kd.VariableAssignment(u,true);s.AddContent(h);}},this.ContentWithNameAtLevel=(s,o=null,l=false)=>{var u;if((o===this.flowLevel||o===null)&&s===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===Mt.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(s),c))return c;if(o===Mt.FlowLevel.WeavePoint)return l?this.DeepSearchForAnyLevelContent(s):null}if(o!==null&&o<this.flowLevel)return null;let h=this._subFlowsByName.get(s)||null;return h&&(o===null||o===h.flowLevel)?h:l?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,Mt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(s,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==Mt.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[l,u]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${l}' within the function '${this.identifier}'`,u);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(pa.Divert)();for(let l of s)!l.isFunctionCall&&!(l.parent instanceof Md.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(qd.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},this.WarningInTermination=s=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";s.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let l=(0, Jl.asOrNull)(s,pa.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=t,this.args=n,e===null&&(e=[]),this.PreProcessTopLevelObjects(e),e=this.SplitWeaveAndSubFlowContent(e,this.GetType()=="Story"&&!a),this.AddContent(e);}PreProcessTopLevelObjects(t){}ResolveReferences(t){var e,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(t),this.args!==null){for(let i of this.args)t.CheckForNamingCollisions(this,i.identifier,ga.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((e=this.args[i].identifier)===null||e===void 0?void 0:e.name)==((n=this.args[a].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==Mt.FlowLevel.Story){let i=this.flowLevel===Mt.FlowLevel.Knot?ga.SymbolType.Knot:ga.SymbolType.SubFlowAndWeave;t.CheckForNamingCollisions(this,this.identifier,i);}}};Ui.FlowBase=ma;});var Ki=b(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.ContentList=void 0;var Qd=H(),Zd=G(),tf=Zt(),ef=D(),Ca=class extends Zd.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(t,...e){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let i=(0, ef.asOrNull)(this.content[n],tf.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 Qd.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,t&&this.AddContent(t),e&&this.AddContent(e);}get typeName(){return "ContentList"}};Hi.ContentList=Ca;});var je=b(zi=>{Object.defineProperty(zi,"__esModule",{value:true});zi.VariableReference=void 0;var nf=ft(),rf=dt(),va=class extends nf.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(t){t===null?this.pathForCount=null:this.pathForCount=new rf.Path(t);}constructor(t=null){super(),this.pathForCount=null,this.name=t;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};zi.VariableReference=va;});var qe=b(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.VariableReference=void 0;var sf=Ki(),af=xt(),Ul=qt(),of=ge(),lf=je(),uf=me(),hf=Ji(),Hl=D(),ya=class extends af.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(t=>t.name).filter(Hl.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let t=this.path.join(".");return new hf.Identifier(t)}get runtimeVarRef(){return this._runtimeVarRef}constructor(t){super(),this.pathIdentifiers=t,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=e=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(e),this.isConstantReference=true;return}if(this._runtimeVarRef=new lf.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",a="";this.path.length===1?i=this.path[0]:(a=this.path[0],i=this.path[1]),this.story.ResolveListItem(a,i,this)&&(this.isListItemReference=true);}e.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(t){if(super.ResolveReferences(t),this.isConstantReference||this.isListItemReference)return;let e=new of.Path(this.pathIdentifiers),n=e.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let i=(0, Hl.asOrNull)(n,Ul.FlowBase);i&&i.isFunction&&(this.parent instanceof uf.Weave||this.parent instanceof sf.ContentList||this.parent instanceof Ul.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${e}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}t.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};Xi.VariableReference=ya;});var yn=b(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.FunctionCall=void 0;var Bt=it(),cf=We(),df=De(),ff=xt(),pf=gt(),gf=$(),Qi=Wt(),Kl=pi(),mf=ge(),Cf=$(),vf=qe(),Yi=D(),Zi=class r extends ff.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(t,e){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=n=>{let i=this.story.ResolveList(this.name),a=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),n.AddContent(Bt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(Bt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, Yi.asOrNull)(this.args[0],df.DivertTarget),o=(0, Yi.asOrNull)(this.args[0],vf.VariableReference);if(this.args.length!==1||s===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}s?(this._divertTargetToCount=s,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(Bt.ControlCommand.TurnsSince()):n.AddContent(Bt.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let s=0;s<this.args.length;s+=1){let o=(0, Yi.asOrNull)(this.args[s],Kl.NumberExpression);if(o&&!o.isInt()){let l=s===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[s].GenerateIntoContainer(n);}n.AddContent(Bt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, Yi.asOrNull)(this.args[0],Kl.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let s=0;s<this.args.length;s+=1)this.args[s].GenerateIntoContainer(n);n.AddContent(Bt.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.ListRandom());else if(Qi.NativeFunctionCall.CallExistsWithName(this.name)){let s=Qi.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${r.name} should take ${s.numberOfParameters} parameter`;s.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(n);n.AddContent(Qi.NativeFunctionCall.CallWithName(this.name));}else if(i!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)n.AddContent(new Cf.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(Bt.ControlCommand.ListFromInt());else {let s=new pf.InkList;s.SetInitialOriginName(this.name),n.AddContent(new gf.ListValue(s));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(Bt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new cf.Divert(new mf.Path(t),e),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(t){if(super.ResolveReferences(t),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let e of this.args)e.ResolveReferences(t);if(this._divertTargetToCount){let e=this._divertTargetToCount.divert,n=e.runtimeDivert.variableDivertName!=null;if(n){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${e.runtimeDivert.variableDivertName})`);return}let i=e.targetContent;if(i===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${e.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let e=this._variableReferenceToCount.runtimeVarRef;if(!e)throw new Error;e.pathForCount!==null&&this.Error(`Should be '${r.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};tr.FunctionCall=Zi;Zi.IsBuiltIn=r=>Qi.NativeFunctionCall.CallExistsWithName(r)?true:r==="CHOICE_COUNT"||r==="TURNS_SINCE"||r==="TURNS"||r==="RANDOM"||r==="SEED_RANDOM"||r==="LIST_VALUE"||r==="LIST_RANDOM"||r==="READ_COUNT";});var ba=b(er=>{Object.defineProperty(er,"__esModule",{value:true});er.MultipleConditionExpression=void 0;var yf=xt(),Sf=Wt(),Sa=class extends yf.Expression{get subExpressions(){return this.content}constructor(t){super(),this.GenerateIntoContainer=e=>{let n=true;for(let i of this.subExpressions)i.GenerateIntoContainer(e),n||e.AddContent(Sf.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(t);}get typeName(){return "MultipleConditionExpression"}};er.MultipleConditionExpression=Sa;});var De=b(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.DivertTarget=void 0;var bf=Js(),_f=ke(),Ef=ki(),wf=xa(),xf=$(),_a=xt(),Tf=qt(),zl=yn(),Pf=ba(),Xl=qe(),Ea=D(),wa=class r extends _a.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(t){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=e=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new xf.DivertTargetValue,e.AddContent(this.runtimeDivertTargetValue);},this.Equals=e=>{let n=(0, Ea.asOrNull)(e,r);if(!n||!this.divert.target||!n.divert.target)return false;let i=this.divert.target.dotSeparatedComponents,a=n.divert.target.dotSeparatedComponents;return i===a},this.divert=this.AddContent(t);}get typeName(){return "DivertTarget"}ResolveReferences(t){if(super.ResolveReferences(t),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let e=this;for(;e&&e instanceof _a.Expression;){let i=false,a=false,s=e.parent;if(s instanceof bf.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof r||o.leftExpression instanceof Xl.VariableReference)&&(o.rightExpression instanceof r||o.rightExpression instanceof Xl.VariableReference)||(i=true),a=true;}else if(s instanceof zl.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof _a.Expression||s instanceof Pf.MultipleConditionExpression||s instanceof _f.Choice&&s.condition===e||s instanceof Ef.Conditional||s instanceof wf.ConditionalSingleBranch)&&(i=true,a=true);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;e=s;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let n=this.divert.targetContent;if(n!==null){let i=n.containerForCounting;if(i!==null){let s=(0, Ea.asOrNull)(this.parent,zl.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, Ea.asOrNull)(n,Tf.FlowBase);if(a!=null&&a.args!==null)for(let s of a.args)s.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${s.identifier}').`);}}};nr.DivertTarget=wa;});var We=b(ir=>{Object.defineProperty(ir,"__esModule",{value:true});ir.Divert=void 0;var Of=H(),Sn=it(),Nf=jt(),Ta=De(),Pa=qt(),Af=yn(),If=G(),Yl=ge(),Vf=dt(),Ql=fe(),Ff=$(),Zl=qe(),kf=vn(),bn=D(),Oa=class extends If.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(t){this._runtimeDivert=t;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(t,e){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return Sn.ControlCommand.End();if(this.isDone)return Sn.ControlCommand.Done();this.runtimeDivert=new Nf.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 Of.Container;if(n){this.isFunctionCall||i.AddContent(Sn.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let s=0;s<this.args.length;++s){let o=this.args[s],l=null;if(a&&s<a.length&&(l=a[s]),l&&l.isByReference){let u=(0, bn.asOrNull)(o,Zl.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let h=new Yl.Path(u.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let f=new Ff.VariablePointerValue(u.name);i.AddContent(f);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Sn.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Sn.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Ql.PushPopType.Function:Ql.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let i=(0, bn.asOrNull)((0, kf.ClosestFlowBase)(this),Pa.FlowBase);if(i){let a=i.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});s&&!s.isDivertTarget&&this.Error(`Since '${s.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${s.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let i=(0, bn.asOrNull)(this.targetContent,Pa.FlowBase);if(n===0&&(i===null||!i.hasParameters))return;if(i===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&n>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof Ta.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==n){let s;n===0?s="but there weren't any passed to it":n<a?s=`but only got ${n}`:s=`but got ${n}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=i.args[s],l=this.args[s];if(o.isDivertTarget){let u=(0, bn.asOrNull)(l,Zl.VariableReference);if(!(l instanceof Ta.DivertTarget)&&u===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${l}`,l);else if(u){let h=new Yl.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 s=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==s&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${s} but got ${o}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},t&&(this.target=t),e&&(this.args=e,this.AddContent(e));}get typeName(){return "Divert"}ResolveReferences(t){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(t);let e=(0, bn.asOrNull)(this.targetContent,Pa.FlowBase);e&&(!e.isFunction&&this.isFunctionCall?super.Error(`${e.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${e.identifier} =='?`):e.isFunction&&!this.isFunctionCall&&!(this.parent instanceof Ta.DivertTarget)&&super.Error(e.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+e.identifier+"(...)'"));let n=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=Af.FunctionCall.IsBuiltIn(this.target.firstComponent),a=t.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new Vf.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(t));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(t,e=null,n=false){if(e!==this&&e){super.Error(t,e);return}this.isFunctionCall?super.Error(`Function call ${t}`,e,n):super.Error(`Divert ${t}`,e,n);}};ir.Divert=Oa;});var tu=b(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.GatherPointToResolve=void 0;var Na=class{constructor(t,e){this.divert=t,this.targetRuntimeObj=e;}};rr.GatherPointToResolve=Na;});var eu=b(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.SequenceDivertToResolve=void 0;var Aa=class{constructor(t,e){this.divert=t,this.targetContent=e;}};sr.SequenceDivertToResolve=Aa;});var Ia=b(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.SequenceType=void 0;var nu;(function(r){r[r.Stopping=1]="Stopping",r[r.Cycle=2]="Cycle",r[r.Shuffle=4]="Shuffle",r[r.Once=8]="Once";})(nu||(ar.SequenceType=nu={}));});var ka=b(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.Sequence=void 0;var iu=H(),Vt=it(),Va=jt(),_n=$(),or=Wt(),Rf=G(),Lf=eu(),lr=Ia(),Df=me(),Fa=class extends Rf.ParsedObject{constructor(t,e){super(),this.sequenceType=e,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new iu.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(Vt.ControlCommand.EvalStart()),n.AddContent(Vt.ControlCommand.VisitIndex());let i=(this.sequenceType&lr.SequenceType.Once)>0,a=(this.sequenceType&lr.SequenceType.Cycle)>0,s=(this.sequenceType&lr.SequenceType.Stopping)>0,o=(this.sequenceType&lr.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(i&&(l+=1),s||i?(n.AddContent(new _n.IntValue(l-1)),n.AddContent(or.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new _n.IntValue(this.sequenceElements.length)),n.AddContent(or.NativeFunctionCall.CallWithName("%"))),o){let h=Vt.ControlCommand.NoOp();if(i||s){let f=s?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(Vt.ControlCommand.Duplicate()),n.AddContent(new _n.IntValue(f)),n.AddContent(or.NativeFunctionCall.CallWithName("=="));let p=new Va.Divert;p.isConditional=true,n.AddContent(p),this.AddDivertToResolve(p,h);}let c=this.sequenceElements.length;s&&(c-=1),n.AddContent(new _n.IntValue(c)),n.AddContent(Vt.ControlCommand.SequenceShuffleIndex()),(i||s)&&n.AddContent(h);}n.AddContent(Vt.ControlCommand.EvalEnd());let u=Vt.ControlCommand.NoOp();for(let h=0;h<l;h+=1){n.AddContent(Vt.ControlCommand.EvalStart()),n.AddContent(Vt.ControlCommand.Duplicate()),n.AddContent(new _n.IntValue(h)),n.AddContent(or.NativeFunctionCall.CallWithName("==")),n.AddContent(Vt.ControlCommand.EvalEnd());let c=new Va.Divert;c.isConditional=true,n.AddContent(c);let f;h<this.sequenceElements.length?f=this.sequenceElements[h].runtimeObject:f=new iu.Container,f.name=`s${h}`,f.InsertContent(Vt.ControlCommand.PopEvaluatedValue(),0);let p=new Va.Divert;f.AddContent(p),n.AddToNamedContentOnly(f),this.AddDivertToResolve(c,f),this.AddDivertToResolve(p,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new Lf.SequenceDivertToResolve(n,i));},this.sequenceType=e,this.sequenceElements=[];for(let n of t){let i=n.content,a=null;i===null||i.length===0?a=n:a=new Df.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(t){super.ResolveReferences(t);for(let e of this._sequenceDivertsToResolve)e.divert.targetPath=e.targetContent.path;}};ur.Sequence=Fa;});var La=b(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.TunnelOnwards=void 0;var Wf=H(),En=it(),jf=jt(),qf=$(),Mf=G(),Bf=de(),Gf=D(),$f=je(),Ra=class extends Mf.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let t=new Wf.Container;if(t.AddContent(En.ControlCommand.EvalStart()),this.divertAfter){let e=this.divertAfter.GenerateRuntimeObject(),n=e;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(s==-1&&u.commandType===En.ControlCommand.CommandType.EvalStart?s=l:u.commandType===En.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=s+1;l<o;l+=1){let u=n.content[l];u.parent=null,t.AddContent(n.content[l]);}}}let i=(0, Gf.asOrNull)(e,jf.Divert);if(i!=null&&i.hasVariableTarget){let a=new $f.VariableReference(i.variableDivertName);t.AddContent(a);}else this._overrideDivertTarget=new qf.DivertTargetValue,t.AddContent(this._overrideDivertTarget);}else t.AddContent(new Bf.Void);return t.AddContent(En.ControlCommand.EvalEnd()),t.AddContent(En.ControlCommand.PopTunnel()),t},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(t){this._divertAfter=t,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(t){super.ResolveReferences(t),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};hr.TunnelOnwards=Ra;});var ja=b(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.ListDefinition=void 0;var Da=gt(),Wa=class{constructor(t,e){this._name=t||"",this._items=null,this._itemNameToValues=e||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[t,e]of this._itemNameToValues){let n=new Da.InkListItem(this.name,t);this._items.set(n.serialized(),e);}}return this._items}ValueForItem(t){if(!t.itemName)return 0;let e=this._itemNameToValues.get(t.itemName);return typeof e<"u"?e:0}ContainsItem(t){return !t.itemName||t.originName!=this.name?false:this._itemNameToValues.has(t.itemName)}ContainsItemWithName(t){return this._itemNameToValues.has(t)}TryGetItemWithValue(t,e){for(let[n,i]of this._itemNameToValues)if(i==t)return e=new Da.InkListItem(this.name,n),{result:e,exists:true};return e=Da.InkListItem.Null,{result:e,exists:false}}TryGetValueForItem(t,e){if(!t.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(t.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};cr.ListDefinition=Wa;});var fr=b(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.ListDefinition=void 0;var Jf=gt(),Uf=gt(),Hf=ja(),Kf=$(),zf=G(),Xf=Ut(),qa=class extends zf.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var t;let e=new Map;for(let n of this.itemDefinitions)e.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):e.set(n.name,n.seriesValue);return new Hf.ListDefinition(((t=this.identifier)===null||t===void 0?void 0:t.name)||"",e)}constructor(t){super(),this.itemDefinitions=t,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,i;let a=new Jf.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new Uf.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new Kf.ListValue(a)};let e=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(e=n.explicitValue),n.seriesValue=e,e+=1;this.AddContent(t);}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.identifier,Xf.SymbolType.List);}};dr.ListDefinition=qa;});var Ba=b(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.VariableAssignment=void 0;var Yf=H(),Qf=vn(),Zf=fr(),tp=G(),ru=Ut(),ep=Yt(),np=qe(),ip=D(),Ma=class extends tp.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:t,isGlobalDeclaration:e,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, Qf.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new Yf.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new ep.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=!!e,this.isNewTemporaryDeclaration=!!n,i instanceof Zf.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):t&&(this.expression=this.AddContent(t));}ResolveReferences(t){if(super.ResolveReferences(t),this.isDeclaration&&this.listDefinition===null&&t.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?ru.SymbolType.Var:ru.SymbolType.Temp),this.isGlobalDeclaration){let e=(0, ip.asOrNull)(this.expression,np.VariableReference);e&&!e.isConstantReference&&!e.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let e=t.ResolveVariableWithName(this.variableName,this);e.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=e.isGlobal);}}};pr.VariableAssignment=Ma;});var me=b(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.Weave=void 0;var su=Qn(),Pt=ke(),gr=ki(),rp=Di(),sp=H(),mr=We(),ap=jt(),op=De(),lp=qt(),Gt=Cn(),up=tu(),hp=G(),Ga=ka(),cp=Zt(),dp=La(),fp=Ba(),Ot=D(),$a=class r extends hp.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let t=null;for(let n=this.content.length-1;n>=0;--n){t=this.content[n];let i=(0, Ot.asOrNull)(t,cp.Text);if(!(i&&i.text===`
|
|
15
|
+
`)&&!this.IsGlobalDeclaration(t))break}let e=(0, Ot.asOrNull)(t,r);return e&&(t=e.lastParsedSignificantObject),t}constructor(t,e=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var n,i,a;let s=[...this.FindAll(Gt.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(Pt.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof Gt.Gather?"gather":"choice",h=l;this.Error(`A ${u} with the same label name '${o.name}' already exists in this context on line ${h.debugMetadata?h.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((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(;n<this.content.length;){let i=this.content[n];if(i instanceof Pt.Choice||i instanceof Gt.Gather){let s=i.indentationDepth-1;if(s>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let c=(0, Ot.asOrNull)(this.content[n],Pt.Choice)||(0, Ot.asOrNull)(this.content[n],Gt.Gather);if(c!==null&&c.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let l=n-o,u=this.content.slice(o,o+l);this.content.splice(o,l);let h=new r(u,s);this.InsertContent(o,h),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let i of n)if(i instanceof Pt.Choice||i instanceof Gt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new sp.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof Pt.Choice||n instanceof Gt.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof r){let i=n;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let s of this.looseEnds){let o=s;if(o instanceof Gt.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof mr.Divert)l=o.runtimeObject;else {l=new ap.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new up.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof Gt.Gather)this.AddRuntimeForGather(n);else if(n instanceof Pt.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Gt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=n;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, Ot.asOrNull)(n,Pt.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=n;},this.AddRuntimeForNestedWeave=n=>{this.AddGeneralRuntimeContent(n.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=n=>{if(n!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(n);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let n=null,i=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, Ot.asOrNull)(s,r);o&&(!a&&n===null&&(n=o),a&&i===null&&(i=o)),(s instanceof Ga.Sequence||s instanceof gr.Conditional)&&(a=true);}if(!(n===null&&i===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],l=false;if(a){if(o instanceof Pt.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof Pt.Choice)){let u=n||i;u!==null&&(u.ReceiveLooseEnd(o),l=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(o),l=true;l&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(n);return i||null},this.IsGlobalDeclaration=n=>{let i=(0, Ot.asOrNull)(n,fp.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, Ot.asOrNull)(n,rp.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 s=(0, Ot.asOrNull)(a.parent,r);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let l=o+1;l<s.content.length;l+=1){let u=s.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof Pt.Choice||u instanceof Gt.Gather||u instanceof r)break;i.push(u);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof su.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let s=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(s,a,n);}else {for(let a of this.content)if(a instanceof Pt.Choice||a instanceof mr.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let i=null;for(let s=n.parent;s!==null;s=s.parent)if(s instanceof Ga.Sequence||s instanceof gr.Conditional){i=(0, Ot.asOrNull)(s,gr.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(Pt.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 s=false,o=i;for(let l of n){if(l.Find(mr.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof op.DivertTarget))!==null&&(s=true),l.Find(dp.TunnelOnwards)()!=null){s=true;break}o=l;}if(!s){if(o instanceof su.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return true;for(let i=n.content.length-1;i>=0;--i){let a=(0, Ot.asOrNull)(n.content[i],mr.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let i of this.ancestry){let a=(0, Ot.asOrNull)(i,lp.FlowBase);if(a)n.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let s of n){let o=s.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);}}},e==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(t):this.baseIndentIndex=e,this.AddContent(t),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(t){if(super.ResolveReferences(t),this.looseEnds!==null&&this.looseEnds.length>0){let e=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof Ga.Sequence||n instanceof gr.Conditional){e=true;break}e&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let e of this.gatherPointsToResolve)e.divert.targetPath=e.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};Cr.Weave=$a;});var xa=b(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.ConditionalSingleBranch=void 0;var au=H(),vr=it(),ou=jt(),pp=G(),gp=Wt(),mp=$(),Cp=Zt(),vp=me(),yp=D(),Ja=class extends pp.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(t){this._ownExpression=t,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(t){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let a=(0, yp.asOrNull)(i,Cp.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let e=new au.Container,n=this.matchingEquality&&!this.isElse;if(n&&e.AddContent(vr.ControlCommand.Duplicate()),this._conditionalDivert=new ou.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&e.AddContent(vr.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(e),this.matchingEquality&&e.AddContent(gp.NativeFunctionCall.CallWithName("==")),i&&e.AddContent(vr.ControlCommand.EvalEnd());}return e.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new mp.StringValue(`
|
|
16
|
+
`),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(vr.ControlCommand.PopEvaluatedValue(),0),e.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new ou.Divert,this._contentContainer.AddContent(this.returnDivert),e},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new au.Container:this._innerWeave.rootContainer,t&&(this._innerWeave=new vp.Weave(t),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(t){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(t);}};yr.ConditionalSingleBranch=Ja;});var uu=b(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.CustomFlags=void 0;var lu;(function(r){r[r.ParsingString=1]="ParsingString",r[r.TagActive=2]="TagActive";})(lu||(Sr.CustomFlags=lu={}));});var hu=b(br=>{Object.defineProperty(br,"__esModule",{value:true});br.DebugMetadata=void 0;var Ua=class r{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(t){let e=new r;return e.fileName=this.fileName,e.sourceName=this.sourceName,this.startLineNumber<t.startLineNumber?(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>t.startLineNumber?(e.startLineNumber=t.startLineNumber,e.startCharacterNumber=t.startCharacterNumber):(e.startLineNumber=this.startLineNumber,e.startCharacterNumber=Math.min(this.startCharacterNumber,t.startCharacterNumber)),this.endLineNumber>t.endLineNumber?(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<t.endLineNumber?(e.endLineNumber=t.endLineNumber,e.endCharacterNumber=t.endCharacterNumber):(e.endLineNumber=this.endLineNumber,e.endCharacterNumber=Math.max(this.endCharacterNumber,t.endCharacterNumber)),e}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};br.DebugMetadata=Ua;});var cu=b(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.ExternalDeclaration=void 0;var Sp=G(),Ha=class extends Sp.ParsedObject{get name(){var t;return ((t=this.identifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e){super(),this.identifier=t,this.argumentNames=e,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var t;return `EXTERNAL ${(t=this.identifier)===null||t===void 0?void 0:t.name}`}};_r.ExternalDeclaration=Ha;});var du=b(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.FlowDecl=void 0;var Ka=class{constructor(t,e,n){this.name=t,this.args=e,this.isFunction=n;}};Er.FlowDecl=Ka;});var Xa=b(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.Wrap=void 0;var bp=G(),za=class extends bp.ParsedObject{constructor(t){super(),this._objToWrap=t,this.GenerateRuntimeObject=()=>this._objToWrap;}};wr.Wrap=za;});var fu=b(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.Glue=void 0;var _p=Xa(),Ya=class extends _p.Wrap{constructor(t){super(t);}get typeName(){return "Glue"}};xr.Glue=Ya;});var Pr=b(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.Glue=void 0;var Ep=ft(),Qa=class extends Ep.InkObject{toString(){return "Glue"}};Tr.Glue=Qa;});var gu=b(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.IncDecExpression=void 0;var wp=Ki(),pu=xt(),xp=qt(),Tp=Wt(),Pp=$(),Op=Yt(),Np=je(),Ap=me(),Za=class extends pu.Expression{constructor(t,e,n){super(),this.varIdentifier=t,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new Np.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new Pp.IntValue(1)),i.AddContent(Tp.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new Op.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,a;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},e instanceof pu.Expression?(this.expression=e,this.AddContent(this.expression),this.isInc=!!n):this.isInc=e;}get typeName(){return "IncDecExpression"}ResolveReferences(t){var e;super.ResolveReferences(t);let n=t.ResolveVariableWithName(((e=this.varIdentifier)===null||e===void 0?void 0:e.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof Ap.Weave)&&!(this.parent instanceof xp.FlowBase)&&!(this.parent instanceof wp.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Or.IncDecExpression=Za;});var eo=b(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.IncludedFile=void 0;var Ip=G(),to=class extends Ip.ParsedObject{constructor(t){super(),this.includedStory=t,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Nr.IncludedFile=to;});var mu=b(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.InfixOperator=void 0;var no=class{constructor(t,e,n){this.type=t,this.precedence=e,this.requireWhitespace=n,this.toString=()=>this.type;}};Ar.InfixOperator=no;});var ro=b(Ir=>{Object.defineProperty(Ir,"__esModule",{value:true});Ir.Knot=void 0;var Vp=qt(),Cu=Re(),io=class extends Vp.FlowBase{get flowLevel(){return Cu.FlowLevel.Knot}constructor(t,e,n,i){super(t,e,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(t){super.ResolveReferences(t);let e=this.story;for(let n in this.subFlowsByName){let i=e.ContentWithNameAtLevel(n,Cu.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(n),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(s,a);}}}};Ir.Knot=io;});var vu=b(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.List=void 0;var Fp=xt(),kp=gt(),Rp=gt(),Lp=$(),so=class extends Fp.Expression{constructor(t){super(),this.itemIdentifierList=t,this.GenerateIntoContainer=e=>{var n,i;let a=new kp.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((n=s?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";o.length>1?(l=o[0],u=o[1]):u=o[0];let h=this.story.ResolveListItem(l,u,this);if(h===null)l===null?this.Error(`Could not find list definition that contains item '${s}'`):this.Error(`Could not find list item ${s}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${s}`);return}l||(l=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new Rp.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(c,h.seriesValue);}}e.AddContent(new Lp.ListValue(a));};}get typeName(){return "List"}};Vr.List=so;});var oo=b(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.ListElementDefinition=void 0;var Dp=G(),Wp=Ut(),ao=class extends Dp.ParsedObject{get fullName(){var t;let e=this.parent;if(e===null)throw new Error("Can't get full name without a parent list.");return `${(t=e.identifier)===null||t===void 0?void 0:t.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var t;return ((t=this.indentifier)===null||t===void 0?void 0:t.name)||null}constructor(t,e,n=null){super(),this.indentifier=t,this.inInitialList=e,this.explicitValue=n,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(t){super.ResolveReferences(t),t.CheckForNamingCollisions(this,this.indentifier,Wp.SymbolType.ListItem);}};Fr.ListElementDefinition=ao;});var lo=b(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.StatementLevel=void 0;var yu;(function(r){r[r.InnerBlock=0]="InnerBlock",r[r.Stitch=1]="Stitch",r[r.Knot=2]="Knot",r[r.Top=3]="Top";})(yu||(kr.StatementLevel=yu={}));});var ho=b(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.Stitch=void 0;var jp=qt(),qp=Re(),uo=class extends jp.FlowBase{get flowLevel(){return qp.FlowLevel.Stitch}constructor(t,e,n,i){super(t,e,n,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};Rr.Stitch=uo;});var Dr=b(Lr=>{Object.defineProperty(Lr,"__esModule",{value:true});Lr.Tag=void 0;var Mp=ft(),co=class extends Mp.InkObject{constructor(t){super(),this.text=t.toString()||"";}toString(){return "# "+this.text}};Lr.Tag=co;});var po=b(Wr=>{Object.defineProperty(Wr,"__esModule",{value:true});Wr.Choice=void 0;var Bp=dt(),Gp=nt(),$p=ft(),fo=class r extends $p.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, Gp.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(t){this.targetPath=new Bp.Path(t);}Clone(){let t=new r;return t.text=this.text,t.sourcePath=this.sourcePath,t.index=this.index,t.targetPath=this.targetPath,t.originalThreadIndex=this.originalThreadIndex,t.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(t.threadAtGeneration=this.threadAtGeneration.Copy()),t}};Wr.Choice=fo;});var mo=b(jr=>{Object.defineProperty(jr,"__esModule",{value:true});jr.ListDefinitionsOrigin=void 0;var Jp=gt(),Up=$(),Hp=nt(),go=class{constructor(t){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let e of t){this._lists.set(e.name,e);for(let[n,i]of e.items){let a=Jp.InkListItem.fromSerializedKey(n),s=new Up.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,s),this._allUnambiguousListValueCache.set(a.fullName,s);}}}get lists(){let t=[];for(let[,e]of this._lists)t.push(e);return t}TryListGetDefinition(t,e){if(t===null)return {result:e,exists:false};let n=this._lists.get(t);return n?{result:n,exists:true}:{result:e,exists:false}}FindSingleItemListWithName(t){if(t===null)return (0, Hp.throwNullException)("name");let e=this._allUnambiguousListValueCache.get(t);return typeof e<"u"?e:null}};jr.ListDefinitionsOrigin=go;});var Be=b(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.JsonSerialisation=void 0;var qr=H(),Ct=$(),Su=Pr(),k=it(),Me=fe(),bu=jt(),_u=Si(),Co=je(),Eu=Yt(),vo=Wt(),wu=de(),xu=Dr(),Kp=dt(),Tu=po(),zp=ja(),Xp=mo(),Mr=gt(),K=D(),Ce=nt(),Br=class r{static JArrayToRuntimeObjList(t,e=false){let n=t.length;e&&n--;let i=[];for(let a=0;a<n;a++){let s=t[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, Ce.throwNullException)("runtimeObj");i.push(o);}return i}static WriteDictionaryRuntimeObjs(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WritePropertyStart(n),this.WriteRuntimeObject(t,i),t.WritePropertyEnd();t.WriteObjectEnd();}static WriteListRuntimeObjs(t,e){t.WriteArrayStart();for(let n of e)this.WriteRuntimeObject(t,n);t.WriteArrayEnd();}static WriteIntDictionary(t,e){t.WriteObjectStart();for(let[n,i]of e)t.WriteIntProperty(n,i);t.WriteObjectEnd();}static WriteRuntimeObject(t,e){let n=(0, K.asOrNull)(e,qr.Container);if(n){this.WriteRuntimeContainer(t,n);return}let i=(0, K.asOrNull)(e,bu.Divert);if(i){let m="->";i.isExternal?m="x()":i.pushesToStack&&(i.stackPushType==Me.PushPopType.Function?m="f()":i.stackPushType==Me.PushPopType.Tunnel&&(m="->t->"));let E;i.hasVariableTarget?E=i.variableDivertName:E=i.targetPathString,t.WriteObjectStart(),t.WriteProperty(m,E),i.hasVariableTarget&&t.WriteProperty("var",true),i.isConditional&&t.WriteProperty("c",true),i.externalArgs>0&&t.WriteIntProperty("exArgs",i.externalArgs),t.WriteObjectEnd();return}let a=(0, K.asOrNull)(e,_u.ChoicePoint);if(a){t.WriteObjectStart(),t.WriteProperty("*",a.pathStringOnChoice),t.WriteIntProperty("flg",a.flags),t.WriteObjectEnd();return}let s=(0, K.asOrNull)(e,Ct.BoolValue);if(s){t.WriteBool(s.value);return}let o=(0, K.asOrNull)(e,Ct.IntValue);if(o){t.WriteInt(o.value);return}let l=(0, K.asOrNull)(e,Ct.FloatValue);if(l){t.WriteFloat(l.value);return}let u=(0, K.asOrNull)(e,Ct.StringValue);if(u){u.isNewline?t.Write(`
|
|
17
|
+
`,false):(t.WriteStringStart(),t.WriteStringInner("^"),t.WriteStringInner(u.value),t.WriteStringEnd());return}let h=(0, K.asOrNull)(e,Ct.ListValue);if(h){this.WriteInkList(t,h);return}let c=(0, K.asOrNull)(e,Ct.DivertTargetValue);if(c){if(t.WriteObjectStart(),c.value===null)return (0, Ce.throwNullException)("divTargetVal.value");t.WriteProperty("^->",c.value.componentsString),t.WriteObjectEnd();return}let f=(0, K.asOrNull)(e,Ct.VariablePointerValue);if(f){t.WriteObjectStart(),t.WriteProperty("^var",f.value),t.WriteIntProperty("ci",f.contextIndex),t.WriteObjectEnd();return}if((0, K.asOrNull)(e,Su.Glue)){t.Write("<>");return}let g=(0, K.asOrNull)(e,k.ControlCommand);if(g){t.Write(r._controlCommandNames[g.commandType]);return}let y=(0, K.asOrNull)(e,vo.NativeFunctionCall);if(y){let m=y.name;m=="^"&&(m="L^"),t.Write(m);return}let b=(0, K.asOrNull)(e,Co.VariableReference);if(b){t.WriteObjectStart();let m=b.pathStringForCount;m!=null?t.WriteProperty("CNT?",m):t.WriteProperty("VAR?",b.name),t.WriteObjectEnd();return}let _=(0, K.asOrNull)(e,Eu.VariableAssignment);if(_){t.WriteObjectStart();let m=_.isGlobal?"VAR=":"temp=";t.WriteProperty(m,_.variableName),_.isNewDeclaration||t.WriteProperty("re",true),t.WriteObjectEnd();return}if((0, K.asOrNull)(e,wu.Void)){t.Write("void");return}let S=(0, K.asOrNull)(e,xu.Tag);if(S){t.WriteObjectStart(),t.WriteProperty("#",S.text),t.WriteObjectEnd();return}let v=(0, K.asOrNull)(e,Tu.Choice);if(v){this.WriteChoice(t,v);return}throw new Error("Failed to convert runtime object to Json token: "+e)}static JObjectToDictionaryRuntimeObjs(t){let e=new Map;for(let n in t)if(t.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(t[n]);if(i===null)return (0, Ce.throwNullException)("inkObject");e.set(n,i);}return e}static JObjectToIntDictionary(t){let e=new Map;for(let n in t)t.hasOwnProperty(n)&&e.set(n,parseInt(t[n]));return e}static JTokenToRuntimeObject(t){if(typeof t=="number"&&!isNaN(t)||typeof t=="boolean")return Ct.Value.Create(t);if(typeof t=="string"){let e=t.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(e);if(n)return new Ct.FloatValue(parseFloat(n[0]));let i=e[0];if(i=="^")return new Ct.StringValue(e.substring(1));if(i==`
|
|
18
|
+
`&&e.length==1)return new Ct.StringValue(`
|
|
19
|
+
`);if(e=="<>")return new Su.Glue;for(let a=0;a<r._controlCommandNames.length;++a){let s=r._controlCommandNames[a];if(e==s)return new k.ControlCommand(a)}if(e=="L^"&&(e="^"),vo.NativeFunctionCall.CallExistsWithName(e))return vo.NativeFunctionCall.CallWithName(e);if(e=="->->")return k.ControlCommand.PopTunnel();if(e=="~ret")return k.ControlCommand.PopFunction();if(e=="void")return new wu.Void}if(typeof t=="object"&&!Array.isArray(t)){let e=t,n;if(e["^->"])return n=e["^->"],new Ct.DivertTargetValue(new Kp.Path(n.toString()));if(e["^var"]){n=e["^var"];let h=new Ct.VariablePointerValue(n.toString());return "ci"in e&&(n=e.ci,h.contextIndex=parseInt(n)),h}let i=false,a=false,s=Me.PushPopType.Function,o=false;if((n=e["->"])?i=true:(n=e["f()"])?(i=true,a=true,s=Me.PushPopType.Function):(n=e["->t->"])?(i=true,a=true,s=Me.PushPopType.Tunnel):(n=e["x()"])&&(i=true,o=true,a=false,s=Me.PushPopType.Function),i){let h=new bu.Divert;h.pushesToStack=a,h.stackPushType=s,h.isExternal=o;let c=n.toString();return (n=e.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!e.c,o&&(n=e.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=e["*"]){let h=new _u.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=e.flg)&&(h.flags=parseInt(n)),h}if(n=e["VAR?"])return new Co.VariableReference(n.toString());if(n=e["CNT?"]){let h=new Co.VariableReference;return h.pathStringForCount=n.toString(),h}let l=false,u=false;if((n=e["VAR="])?(l=true,u=true):(n=e["temp="])&&(l=true,u=false),l){let h=n.toString(),c=!e.re,f=new Eu.VariableAssignment(h,c);return f.isGlobal=u,f}if(e["#"]!==void 0)return n=e["#"],new xu.Tag(n.toString());if(n=e.list){let h=n,c=new Mr.InkList;if(n=e.origins){let f=n;c.SetInitialOriginNames(f);}for(let f in h)if(h.hasOwnProperty(f)){let p=h[f],g=new Mr.InkListItem(f),y=parseInt(p);c.Add(g,y);}return new Ct.ListValue(c)}if(e.originalChoicePath!=null)return this.JObjectToChoice(e)}if(Array.isArray(t))return this.JArrayToContainer(t);if(t==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(t,["parent"]))}static toJson(t,e,n){return JSON.stringify(t,(i,a)=>e?.some(s=>s===i)?void 0:a,n)}static WriteRuntimeContainer(t,e,n=false){if(t.WriteArrayStart(),e===null)return (0, Ce.throwNullException)("container");for(let l of e.content)this.WriteRuntimeObject(t,l);let i=e.namedOnlyContent,a=e.countFlags,s=e.name!=null&&!n,o=i!=null||a>0||s;if(o&&t.WriteObjectStart(),i!=null)for(let[l,u]of i){let h=l,c=(0, K.asOrNull)(u,qr.Container);t.WritePropertyStart(h),this.WriteRuntimeContainer(t,c,true),t.WritePropertyEnd();}a>0&&t.WriteIntProperty("#f",a),s&&t.WriteProperty("#n",e.name),o?t.WriteObjectEnd():t.WriteNull(),t.WriteArrayEnd();}static JArrayToContainer(t){let e=new qr.Container;e.content=this.JArrayToRuntimeObjList(t,true);let n=t[t.length-1];if(n!=null){let i=new Map;for(let a in n)if(a=="#f")e.countFlags=parseInt(n[a]);else if(a=="#n")e.name=n[a].toString();else {let s=this.JTokenToRuntimeObject(n[a]),o=(0, K.asOrNull)(s,qr.Container);o&&(o.name=a),i.set(a,s);}e.namedOnlyContent=i;}return e}static JObjectToChoice(t){let e=new Tu.Choice;return e.text=t.text.toString(),e.index=parseInt(t.index),e.sourcePath=t.originalChoicePath.toString(),e.originalThreadIndex=parseInt(t.originalThreadIndex),e.pathStringOnChoice=t.targetPath.toString(),e.tags=this.JArrayToTags(t),e}static JArrayToTags(t){return t.tags?t.tags:null}static WriteChoice(t,e){t.WriteObjectStart(),t.WriteProperty("text",e.text),t.WriteIntProperty("index",e.index),t.WriteProperty("originalChoicePath",e.sourcePath),t.WriteIntProperty("originalThreadIndex",e.originalThreadIndex),t.WriteProperty("targetPath",e.pathStringOnChoice),this.WriteChoiceTags(t,e),t.WriteObjectEnd();}static WriteChoiceTags(t,e){if(e.tags&&e.tags.length>0){t.WritePropertyStart("tags"),t.WriteArrayStart();for(let n of e.tags)t.Write(n);t.WriteArrayEnd(),t.WritePropertyEnd();}}static WriteInkList(t,e){let n=e.value;if(n===null)return (0, Ce.throwNullException)("rawList");t.WriteObjectStart(),t.WritePropertyStart("list"),t.WriteObjectStart();for(let[i,a]of n){let s=Mr.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, Ce.throwNullException)("item.itemName");t.WritePropertyNameStart(),t.WritePropertyNameInner(s.originName?s.originName:"?"),t.WritePropertyNameInner("."),t.WritePropertyNameInner(s.itemName),t.WritePropertyNameEnd(),t.Write(o),t.WritePropertyEnd();}if(t.WriteObjectEnd(),t.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){t.WritePropertyStart("origins"),t.WriteArrayStart();for(let i of n.originNames)t.Write(i);t.WriteArrayEnd(),t.WritePropertyEnd();}t.WriteObjectEnd();}static ListDefinitionsToJToken(t){let e={};for(let n of t.lists){let i={};for(let[a,s]of n.items){let o=Mr.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Ce.throwNullException)("item.itemName");i[o.itemName]=s;}e[n.name]=i;}return e}static JTokenToListDefinitions(t){let e=t,n=[];for(let i in e)if(e.hasOwnProperty(i)){let a=i.toString(),s=e[i],o=new Map;for(let u in s)if(e.hasOwnProperty(i)){let h=s[u];o.set(u,parseInt(h));}let l=new zp.ListDefinition(a,o);n.push(l);}return new Xp.ListDefinitionsOrigin(n)}};Gr.JsonSerialisation=Br;Br._controlCommandNames=(()=>{let r=[];r[k.ControlCommand.CommandType.EvalStart]="ev",r[k.ControlCommand.CommandType.EvalOutput]="out",r[k.ControlCommand.CommandType.EvalEnd]="/ev",r[k.ControlCommand.CommandType.Duplicate]="du",r[k.ControlCommand.CommandType.PopEvaluatedValue]="pop",r[k.ControlCommand.CommandType.PopFunction]="~ret",r[k.ControlCommand.CommandType.PopTunnel]="->->",r[k.ControlCommand.CommandType.BeginString]="str",r[k.ControlCommand.CommandType.EndString]="/str",r[k.ControlCommand.CommandType.NoOp]="nop",r[k.ControlCommand.CommandType.ChoiceCount]="choiceCnt",r[k.ControlCommand.CommandType.Turns]="turn",r[k.ControlCommand.CommandType.TurnsSince]="turns",r[k.ControlCommand.CommandType.ReadCount]="readc",r[k.ControlCommand.CommandType.Random]="rnd",r[k.ControlCommand.CommandType.SeedRandom]="srnd",r[k.ControlCommand.CommandType.VisitIndex]="visit",r[k.ControlCommand.CommandType.SequenceShuffleIndex]="seq",r[k.ControlCommand.CommandType.StartThread]="thread",r[k.ControlCommand.CommandType.Done]="done",r[k.ControlCommand.CommandType.End]="end",r[k.ControlCommand.CommandType.ListFromInt]="listInt",r[k.ControlCommand.CommandType.ListRange]="range",r[k.ControlCommand.CommandType.ListRandom]="lrnd",r[k.ControlCommand.CommandType.BeginTag]="#",r[k.ControlCommand.CommandType.EndTag]="/#";for(let t=0;t<k.ControlCommand.CommandType.TOTAL_VALUES;++t)if(r[t]==null)throw new Error("Control command not accounted for in serialisation");return r})();});var bo=b(Tn=>{Object.defineProperty(Tn,"__esModule",{value:true});Tn.CallStack=void 0;var yo=fe(),Pu=dt(),Yp=Pn(),Ou=Be(),Qp=$(),Zp=he(),wn=gn(),tg=en(),Nu=Ae(),So=nt(),xn=class r{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let e=this._threads[this._threads.length-1].callstack;return e[e.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(t){tg.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(t);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=wn.Pointer.Null,arguments[0]instanceof Yp.Story){let t=arguments[0];this._startOfRoot=wn.Pointer.StartOf(t.rootContentContainer),this.Reset();}else {let t=arguments[0];this._threads=[];for(let e of t._threads)this._threads.push(e.Copy());this._threadCounter=t._threadCounter,this._startOfRoot=t._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new r.Thread),this._threads[0].callstack.push(new r.Element(yo.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(t,e){this._threads.length=0;let n=t.threads;for(let i of n){let a=i,s=new r.Thread(a,e);this._threads.push(s);}this._threadCounter=parseInt(t.threadCounter),this._startOfRoot=wn.Pointer.StartOf(e.rootContentContainer);}WriteJson(t){t.WriteObject(e=>{e.WritePropertyStart("threads"),e.WriteArrayStart();for(let n of this._threads)n.WriteJson(e);e.WriteArrayEnd(),e.WritePropertyEnd(),e.WritePropertyStart("threadCounter"),e.WriteInt(this._threadCounter),e.WritePropertyEnd();});}PushThread(){let t=this.currentThread.Copy();this._threadCounter++,t.threadIndex=this._threadCounter,this._threads.push(t);}ForkThread(){let t=this.currentThread.Copy();return this._threadCounter++,t.threadIndex=this._threadCounter,t}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==yo.PushPopType.FunctionEvaluationFromGame}Push(t,e=0,n=0){let i=new r.Element(t,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=e,i.functionStartInOutputStream=n,this.callStack.push(i);}CanPop(t=null){return this.canPop?t==null?true:this.currentElement.type==t:false}Pop(t=null){if(this.CanPop(t)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(t,e=-1){e==-1&&(e=this.currentElementIndex+1);let n=this.callStack[e-1],i=(0, Nu.tryGetValueFromMap)(n.temporaryVariables,t,null);return i.exists?i.result:null}SetTemporaryVariable(t,e,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!n&&!a.temporaryVariables.get(t))throw new Error("Could not find temporary variable to set: "+t);let s=(0, Nu.tryGetValueFromMap)(a.temporaryVariables,t,null);s.exists&&Qp.ListValue.RetainListOriginsForAssignment(s.result,e),a.temporaryVariables.set(t,e);}ContextForVariableNamed(t){return this.currentElement.temporaryVariables.get(t)?this.currentElementIndex+1:0}ThreadWithIndex(t){let e=this._threads.filter(n=>{if(n.threadIndex==t)return n});return e.length>0?e[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let t=new Zp.StringBuilder;for(let e=0;e<this._threads.length;e++){let n=this._threads[e],i=e==this._threads.length-1;t.AppendFormat(`=== THREAD {0}/{1} {2}===
|
|
20
|
+
`,e+1,this._threads.length,i?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==yo.PushPopType.Function?t.Append(" [FUNCTION] "):t.Append(" [TUNNEL] ");let s=n.callstack[a].currentPointer;if(!s.isNull){if(t.Append("<SOMEWHERE IN "),s.container===null)return (0, So.throwNullException)("pointer.container");t.Append(s.container.path.toString()),t.AppendLine(">");}}}return t.toString()}};Tn.CallStack=xn;(function(r){class t{constructor(i,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new t(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}r.Element=t;class e{constructor(){if(this.threadIndex=0,this.previousPointer=wn.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let s=i.callstack;for(let l of s){let u=l,h=parseInt(u.type),c=wn.Pointer.Null,f,p=u.cPath;if(typeof p<"u"){f=p.toString();let _=a.ContentAtPath(new Pu.Path(f));if(c.container=_.container,c.index=parseInt(u.idx),_.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?");_.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 g=!!u.exp,y=new t(h,c,g),b=u.temp;typeof b<"u"?y.temporaryVariables=Ou.JsonSerialisation.JObjectToDictionaryRuntimeObjs(b):y.temporaryVariables.clear(),this.callstack.push(y);}let o=i.previousContentObject;if(typeof o<"u"){let l=new Pu.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let i=new e;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, So.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"),Ou.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, So.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}r.Thread=e;})(xn||(Tn.CallStack=xn={}));});var Iu=b(Jr=>{Object.defineProperty(Jr,"__esModule",{value:true});Jr.VariablesState=void 0;var et=$(),eg=rn(),Au=Be(),rt=D(),On=Ae(),te=nt();function ng(){return class{}}var $r=class r extends ng(){variableChangedEvent(t,e){for(let n of this.variableChangedEventCallbacks)n(t,e);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let t=new Map;if(this._changedVariablesForBatchObs!=null)for(let e of this._changedVariablesForBatchObs){let n=this._globalVariables.get(e);this.variableChangedEvent(e,n);}if(this.patch!=null)for(let e of this.patch.changedVariables){let n=this.patch.TryGetGlobal(e,null);n.exists&&t.set(e,n);}return this._changedVariablesForBatchObs=null,t}NotifyObservers(t){for(let[e,n]of t)this.variableChangedEvent(e,n);}get callStack(){return this._callStack}set callStack(t){this._callStack=t;}$(t,e){if(typeof e>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(t),typeof n>"u"&&(n=this._defaultGlobalVariables.get(t)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(t)>"u")throw new eg.StoryException("Cannot assign to a variable ("+t+") that hasn't been declared in the story");let n=et.Value.Create(e);if(n==null)throw e==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+e.toString());this.SetGlobal(t,n);}}constructor(t,e){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=t,this._listDefsOrigin=e;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,s){return a in i?i[a]=s:i.$(a,s),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,a){return {enumerable:!0,configurable:!0,value:i.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, te.throwNullException)("this.patch");for(let[t,e]of this.patch.globals)this._globalVariables.set(t,e);if(this._changedVariablesForBatchObs!==null)for(let t of this.patch.changedVariables)this._changedVariablesForBatchObs.add(t);this.patch=null;}SetJsonToken(t){this._globalVariables.clear();for(let[e,n]of this._defaultGlobalVariables){let i=t[e];if(typeof i<"u"){let a=Au.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, te.throwNullException)("tokenInkObject");this._globalVariables.set(e,a);}else this._globalVariables.set(e,n);}}WriteJson(t){t.WriteObjectStart();for(let[e,n]of this._globalVariables){let i=e,a=n;if(r.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let s=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,s))continue}t.WritePropertyStart(i),Au.JsonSerialisation.WriteRuntimeObject(t,a),t.WritePropertyEnd();}t.WriteObjectEnd();}RuntimeObjectsEqual(t,e){if(t===null)return (0, te.throwNullException)("obj1");if(e===null)return (0, te.throwNullException)("obj2");if(t.constructor!==e.constructor)return false;let n=(0, rt.asOrNull)(t,et.BoolValue);if(n!==null)return n.value===(0, rt.asOrThrows)(e,et.BoolValue).value;let i=(0, rt.asOrNull)(t,et.IntValue);if(i!==null)return i.value===(0, rt.asOrThrows)(e,et.IntValue).value;let a=(0, rt.asOrNull)(t,et.FloatValue);if(a!==null)return a.value===(0, rt.asOrThrows)(e,et.FloatValue).value;let s=(0, rt.asOrNull)(t,et.Value),o=(0, rt.asOrNull)(e,et.Value);if(s!==null&&o!==null)return (0, rt.isEquatable)(s.valueObject)&&(0, rt.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+t.constructor.name)}GetVariableWithName(t,e=-1){let n=this.GetRawVariableWithName(t,e),i=(0, rt.asOrNull)(n,et.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(t){let e=(0, On.tryGetValueFromMap)(this._defaultGlobalVariables,t,null);return e.exists?e.result:null}GlobalVariableExistsWithName(t){return this._globalVariables.has(t)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(t)}GetRawVariableWithName(t,e){let n=null;if(e==0||e==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(t,null),i.exists)||(i=(0, On.tryGetValueFromMap)(this._globalVariables,t,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, On.tryGetValueFromMap)(this._defaultGlobalVariables,t,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, te.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(t);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(t,e),n}ValueAtVariablePointer(t){return this.GetVariableWithName(t.variableName,t.contextIndex)}Assign(t,e){let n=t.variableName;if(n===null)return (0, te.throwNullException)("name");let i=-1,a=false;if(t.isNewDeclaration?a=t.isGlobal:a=this.GlobalVariableExistsWithName(n),t.isNewDeclaration){let s=(0, rt.asOrNull)(e,et.VariablePointerValue);s!==null&&(e=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, rt.asOrNull)(this.GetRawVariableWithName(n,i),et.VariablePointerValue),s!=null&&(n=s.variableName,i=s.contextIndex,a=i==0);while(s!=null)}a?this.SetGlobal(n,e):this._callStack.SetTemporaryVariable(n,e,t.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(t,e){let n=(0, rt.asOrThrows)(t,et.ListValue),i=(0, rt.asOrThrows)(e,et.ListValue);n.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(t,e){let n=null;if(this.patch===null&&(n=(0, On.tryGetValueFromMap)(this._globalVariables,t,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(t,null),n.exists||(n=(0, On.tryGetValueFromMap)(this._globalVariables,t,null))),et.ListValue.RetainListOriginsForAssignment(n.result,e),t===null)return (0, te.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(t,e):this._globalVariables.set(t,e),this.variableChangedEvent!==null&&n!==null&&e!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, te.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(t):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(t);}else this.variableChangedEvent(t,e);}ResolveVariablePointer(t){let e=t.contextIndex;e==-1&&(e=this.GetContextIndexOfVariableNamed(t.variableName));let n=this.GetRawVariableWithName(t.variableName,e),i=(0, rt.asOrNull)(n,et.VariablePointerValue);return i??new et.VariablePointerValue(t.variableName,e)}GetContextIndexOfVariableNamed(t){return this.GlobalVariableExistsWithName(t)?0:this._callStack.currentElementIndex}ObserveVariableChange(t){this.variableChangedEventCallbacks.push(t);}};Jr.VariablesState=$r;$r.dontSaveDefaultValues=true;});var Eo=b(Ur=>{Object.defineProperty(Ur,"__esModule",{value:true});Ur.PRNG=void 0;var _o=class{constructor(t){this.seed=t%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};Ur.PRNG=_o;});var Vu=b(Hr=>{Object.defineProperty(Hr,"__esModule",{value:true});Hr.StatePatch=void 0;var wo=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let t=arguments[0];this._globals=new Map(t._globals),this._changedVariables=new Set(t._changedVariables),this._visitCounts=new Map(t._visitCounts),this._turnIndices=new Map(t._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(t,e){return t!==null&&this._globals.has(t)?{result:this._globals.get(t),exists:true}:{result:e,exists:false}}SetGlobal(t,e){this._globals.set(t,e);}AddChangedVariable(t){return this._changedVariables.add(t)}TryGetVisitCount(t,e){return this._visitCounts.has(t)?{result:this._visitCounts.get(t),exists:true}:{result:e,exists:false}}SetVisitCount(t,e){this._visitCounts.set(t,e);}SetTurnIndex(t,e){this._turnIndices.set(t,e);}TryGetTurnIndex(t,e){return this._turnIndices.has(t)?{result:this._turnIndices.get(t),exists:true}:{result:e,exists:false}}};Hr.StatePatch=wo;});var xo=b(An=>{Object.defineProperty(An,"__esModule",{value:true});An.SimpleJson=void 0;var Nn=class r{static TextToDictionary(t){return new r.Reader(t).ToDictionary()}static TextToArray(t){return new r.Reader(t).ToArray()}};An.SimpleJson=Nn;(function(r){class t{constructor(i){if(JSON.parse("0",(s,o,l)=>l!=null)){let s=(o,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(i,s);}else {let s=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}r.Reader=t;class e{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===r.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===r.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===r.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new r.Writer.StateElement(r.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===r.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}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===r.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new r.Writer.StateElement(r.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===r.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===r.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new r.Writer.StateElement(r.Writer.State.Property)),this._stateStack.push(new r.Writer.StateElement(r.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===r.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===r.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===r.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===r.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===r.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new r.Writer.StateElement(r.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===r.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new r.Writer.StateElement(r.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==r.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===r.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===r.Writer.State.None||this.state===r.Writer.State.Property||this.state===r.Writer.State.Array):this.Assert(this.state===r.Writer.State.Property||this.state===r.Writer.State.Array),this.state===r.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===r.Writer.State.Array||this.state===r.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:r.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===r.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===r.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}r.Writer=e,(function(n){(function(s){s[s.None=0]="None",s[s.Object=1]="Object",s[s.Array=2]="Array",s[s.Property=3]="Property",s[s.PropertyName=4]="PropertyName",s[s.String=5]="String";})(n.State||(n.State={}));class a{constructor(o){this.type=r.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;})(e=r.Writer||(r.Writer={}));})(Nn||(An.SimpleJson=Nn={}));});var ku=b(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.Flow=void 0;var Fu=bo(),Kr=Be(),ig=nt(),To=class{constructor(){let t=arguments[0],e=arguments[1];if(this.name=t,this.callStack=new Fu.CallStack(e),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,e),this.outputStream=Kr.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=Kr.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let i=n.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,e);}else this.outputStream=[],this.currentChoices=[];}WriteJson(t){t.WriteObjectStart(),t.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),t.WriteProperty("outputStream",n=>Kr.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let e=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, ig.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(e||(e=true,t.WritePropertyStart("choiceThreads"),t.WriteObjectStart()),t.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(t),t.WritePropertyEnd());}e&&(t.WriteObjectEnd(),t.WritePropertyEnd()),t.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let i of this.currentChoices)Kr.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),t.WriteObjectEnd();}LoadFlowChoiceThreads(t,e){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let a=t[`${n.originalThreadIndex}`];n.threadAtGeneration=new Fu.CallStack.Thread(a,e);}}}};zr.Flow=To;});var Du=b(Yr=>{Object.defineProperty(Yr,"__esModule",{value:true});Yr.StoryState=void 0;var rg=bo(),sg=Iu(),Y=$(),ee=fe(),ag=Dr(),Po=Pr(),Ru=dt(),ut=it(),Oo=he(),ne=Be(),og=Eo(),lg=de(),Ge=gn(),In=Ae(),z=D(),ug=en(),Nt=nt(),hg=Pn(),cg=Vu(),Lu=xo(),Xr=ku(),dg=gt(),No=class r{ToJson(t=false){let e=new Lu.SimpleJson.Writer;return this.WriteJson(e),e.toString()}toJson(t=false){return this.ToJson(t)}LoadJson(t){let e=Lu.SimpleJson.TextToDictionary(t);this.LoadJsonObj(e),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(t){let e;if(this._patch!==null){let n=this.story.ContentAtPath(new Ru.Path(t)).container;if(n===null)throw new Error("Content at path not found: "+t);if(e=this._patch.TryGetVisitCount(n,0),e.exists)return e.result}return e=(0, In.tryGetValueFromMap)(this._visitCounts,t,null),e.exists?e.result:0}VisitCountForContainer(t){if(t===null)return (0, Nt.throwNullException)("container");if(!t.visitsShouldBeCounted)return this.story.Error("Read count for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(t,0);if(i.exists)return i.result}let e=t.path.toString(),n=(0, In.tryGetValueFromMap)(this._visitCounts,e,null);return n.exists?n.result:0}IncrementVisitCountForContainer(t){if(this._patch!==null){let i=this.VisitCountForContainer(t);i++,this._patch.SetVisitCount(t,i);return}let e=t.path.toString(),n=(0, In.tryGetValueFromMap)(this._visitCounts,e,null);n.exists?this._visitCounts.set(e,n.result+1):this._visitCounts.set(e,1);}RecordTurnIndexVisitToContainer(t){if(this._patch!==null){this._patch.SetTurnIndex(t,this.currentTurnIndex);return}let e=t.path.toString();this._turnIndices.set(e,this.currentTurnIndex);}TurnsSinceForContainer(t){if(t.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+t.name+" - on "+t.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(t,0);if(i.exists)return this.currentTurnIndex-i.result}let e=t.path.toString(),n=(0, In.tryGetValueFromMap)(this._turnIndices,e,0);return n.exists?this.currentTurnIndex-n.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(t){this._variablesState=t;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(t){this._currentTurnIndex=t;}get currentPathString(){let t=this.currentPointer;return t.isNull?null:t.path===null?(0, Nt.throwNullException)("pointer.path"):t.path.toString()}get previousPathString(){let t=this.previousPointer;return t.isNull?null:t.path===null?(0, Nt.throwNullException)("previousPointer.path"):t.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(t){this.callStack.currentElement.currentPointer=t.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(t){this.callStack.currentThread.previousPointer=t.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let t=new Oo.StringBuilder,e=false;for(let n of this.outputStream){let i=(0, z.asOrNull)(n,Y.StringValue);if(!e&&i!==null)t.Append(i.value);else {let a=(0, z.asOrNull)(n,ut.ControlCommand);a!==null&&(a.commandType==ut.ControlCommand.CommandType.BeginTag?e=true:a.commandType==ut.ControlCommand.CommandType.EndTag&&(e=false));}}this._currentText=this.CleanOutputWhitespace(t.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(t){let e=new Oo.StringBuilder,n=-1,i=0;for(let a=0;a<t.length;a++){let s=t.charAt(a),o=s==" "||s==" ";o&&n==-1&&(n=a),o||(s!=`
|
|
21
|
+
`&&n>0&&n!=i&&e.Append(" "),n=-1),s==`
|
|
22
|
+
`&&(i=a+1),o||e.Append(s);}return e.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let t=false,e=new Oo.StringBuilder;for(let n of this.outputStream){let i=(0, z.asOrNull)(n,ut.ControlCommand);if(i!=null){if(i.commandType==ut.ControlCommand.CommandType.BeginTag){if(t&&e.Length>0){let a=this.CleanOutputWhitespace(e.toString());this._currentTags.push(a),e.Clear();}t=true;}else if(i.commandType==ut.ControlCommand.CommandType.EndTag){if(e.Length>0){let a=this.CleanOutputWhitespace(e.toString());this._currentTags.push(a),e.Clear();}t=false;}}else if(t){let a=(0, z.asOrNull)(n,Y.StringValue);a!==null&&e.Append(a.value);}else {let a=(0, z.asOrNull)(n,ag.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(e.Length>0){let n=this.CleanOutputWhitespace(e.toString());this._currentTags.push(n),e.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let t of this._namedFlows.keys())t!=this.kDefaultFlowName&&this._aliveFlowNames.push(t);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(t){this.callStack.currentElement.inExpressionEvaluation=t;}constructor(t){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=Ge.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=t,this._currentFlow=new Xr.Flow(this.kDefaultFlowName,t),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new sg.VariablesState(this.callStack,t.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let e=new Date().getTime();this.storySeed=new og.PRNG(e).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Ge.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(t){if(t===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),t===this._currentFlow.name)return;let e,n=(0, In.tryGetValueFromMap)(this._namedFlows,t,null);n.exists?e=n.result:(e=new Xr.Flow(t,this.story),this._namedFlows.set(t,e),this._aliveFlowNamesDirty=true),this._currentFlow=e,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(t){if(t===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(t===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===t&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, Nt.throwNullException)("this._namedFlows");this._namedFlows.delete(t),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(t){let e=new r(this.story);if(e._patch=new cg.StatePatch(this._patch),e._currentFlow.name=this._currentFlow.name,e._currentFlow.callStack=new rg.CallStack(this._currentFlow.callStack),e._currentFlow.outputStream.push(...this._currentFlow.outputStream),e.OutputStreamDirty(),t)for(let n of this._currentFlow.currentChoices)e._currentFlow.currentChoices.push(n.Clone());else e._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){e._namedFlows=new Map;for(let[n,i]of this._namedFlows)e._namedFlows.set(n,i),e._aliveFlowNamesDirty=true;e._namedFlows.set(this._currentFlow.name,e._currentFlow);}return this.hasError&&(e._currentErrors=[],e._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(e._currentWarnings=[],e._currentWarnings.push(...this.currentWarnings||[])),e.variablesState=this.variablesState,e.variablesState.callStack=e.callStack,e.variablesState.patch=e._patch,e.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(e.divertedPointer=this.divertedPointer.copy()),e.previousPointer=this.previousPointer.copy(),e._visitCounts=this._visitCounts,e._turnIndices=this._turnIndices,e.currentTurnIndex=this.currentTurnIndex,e.storySeed=this.storySeed,e.previousRandom=this.previousRandom,e.didSafeExit=this.didSafeExit,e}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[t,e]of this._patch.visitCounts)this.ApplyCountChanges(t,e,true);for(let[t,e]of this._patch.turnIndices)this.ApplyCountChanges(t,e,false);this._patch=null;}}ApplyCountChanges(t,e,n){(n?this._visitCounts:this._turnIndices).set(t.path.toString(),e);}WriteJson(t){if(t.WriteObjectStart(),t.WritePropertyStart("flows"),t.WriteObjectStart(),this._namedFlows!==null)for(let[e,n]of this._namedFlows)t.WriteProperty(e,i=>n.WriteJson(i));else t.WriteProperty(this._currentFlow.name,e=>this._currentFlow.WriteJson(e));if(t.WriteObjectEnd(),t.WritePropertyEnd(),t.WriteProperty("currentFlowName",this._currentFlow.name),t.WriteProperty("variablesState",e=>this.variablesState.WriteJson(e)),t.WriteProperty("evalStack",e=>ne.JsonSerialisation.WriteListRuntimeObjs(e,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, Nt.throwNullException)("divertedPointer");t.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}t.WriteProperty("visitCounts",e=>ne.JsonSerialisation.WriteIntDictionary(e,this._visitCounts)),t.WriteProperty("turnIndices",e=>ne.JsonSerialisation.WriteIntDictionary(e,this._turnIndices)),t.WriteIntProperty("turnIdx",this.currentTurnIndex),t.WriteIntProperty("storySeed",this.storySeed),t.WriteIntProperty("previousRandom",this.previousRandom),t.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),t.WriteIntProperty("inkFormatVersion",hg.Story.inkVersionCurrent),t.WriteObjectEnd();}LoadJsonObj(t){let e=t,n=e.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+n+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let i=e.flows;if(i!=null){let s=i;Object.keys(s).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(s);for(let[l,u]of o){let h=l,c=u,f=new Xr.Flow(h,this.story,c);if(Object.keys(s).length===1)this._currentFlow=new Xr.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, Nt.throwNullException)("this._namedFlows");this._namedFlows.set(h,f);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let l=e.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(e.callstackThreads,this.story),this._currentFlow.outputStream=ne.JsonSerialisation.JArrayToRuntimeObjList(e.outputStream),this._currentFlow.currentChoices=ne.JsonSerialisation.JArrayToRuntimeObjList(e.currentChoices);let s=e.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(e.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=ne.JsonSerialisation.JArrayToRuntimeObjList(e.evalStack);let a=e.currentDivertTarget;if(a!=null){let s=new Ru.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=ne.JsonSerialisation.JObjectToIntDictionary(e.visitCounts),this._turnIndices=ne.JsonSerialisation.JObjectToIntDictionary(e.turnIndices),this.currentTurnIndex=parseInt(e.turnIdx),this.storySeed=parseInt(e.storySeed),this.previousRandom=parseInt(e.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(t=null){this.outputStream.length=0,t!==null&&this.outputStream.push(...t),this.OutputStreamDirty();}PushToOutputStream(t){let e=(0, z.asOrNull)(t,Y.StringValue);if(e!==null){let n=this.TrySplittingHeadTailWhitespace(e);if(n!==null){for(let i of n)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(t),this.OutputStreamDirty();}PopFromOutputStream(t){this.outputStream.splice(this.outputStream.length-t,t),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(t){let e=t.value;if(e===null)return (0, Nt.throwNullException)("single.value");let n=-1,i=-1;for(let h=0;h<e.length;h++){let c=e[h];if(c==`
|
|
23
|
+
`)n==-1&&(n=h),i=h;else {if(c==" "||c==" ")continue;break}}let a=-1,s=-1;for(let h=e.length-1;h>=0;h--){let c=e[h];if(c==`
|
|
24
|
+
`)a==-1&&(a=h),s=h;else {if(c==" "||c==" ")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=e.length;if(n!=-1){if(n>0){let h=new Y.StringValue(e.substring(0,n));o.push(h);}o.push(new Y.StringValue(`
|
|
25
|
+
`)),l=i+1;}if(a!=-1&&(u=s),u>l){let h=e.substring(l,u);o.push(new Y.StringValue(h));}if(a!=-1&&s>i&&(o.push(new Y.StringValue(`
|
|
26
|
+
`)),a<e.length-1)){let h=e.length-a-1,c=new Y.StringValue(e.substring(a+1,a+1+h));o.push(c);}return o}PushToOutputStreamIndividual(t){let e=(0, z.asOrNull)(t,Po.Glue),n=(0, z.asOrNull)(t,Y.StringValue),i=true;if(e)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let a=-1,s=this.callStack.currentElement;s.type==ee.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u],c=h instanceof ut.ControlCommand?h:null;if((h instanceof Po.Glue?h:null)!=null){o=u;break}else if(c!=null&&c.commandType==ut.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=false;else if(n.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let u=this.callStack.elements;for(let h=u.length-1;h>=0;h--){let c=u[h];if(c.type==ee.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(t===null)return (0, Nt.throwNullException)("obj");this.outputStream.push(t),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let t=-1,e=this.outputStream.length-1;for(;e>=0;){let n=this.outputStream[e],i=(0, z.asOrNull)(n,ut.ControlCommand),a=(0, z.asOrNull)(n,Y.StringValue);if(i!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(t=e),e--;}if(t>=0)for(e=t;e<this.outputStream.length;)(0, z.asOrNull)(this.outputStream[e],Y.StringValue)?this.outputStream.splice(e,1):e++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let t=this.outputStream.length-1;t>=0;t--){let e=this.outputStream[t];if(e instanceof Po.Glue)this.outputStream.splice(t,1);else if(e instanceof ut.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let t=this.outputStream.length-1;t>=0&&!(this.outputStream[t]instanceof ut.ControlCommand);t--){let n=this.outputStream[t];if(n instanceof Y.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let t of this.outputStream)if(t instanceof Y.StringValue)return true;return false}get inStringEvaluation(){for(let t=this.outputStream.length-1;t>=0;t--){let e=(0, z.asOrNull)(this.outputStream[t],ut.ControlCommand);if(e instanceof ut.ControlCommand&&e.commandType==ut.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(t){let e=(0, z.asOrNull)(t,Y.ListValue);if(e){let n=e.value;if(n===null)return (0, Nt.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, Nt.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, Nt.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(t===null)return (0, Nt.throwNullException)("obj");this.evaluationStack.push(t);}PopEvaluationStack(t){if(typeof t>"u"){let e=this.evaluationStack.pop();return (0, z.nullIfUndefined)(e)}else {if(t>this.evaluationStack.length)throw new Error("trying to pop too many objects");let e=this.evaluationStack.splice(this.evaluationStack.length-t,t);return (0, z.nullIfUndefined)(e)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Ge.Pointer.Null,this.previousPointer=Ge.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){ug.Debug.Assert(this.callStack.currentElement.type==ee.PushPopType.Function);let t=this.callStack.currentElement.functionStartInOutputStream;t==-1&&(t=0);for(let e=this.outputStream.length-1;e>=t;e--){let n=this.outputStream[e],i=(0, z.asOrNull)(n,Y.StringValue),a=(0, z.asOrNull)(n,ut.ControlCommand);if(i!=null){if(a)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(e,1),this.OutputStreamDirty();else break}}}PopCallStack(t=null){this.callStack.currentElement.type==ee.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(t);}SetChosenPath(t,e){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(t);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,e&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(t,e){this.callStack.Push(ee.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Ge.Pointer.StartOf(t),this.PassArgumentsToEvaluationStack(e);}PassArgumentsToEvaluationStack(t){if(t!==null)for(let e=0;e<t.length;e++){if(!(typeof t[e]=="number"||typeof t[e]=="string"||typeof t[e]=="boolean"||t[e]instanceof dg.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, z.nullIfUndefined)(t[e])===null?"null":t[e].constructor.name));this.PushEvaluationStack(Y.Value.Create(t[e]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==ee.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Ge.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=ee.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let t=this.callStack.currentElement.evaluationStackHeightWhenPushed,e=null;for(;this.evaluationStack.length>t;){let n=this.PopEvaluationStack();e===null&&(e=n);}if(this.PopCallStack(ee.PushPopType.FunctionEvaluationFromGame),e){if(e instanceof lg.Void)return null;let n=(0, z.asOrThrows)(e,Y.Value);return n.valueType==Y.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(t,e){e?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(t)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(t));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};Yr.StoryState=No;});var Wu=b(Qr=>{Object.defineProperty(Qr,"__esModule",{value:true});Qr.Stopwatch=void 0;var Ao=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;}};Qr.Stopwatch=Ao;});var qu=b(Zr=>{Object.defineProperty(Zr,"__esModule",{value:true});Zr.ErrorType=void 0;var ju;(function(r){r[r.Author=0]="Author",r[r.Warning=1]="Warning",r[r.Error=2]="Error";})(ju||(Zr.ErrorType=ju={}));});var Pn=b(Se=>{Object.defineProperty(Se,"__esModule",{value:true});Se.Story=Se.InkList=void 0;var st=H(),Io=ft(),Vo=Be(),fg=Du(),O=it(),At=fe(),pg=Si(),gg=po(),Mu=jt(),x=$(),Fo=dt(),Vn=de(),ts=Dr(),mg=Yt(),Cg=je(),vg=Wt(),ve=rn(),ko=Eo(),ye=he(),yg=mo(),Sg=Wu(),ie=gn(),Fn=gt(),N=D(),L=nt(),Bu=xo(),Gu=qu(),bg=gt();Object.defineProperty(Se,"InkList",{enumerable:true,get:function(){return bg.InkList}});Number.isInteger||(Number.isInteger=function(t){return typeof t=="number"&&isFinite(t)&&t>-9007199254740992&&t<9007199254740992&&Math.floor(t)===t});var $e=class r extends Io.InkObject{get currentChoices(){let t=[];if(this._state===null)return (0, L.throwNullException)("this._state");for(let e of this._state.currentChoices)e.isInvisibleDefault||(e.index=t.length,t.push(e));return t}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=false,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=false,this._temporaryEvaluationContainer=null,this._asyncContinueActive=false,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount=0,this._asyncSaving=false,this._profiler=null;let t,e=null,n=null;if(arguments[0]instanceof st.Container)t=arguments[0],typeof arguments[1]<"u"&&(e=arguments[1]),this._mainContentContainer=t;else if(typeof arguments[0]=="string"){let i=arguments[0];n=Bu.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(e!=null&&(this._listDefinitions=new yg.ListDefinitionsOrigin(e)),this._externals=new Map,n!==null){let i=n,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let s=parseInt(a);if(s>r.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(s<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");s!=r.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${r.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=i.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let l;(l=i.listDefs)&&(this._listDefinitions=Vo.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, N.asOrThrows)(Vo.JsonSerialisation.JTokenToRuntimeObject(o),st.Container),this.ResetState();}}ToJson(t){let e=false;if(t||(e=true,t=new Bu.SimpleJson.Writer),t.WriteObjectStart(),t.WriteIntProperty("inkVersion",r.inkVersionCurrent),t.WriteProperty("root",n=>Vo.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){t.WritePropertyStart("listDefs"),t.WriteObjectStart();for(let n of this._listDefinitions.lists){t.WritePropertyStart(n.name),t.WriteObjectStart();for(let[i,a]of n.items){let s=Fn.InkListItem.fromSerializedKey(i),o=a;t.WriteIntProperty(s.itemName,o);}t.WriteObjectEnd(),t.WritePropertyEnd();}t.WriteObjectEnd(),t.WritePropertyEnd();}if(t.WriteObjectEnd(),e)return t.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new fg.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, L.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, L.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let t=this.state.currentPointer.copy();this.ChoosePath(new Fo.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=t;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(t){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+t);this.state.SwitchFlow_Internal(t);}RemoveFlow(t){this.state.RemoveFlow_Internal(t);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(t){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(t);}ContinueInternal(t=0){this._profiler!=null&&this._profiler.PreContinue();let e=t>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!e&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=e,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=false,this._state.ResetOutput(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation();}let n=new Sg.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof ve.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>t)break}while(this.canContinue);n.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(At.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(At.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(a=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let s of this.state.currentErrors)this.onError(s,Gu.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,Gu.ErrorType.Warning);this.ResetErrors();}else {let s=new ye.StringBuilder;throw s.Append("Ink had "),this.state.hasError&&(s.Append(`${this.state.currentErrors.length}`),s.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&s.Append(" and ")),this.state.hasWarning&&(s.Append(`${this.state.currentWarnings.length}`),s.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&s.Append(" and ")),s.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),s.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new ve.StoryException(s.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, L.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, L.throwNullException)("this.state.currentTags");let t=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(t==r.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;t==r.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(t,e,n,i){if(t===null)return (0, L.throwNullException)("prevText");if(e===null)return (0, L.throwNullException)("currText");let a=e.length>=t.length&&t.length>0&&e.charAt(t.length-1)==`
|
|
27
|
+
`;if(n==i&&t.length==e.length&&a)return r.OutputStateChange.NoChange;if(!a)return r.OutputStateChange.NewlineRemoved;if(i>n)return r.OutputStateChange.ExtendedBeyondNewline;for(let s=t.length;s<e.length;s++){let o=e.charAt(s);if(o!=" "&&o!=" ")return r.OutputStateChange.ExtendedBeyondNewline}return r.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let t=new ye.StringBuilder;for(;this.canContinue;)t.Append(this.Continue());return t.toString()}ContentAtPath(t){return this.mainContentContainer.ContentAtPath(t)}KnotContainerWithName(t){let e=this.mainContentContainer.namedContent.get(t);return e instanceof st.Container?e:null}PointerAtPath(t){if(t.length==0)return ie.Pointer.Null;let e=new ie.Pointer,n=t.length,i=null;return t.lastComponent===null?(0, L.throwNullException)("path.lastComponent"):(t.lastComponent.isIndex?(n=t.length-1,i=this.mainContentContainer.ContentAtPath(t,void 0,n),e.container=i.container,e.index=t.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(t),e.container=i.container,e.index=-1),i.obj==null||i.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+t+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+t+"', so it was approximated to: '"+i.obj.path+"'."),e)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, L.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let t=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,t}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let t=true,e=this.state.currentPointer.copy();if(e.isNull)return;let n=(0, N.asOrNull)(e.Resolve(),st.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)e=ie.Pointer.StartOf(n),n=(0, N.asOrNull)(e.Resolve(),st.Container);this.state.currentPointer=e.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=e.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(t=false);let s=(0, N.asOrNull)(i,pg.ChoicePoint);if(s){let l=this.ProcessChoice(s);l&&this.state.generatedChoices.push(l),i=null,t=false;}if(i instanceof st.Container&&(t=false),t){let l=(0, N.asOrNull)(i,x.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);i=new x.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(t,e){(!t.countingAtStartOnly||e)&&(t.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(t),t.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(t));}VisitChangedContainersDueToDivert(){let t=this.state.previousPointer.copy(),e=this.state.currentPointer.copy();if(e.isNull||e.index==-1)return;if(this._prevContainers.length=0,!t.isNull){let s=t.Resolve(),o=(0, N.asOrNull)(s,st.Container)||(0, N.asOrNull)(t.container,st.Container);for(;o;)this._prevContainers.push(o),o=(0, N.asOrNull)(o.parent,st.Container);}let n=e.Resolve();if(n==null)return;let i=(0, N.asOrNull)(n.parent,st.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let s=i.content.length>0&&n==i.content[0]&&a;s||(a=false),this.VisitContainer(i,s),n=i,i=(0, N.asOrNull)(i.parent,st.Container);}}PopChoiceStringAndTags(t){let e=(0, N.asOrThrows)(this.state.PopEvaluationStack(),x.StringValue);for(;this.state.evaluationStack.length>0&&(0, N.asOrNull)(this.state.PeekEvaluationStack(),ts.Tag)!=null;){let n=(0, N.asOrNull)(this.state.PopEvaluationStack(),ts.Tag);n&&t.push(n.text);}return e.value}ProcessChoice(t){let e=true;if(t.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(e=false);}let n="",i="",a=[];if(t.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),t.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),t.onceOnly&&this.state.VisitCountForContainer(t.choiceTarget)>0&&(e=false),!e)return null;let s=new gg.Choice;return s.targetPath=t.pathOnChoice,s.sourcePath=t.path.toString(),s.isInvisibleDefault=t.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(t){let e=false;if(t instanceof x.Value){let n=t;if(n instanceof x.DivertTargetValue){let i=n;return this.Error("Shouldn't use a divert target (to "+i.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return e}PerformLogicAndFlowControl(t){if(t==null)return false;if(t instanceof Mu.Divert){let e=t;if(e.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(e.hasVariableTarget){let n=e.variableDivertName,i=this.state.variablesState.GetVariableWithName(n);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(i instanceof x.DivertTargetValue)){let s=(0, N.asOrNull)(i,x.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";s instanceof x.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, N.asOrThrows)(i,x.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(e.isExternal)return this.CallExternalFunction(e.targetPathString,e.externalArgs),true;this.state.divertedPointer=e.targetPointer.copy();}return e.pushesToStack&&this.state.callStack.Push(e.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!e.isExternal&&(e&&e.debugMetadata&&e.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+e.debugMetadata.sourceName):this.Error("Divert resolution failed: "+e)),true}else if(t instanceof O.ControlCommand){let e=t;switch(e.commandType){case O.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case O.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case O.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let m=this.state.PopEvaluationStack();if(!(m instanceof Vn.Void)){let E=new x.StringValue(m.toString());this.state.PushToOutputStream(E);}}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=e.commandType==O.ControlCommand.CommandType.PopFunction?At.PushPopType.Function:At.PushPopType.Tunnel,i=null;if(n==At.PushPopType.Tunnel){let m=this.state.PopEvaluationStack();i=(0, N.asOrNull)(m,x.DivertTargetValue),i===null&&this.Assert(m instanceof Vn.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let m=new Map;m.set(At.PushPopType.Function,"function return statement (~ return)"),m.set(At.PushPopType.Tunnel,"tunnel onwards statement (->->)");let E=m.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(E="end of flow (-> END or choice)");let V="Found "+m.get(n)+", when expected "+E;this.Error(V);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case O.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(e),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case O.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(e);break;case O.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let m=[],E=0;for(let j=this.state.outputStream.length-1;j>=0;--j){let U=this.state.outputStream[j];E++;let Et=(0, N.asOrNull)(U,O.ControlCommand);if(Et!=null){if(Et.commandType==O.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}U instanceof x.StringValue&&m.push(U);}this.state.PopFromOutputStream(E);let V=new ye.StringBuilder;for(let j of m.reverse())V.Append(j.toString());let _t=new ts.Tag(this.state.CleanOutputWhitespace(V.toString()));this.state.PushEvaluationStack(_t);}else this.state.PushToOutputStream(e);break}case O.ControlCommand.CommandType.EndString:{let m=[],E=[],V=0;for(let j=this.state.outputStream.length-1;j>=0;--j){let U=this.state.outputStream[j];V++;let Et=(0, N.asOrNull)(U,O.ControlCommand);if(Et&&Et.commandType==O.ControlCommand.CommandType.BeginString)break;U instanceof ts.Tag&&E.push(U),U instanceof x.StringValue&&m.push(U);}this.state.PopFromOutputStream(V);for(let j of E)this.state.PushToOutputStream(j);m=m.reverse();let _t=new ye.StringBuilder;for(let j of m)_t.Append(j.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new x.StringValue(_t.toString()));break}case O.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new x.IntValue(a));break;case O.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new x.IntValue(this.state.currentTurnIndex+1));break;case O.ControlCommand.CommandType.TurnsSince:case O.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof x.DivertTargetValue)){let m="";s instanceof x.IntValue&&(m=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+m);break}let o=(0, N.asOrThrows)(s,x.DivertTargetValue),l=(0, N.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,st.Container),u;l!=null?e.commandType==O.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(e.commandType==O.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+e.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new x.IntValue(u));break;case O.ControlCommand.CommandType.Random:{let m=(0, N.asOrNull)(this.state.PopEvaluationStack(),x.IntValue),E=(0, N.asOrNull)(this.state.PopEvaluationStack(),x.IntValue);if(E==null||!(E instanceof x.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(m==null||!(m instanceof x.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(m.value===null)return (0, L.throwNullException)("maxInt.value");if(E.value===null)return (0, L.throwNullException)("minInt.value");let V=m.value-E.value+1;(!isFinite(V)||V>Number.MAX_SAFE_INTEGER)&&(V=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),V<=0&&this.Error("RANDOM was called with minimum as "+E.value+" and maximum as "+m.value+". The maximum must be larger");let _t=this.state.storySeed+this.state.previousRandom,U=new ko.PRNG(_t).next(),Et=U%V+E.value;this.state.PushEvaluationStack(new x.IntValue(Et)),this.state.previousRandom=U;break}case O.ControlCommand.CommandType.SeedRandom:let h=(0, N.asOrNull)(this.state.PopEvaluationStack(),x.IntValue);if(h==null||!(h instanceof x.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, L.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new Vn.Void);break;case O.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new x.IntValue(c));break;case O.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new x.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=true,this.state.currentPointer=ie.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(),x.IntValue),g=(0, N.asOrThrows)(this.state.PopEvaluationStack(),x.StringValue);if(p===null)throw new ve.StoryException("Passed non-integer when creating a list element from a numerical value.");let y=null;if(this.listDefinitions===null)return (0, L.throwNullException)("this.listDefinitions");let b=this.listDefinitions.TryListGetDefinition(g.value,null);if(b.exists){if(p.value===null)return (0, L.throwNullException)("minInt.value");let m=b.result.TryGetItemWithValue(p.value,Fn.InkListItem.Null);m.exists&&(y=new x.ListValue(m.result,p.value));}else throw new ve.StoryException("Failed to find LIST called "+g.value);y==null&&(y=new x.ListValue),this.state.PushEvaluationStack(y);break;case O.ControlCommand.CommandType.ListRange:let _=(0, N.asOrNull)(this.state.PopEvaluationStack(),x.Value),d=(0, N.asOrNull)(this.state.PopEvaluationStack(),x.Value),S=(0, N.asOrNull)(this.state.PopEvaluationStack(),x.ListValue);if(S===null||d===null||_===null)throw new ve.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(S.value===null)return (0, L.throwNullException)("targetList.value");let v=S.value.ListWithSubRange(d.valueObject,_.valueObject);this.state.PushEvaluationStack(new x.ListValue(v));break;case O.ControlCommand.CommandType.ListRandom:{let m=this.state.PopEvaluationStack();if(m===null)throw new ve.StoryException("Expected list for LIST_RANDOM");let E=m.value,V=null;if(E===null)throw (0, L.throwNullException)("list");if(E.Count==0)V=new Fn.InkList;else {let _t=this.state.storySeed+this.state.previousRandom,U=new ko.PRNG(_t).next(),Et=U%E.Count,_e=E.entries();for(let nl=0;nl<=Et-1;nl++)_e.next();let el=_e.next().value,qn={Key:Fn.InkListItem.fromSerializedKey(el[0]),Value:el[1]};if(qn.Key.originName===null)return (0, L.throwNullException)("randomItem.Key.originName");V=new Fn.InkList(qn.Key.originName,this),V.Add(qn.Key,qn.Value),this.state.previousRandom=U;}this.state.PushEvaluationStack(new x.ListValue(V));break}default:this.Error("unhandled ControlCommand: "+e);break}return true}else if(t instanceof mg.VariableAssignment){let e=t,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(e,n),true}else if(t instanceof Cg.VariableReference){let e=t,n=null;if(e.pathForCount!=null){let i=e.containerForCount,a=this.state.VisitCountForContainer(i);n=new x.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(e.name),n==null&&(this.Warning("Variable not found: '"+e.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),n=new x.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(t instanceof vg.NativeFunctionCall){let e=t,n=this.state.PopEvaluationStack(e.numberOfParameters),i=e.Call(n);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(t,e=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(t,n),e)this.ResetCallstack();else if(this.state.callStack.currentElement.type==At.PushPopType.Function){let i="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(i="("+a.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+t+`) - this is almost certainly not not what you want! Full stack trace:
|
|
28
|
+
`+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new Fo.Path(t));}IfAsyncWeCant(t){if(this._asyncContinueActive)throw new Error("Can't "+t+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(t,e=true){this.state.SetChosenPath(t,e),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(t){t=t;let e=this.currentChoices;this.Assert(t>=0&&t<e.length,"choice out of range");let n=e[t];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, L.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, L.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(t){try{return this.KnotContainerWithName(t)!=null}catch{return false}}EvaluateFunction(t,e=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(t,e),this.IfAsyncWeCant("evaluate a function"),t==null)throw new Error("Function is null");if(t==""||t.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(t);if(i==null)throw new Error("Function doesn't exist: '"+t+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,e);let s=new ye.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let l=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(t,e,o,l),n?{returned:l,output:o}:l}EvaluateExpression(t){let e=this.state.callStack.elements.length;this.state.callStack.Push(At.PushPopType.Tunnel),this._temporaryEvaluationContainer=t,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>e&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(t,e){if(t===null)return (0, L.throwNullException)("funcName");let n=this._externals.get(t),i=null,a=typeof n<"u";if(a&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+t+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+t+"()"),a&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(t),this.Assert(i!==null,"Trying to call EXTERNAL function '"+t+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(At.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=ie.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+t+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let u=0;u<e;++u){let c=(0, N.asOrThrows)(this.state.PopEvaluationStack(),x.Value).valueObject;s.push(c);}s.reverse();let o=n.function(s),l=null;o!=null?(l=x.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new Vn.Void,this.state.PushEvaluationStack(l);}BindExternalFunctionGeneral(t,e,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(t),"Function '"+t+"' has already been bound."),this._externals.set(t,{function:e,lookAheadSafe:n});}TryCoerce(t){return t}BindExternalFunction(t,e,n=false){this.Assert(e!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(t,i=>{this.Assert(i.length>=e.length,"External function expected "+e.length+" arguments");let a=[];for(let s=0,o=i.length;s<o;s++)a[s]=this.TryCoerce(i[s]);return e.apply(null,a)},n);}UnbindExternalFunction(t){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(t),"Function '"+t+"' has not been bound."),this._externals.delete(t);}ValidateExternalBindings(){let t=null,e=null,n=arguments[1]||new Set;if(arguments[0]instanceof st.Container&&(t=arguments[0]),arguments[0]instanceof Io.InkObject&&(e=arguments[0]),t===null&&e===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=n.size>1?"s":"",i+=": '",i+=Array.from(n).join("', '"),i+="' ",i+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(i);}else if(t!=null){for(let i of t.content){let a=i;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(i,n);}for(let[,i]of t.namedContent)this.ValidateExternalBindings((0, N.asOrNull)(i,Io.InkObject),n);}else if(e!=null){let i=(0, N.asOrNull)(e,Mu.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, L.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.add(a);}}}ObserveVariable(t,e){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(t))throw new Error("Cannot observe variable '"+t+"' because it wasn't declared in the ink story.");this._variableObservers.has(t)?this._variableObservers.get(t).push(e):this._variableObservers.set(t,[e]);}ObserveVariables(t,e){for(let n=0,i=t.length;n<i;n++)this.ObserveVariable(t[n],e[n]);}RemoveVariableObserver(t,e){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(e!=null){if(this._variableObservers.has(e))if(t!=null){let n=this._variableObservers.get(e);n!=null&&(n.splice(n.indexOf(t),1),n.length===0&&this._variableObservers.delete(e));}else this._variableObservers.delete(e);}else if(t!=null){let n=this._variableObservers.keys();for(let i of n){let a=this._variableObservers.get(i);a!=null&&(a.splice(a.indexOf(t),1),a.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(t,e){if(this._variableObservers===null)return;let n=this._variableObservers.get(t);if(typeof n<"u"){if(!(e instanceof x.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, N.asOrThrows)(e,x.Value);for(let a of n)a(t,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(t){return this.TagsAtStartOfFlowContainerWithPathString(t)}TagsAtStartOfFlowContainerWithPathString(t){let e=new Fo.Path(t),n=this.ContentAtPath(e).container;if(n===null)return (0, L.throwNullException)("flowContainer");for(;;){let s=n.content[0];if(s instanceof st.Container)n=s;else break}let i=false,a=null;for(let s of n.content){let o=(0, N.asOrNull)(s,O.ControlCommand);if(o!=null)o.commandType==O.ControlCommand.CommandType.BeginTag?i=true:o.commandType==O.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let l=(0, N.asOrNull)(s,x.StringValue);l!==null?(a===null&&(a=[]),l.value!==null&&a.push(l.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let t=new ye.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}BuildStringOfContainer(t){let e=new ye.StringBuilder;return t.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=ie.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let e=false;this.state.callStack.CanPop(At.PushPopType.Function)?(this.state.PopCallStack(At.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new Vn.Void),e=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),e=true):this.state.TryExitFunctionEvaluationFromGame(),e&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let t=true,e=this.state.callStack.currentElement.currentPointer.copy();if(e.index++,e.container===null)return (0, L.throwNullException)("pointer.container");for(;e.index>=e.container.content.length;){t=false;let n=(0, N.asOrNull)(e.container.parent,st.Container);if(!(n instanceof st.Container))break;let i=n.content.indexOf(e.container);if(i==-1)break;if(e=new ie.Pointer(n,i),e.index++,t=true,e.container===null)return (0, L.throwNullException)("pointer.container")}return t||(e=ie.Pointer.Null),this.state.callStack.currentElement.currentPointer=e.copy(),t}TryFollowDefaultInvisibleChoice(){let t=this._state.currentChoices,e=t.filter(i=>i.isInvisibleDefault);if(e.length==0||t.length>e.length)return false;let n=e[0];return n.targetPath===null?(0, L.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, L.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,false),true)}NextSequenceShuffleIndex(){let t=(0, N.asOrNull)(this.state.PopEvaluationStack(),x.IntValue);if(!(t instanceof x.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let e=this.state.currentPointer.container;if(e===null)return (0, L.throwNullException)("seqContainer");if(t.value===null)return (0, L.throwNullException)("numElementsIntVal.value");let n=t.value,a=(0, N.asOrThrows)(this.state.PopEvaluationStack(),x.IntValue).value;if(a===null)return (0, L.throwNullException)("seqCount");let s=a/n,o=a%n,l=e.path.toString(),u=0;for(let p=0,g=l.length;p<g;p++)u+=l.charCodeAt(p)||0;let h=u+s+this.state.storySeed,c=new ko.PRNG(Math.floor(h)),f=[];for(let p=0;p<n;++p)f.push(p);for(let p=0;p<=o;++p){let g=c.next()%f.length,y=f[g];if(f.splice(g,1),p==o)return y}throw new Error("Should never reach here")}Error(t,e=false){let n=new ve.StoryException(t);throw n.useEndLineNumber=e,n}Warning(t){this.AddError(t,true);}AddError(t,e=false,n=false){let i=this.currentDebugMetadata,a=e?"WARNING":"ERROR";if(i!=null){let s=n?i.endLineNumber:i.startLineNumber;t="RUNTIME "+a+": '"+i.fileName+"' line "+s+": "+t;}else this.state.currentPointer.isNull?t="RUNTIME "+a+": "+t:t="RUNTIME "+a+": ("+this.state.currentPointer+"): "+t;this.state.AddError(t,e),e||this.state.ForceEnd();}Assert(t,e=null){if(t==false)throw e==null&&(e="Story assert"),new Error(e+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let t,e=this.state.currentPointer;if(!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(e=this.state.callStack.elements[n].currentPointer,!e.isNull&&e.Resolve()!==null&&(t=e.Resolve().debugMetadata,t!==null))return t;for(let n=this.state.outputStream.length-1;n>=0;--n)if(t=this.state.outputStream[n].debugMetadata,t!==null)return t;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};Se.Story=$e;$e.inkVersionCurrent=21;(function(r){(function(e){e[e.NoChange=0]="NoChange",e[e.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",e[e.NewlineRemoved=2]="NewlineRemoved";})(r.OutputStateChange||(r.OutputStateChange={}));})($e||(Se.Story=$e={}));});var Ju=b(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.Story=void 0;var _g=Qn(),Eg=Di(),es=H(),ns=it(),kn=Kn(),is=qt(),$u=Re(),wg=eo(),xg=fr(),Tg=oo(),Pg=Pn(),Je=Ut(),Og=Zt(),Ng=Yt(),Rn=D(),Ag=vn(),Ig=yn(),Vg=ge(),rs=class r extends is.FlowBase{get flowLevel(){return $u.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(t,e=false){super(null,t,null,false,e),this._errorHandler=null,this._hadError=false,this._hadWarning=false,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=false,this.ExportRuntime=(n=null)=>{var i,a;this._errorHandler=n,this.constants=new Map;for(let h of this.FindAll(Eg.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let f=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(f,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(xg.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 s=this.runtimeObject,o=new es.Container;o.AddContent(ns.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 Ng.VariableAssignment(h,true);f.isGlobal=true,o.AddContent(f);}o.AddContent(ns.ControlCommand.EvalEnd()),o.AddContent(ns.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(ns.ControlCommand.Done());let u=new Pg.Story(s,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,a=null)=>{let s=null;if(n)return (s=this._listDefs.get(n))?s.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,false):(o=h,l=u));}return o}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let a of n.content){let s=(0, Rn.asOrNull)(a,es.Container);s&&i.add(s);}if(n.namedContent)for(let[,a]of n.namedContent){let s=(0, Rn.asOrNull)(a,es.Container);s&&i.add(s);}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, Rn.asOrNull)(n.parent,es.Container);if(i){let a=i.content.indexOf(n);i.content.splice(a,1);let s=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),i.InsertContent(o,a),a+=1;}},this.Error=(n,i,a)=>{let s=a?kn.ErrorType.Warning:kn.ErrorType.Error,o="";if(i instanceof _g.AuthorWarning?(o+="TODO: ",s=kn.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,s);else throw new Error(n);this._hadError=s===kn.ErrorType.Error,this._hadWarning=s===kn.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=n=>this.externals.has(n),this.AddExternal=n=>{this.externals.has(n.name)?this.Error(`Duplicate EXTERNAL definition of '${n.name}'`,n,false):n.name&&this.externals.set(n.name,n);},this.DontFlattenContainer=n=>{this._dontFlattenContainers.add(n);},this.NameConflictError=(n,i,a,s)=>{n.Error(`${s} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,i,a,s="")=>{var o;let l=s||n.typeName;if(r.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(Ig.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||"",$u.FlowLevel.Knot),h=(0, Rn.asOrNull)(u,is.FlowBase);if(h&&(h!==n||a===Je.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,l);return}if(a<Je.SymbolType.List)return;for(let[g,y]of this._listDefs)if(i?.name===g&&n!==y&&y.variableAssignment!==n&&this.NameConflictError(n,i?.name,y,l),!(n instanceof Tg.ListElementDefinition))for(let b of y.itemDefinitions)i?.name===b.name&&this.NameConflictError(n,i?.name||"",b,l);if(a<=Je.SymbolType.Var)return;let c=i?.name&&this.variableDeclarations.get(i?.name)||null;if(c&&c!==n&&c.isGlobalDeclaration&&c.listDefinition==null&&this.NameConflictError(n,i?.name||"",c,l),a<Je.SymbolType.SubFlowAndWeave)return;let p=new Vg.Path(i).ResolveFromContext(n);if(p&&p!==n){this.NameConflictError(n,i?.name||"",p,l);return}if(!(a<Je.SymbolType.Arg)&&a!==Je.SymbolType.Arg){let g=(0, Rn.asOrNull)(n,is.FlowBase);if(g||(g=(0, Ag.ClosestFlowBase)(n)),g&&g.hasParameters&&g.args){for(let y of g.args)if(((o=y.identifier)===null||o===void 0?void 0:o.name)===i?.name){n.Error(`${l} '${i}': name has already been used for a argument to ${g.identifier} on ${g.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(t){super.PreProcessTopLevelObjects(t);let e=[];for(let n of t)if(n instanceof wg.IncludedFile){let i=n,a=t.indexOf(n);if(t.splice(a,1),i.includedStory){let s=[],o=i.includedStory;if(o.content!=null){for(let l of o.content)l instanceof is.FlowBase?e.push(l):s.push(l);s.push(new Og.Text(`
|
|
29
|
+
`)),t.splice(a,0,...s);}}continue}t.splice(0,0,...e);}};ss.Story=rs;rs.IsReservedKeyword=r=>{switch(r){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var Hu=b(as=>{Object.defineProperty(as,"__esModule",{value:true});as.StringExpression=void 0;var Uu=it(),Fg=xt(),kg=Zt(),Rg=D(),Ro=class r extends Fg.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof kg.Text))}constructor(t){super(),this.GenerateIntoContainer=e=>{e.AddContent(Uu.ControlCommand.BeginString());for(let n of this.content)e.AddContent(n.runtimeObject);e.AddContent(Uu.ControlCommand.EndString());},this.toString=()=>{let e="";for(let n of this.content)e+=n;return e},this.AddContent(t);}get typeName(){return "String"}Equals(t){let e=(0, Rg.asOrNull)(t,r);if(e===null||!this.isSingleString||!e.isSingleString)return false;let n=this.toString(),i=e.toString();return n===i}};as.StringExpression=Ro;});var zu=b(Ue=>{Object.defineProperty(Ue,"__esModule",{value:true});Ue.LegacyTag=Ue.Tag=void 0;var Lg=G(),Ku=it(),Lo=class extends Lg.ParsedObject{constructor(t,e=false){super(),this.GenerateRuntimeObject=()=>this.isStart?Ku.ControlCommand.BeginTag():Ku.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=t,this.inChoice=e;}get typeName(){return "Tag"}};Ue.Tag=Lo;var Dg=Xa(),Do=class extends Dg.Wrap{constructor(t){super(t);}get typeName(){return "Tag"}};Ue.LegacyTag=Do;});var Xu=b(os=>{Object.defineProperty(os,"__esModule",{value:true});os.DefaultFileHandler=void 0;var Wo=class{constructor(t){this.rootPath=t,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};os.DefaultFileHandler=Wo;});var Bo=b(cs=>{Object.defineProperty(cs,"__esModule",{value:true});cs.InkParser=void 0;var Wg=yl(),jg=Qn(),qg=Js(),Ft=Vl(),Z=fn(),Mg=ke(),Bg=Ml(),Gg=ki(),Ln=xa(),vt=Ki(),$g=Di(),ls=uu(),Jg=hu(),be=We(),jo=De(),Ug=xt(),Hg=cu(),Yu=du(),us=yn(),Kg=Cn(),zg=fu(),Xg=Pr(),hs=gu(),Qu=eo(),Yg=mu(),Qg=ro(),Zu=vu(),Zg=fr(),tm=oo(),em=ba(),th=G(),nm=ge(),eh=da(),nh=ka(),Q=Ia(),ht=lo(),im=ho(),ih=Ju(),Dn=Hu(),Ht=na(),He=zu(),Kt=Zt(),rh=La(),qo=Ba(),Mo=qe(),rm=Gs(),re=D(),Wn=Ji(),Ke=pi(),sh=Kn(),sm=Xu(),q=class r extends Ht.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(t){this._fileHandler=t;}constructor(t,e=null,n=null,i=null,a=null){if(super(t),this.ParseStory=()=>{let s=this.StatementsAtLevel(ht.StatementLevel.Top);return new ih.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let l=this.Parse(s);if(l===null)return null;let u=[];u.push(l);do{let h=this.BeginRule();if(o()===null){this.FailRule(h);break}let f=this.Parse(s);if(f===null){this.FailRule(h);break}this.SucceedRule(h),u.push(f);}while(true);return u},this.CreateDebugMetadata=(s,o)=>{let l=new Jg.DebugMetadata;return l.startLineNumber=(s?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(s?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(s,o,l)=>{let u=(0, re.asOrNull)(s,th.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let h=Array.isArray(s)?s:null;if(h!==null)for(let f of h)(0, re.asOrNull)(f,th.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,l)));let c=(0, re.asOrNull)(s,Wn.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(s,o,l=0,u=false)=>{let c=u?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${l+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,u?sh.ErrorType.Warning:sh.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
|
|
30
|
+
\r`);return o?new jg.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=r.ListAllCharacterRanges();for(let l of o)s.AddCharacters(l.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let s=true,o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!o){if(o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),o===null)return null;s=false;}let l=this.Parse(this.BracketedName);this.Whitespace(),l!=null&&this.Newline();let u=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let h=null,c=this.Parse(this.MixedTextAndLogic);c&&(h=new vt.ContentList(c));let f=null,p=null,g=this.ParseString("[")!==null;if(g){this.EndTagIfNecessary(h);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(f=new vt.ContentList(d)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let S=this.Parse(this.MixedTextAndLogic);S!==null&&(p=new vt.ContentList(S));}this.Whitespace(),this.EndTagIfNecessary(p??h);let y=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let b=!h&&!p&&!f;if(b&&y===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&g&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),p||(p=new vt.ContentList),this.EndTagIfNecessary(p),y!==null)for(let d of y){let S=(0, re.asOrNull)(d,be.Divert);S&&S.isEmpty||p.AddContent(d);}p.AddContent(new Kt.Text(`
|
|
31
|
+
`));let _=new Mg.Choice(h,f,p);return l&&(_.identifier=l),_.indentationDepth=o.length,_.hasWeaveStyleInlineBrackets=g,_.condition=u,_.onceOnly=s,_.isInvisibleDefault=b,_},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new em.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Ht.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let s=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(s),this.Expect(this.String("}"),"closing '}' for choice condition"),s},this.Gather=()=>{let s=this.Parse(this.GatherDashes);if(s===null)return null;let o=Number(s),l=this.Parse(this.BracketedName),u=new Kg.Gather(l,o);return this.Newline(),u},this.GatherDashes=()=>{this.Whitespace();let s=0;for(;this.ParseDashNotArrow()!==null;)s+=1,this.Whitespace();return s===0?null:s},this.ParseDashNotArrow=()=>{let s=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(s):this.FailRule(s)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),s)},this.InnerConditionalContent=s=>{if(s===void 0){let c=this.Parse(this.ConditionExpression),f=this.Parse(()=>this.InnerConditionalContent(c));return f===null?null:f}let o,l=s!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let c=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);if(c!==null){o=[new Ln.ConditionalSingleBranch(c)];let p=this.Parse(this.SingleMultilineCondition);p&&(p.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",p),p.isElse=true),o.push(p));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let c=new Ln.ConditionalSingleBranch(null);c.isTrueBranch=true,o.unshift(c);}if(s){let c=false;for(let f=0;f<o.length;++f){let p=o[f],g=f===o.length-1;p.ownExpression?(p.matchingEquality=true,c=true):c&&g?(p.matchingEquality=true,p.isElse=true):!g&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",p):f===0?p.isTrueBranch=true:p.isElse=true;}}else {for(let c=0;c<o.length;++c){let f=o[c],p=c===o.length-1;if(f.ownExpression===null)if(p)f.isElse=true;else if(f.isElse){let g=o[o.length-1];g.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",g):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",f);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",f);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let c of o)c.isInline=u;return new Gg.Conditional(s,o)},this.InlineConditionalBranches=()=>{let s=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(s===null||s.length===0)return null;let o=[];if(s.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let l=new Ln.ConditionalSingleBranch(s[0]);if(l.isTrueBranch=true,o.push(l),s.length>1){let u=new Ln.ConditionalSingleBranch(s[1]);u.isElse=true,o.push(u);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineCondition);return s===null?null:(this.MultilineWhitespace(),s)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=null,o=this.Parse(this.ElseExpression)!==null;o||(s=this.Parse(this.ConditionExpression));let l=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);s===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new Kt.Text("")]),this.MultilineWhitespace();let u=new Ln.ConditionalSingleBranch(l);return u.ownExpression=s,u.isElse=o,u},this.ConditionExpression=()=>{let s=this.Parse(this.Expression);return s===null||(this.DisallowIncrement(s),this.Whitespace(),this.ParseString(":")===null)?null:s},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:Ht.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let l=s.length-1,u=s[l];if(u instanceof Kt.Text){let h=u;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),o?h.text+=" ":h.text.length===0&&(s.splice(l,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof be.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof He.Tag&&s[0].isStart||s.push(new Kt.Text(`
|
|
32
|
+
`)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),s)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let o=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let l=this.Parse(this.MultiDivert);l!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...l));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),l){let u=this.ParseSingleCharacter();s+=u;}}else break}while(true);return s!==null?new Kt.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new Z.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new Z.CharacterSet(`{}|
|
|
33
|
+
\r\\#`),this._notTextEndCharactersChoice=new Z.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new Z.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let s=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let l=this.ParseUntil(s,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;s=[],this.EndTagIfNecessary(s);for(let u=0;u<l.length;++u)if(u%2===0){if(l[u]==="->->"){u===0||u===l.length-1||u===l.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let f=new rh.TunnelOnwards;if(u<l.length-1){let p=(0, re.asOrNull)(l[u+1],be.Divert);f.divertAfter=p;}s.push(f);break}}else {let c=l[u];u<l.length-1&&(c.isTunnel=true),s.push(c);}if(s.length===0&&l.length===1){let u=new be.Divert(null);u.isEmpty=true,s.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new be.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new nm.Path(s);return new be.Divert(l,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof rh.TunnelOnwards)return null;let l=s[0];return l.isTunnel?null:l},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let s=0;for(;this.ParseString("->")!==null;)s+=1;return s===0?null:s===1?"->":(s===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let s=this.ParseTempKeyword();this.Whitespace();let o=null;if(s?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let l=this.ParseString("+")!==null,u=this.ParseString("-")!==null;if(l&&u&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return s&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return l||u?new hs.IncDecExpression(o,h,l):new qo.VariableAssignment({variableIdentifier:o,assignedExpression:h,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof hs.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let s=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(s),true):(this.FailRule(s),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new eh.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>s){let h=`right side of '${u.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(o,u),h);if(c===null)return this.FailRule(l),null;o=this.SucceedRule(l,c);continue}this.FailRule(l);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let s=this.Parse(this.ExpressionDivertTarget);if(s!==null)return s;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&o!==null&&(l=this.ExpressionUnary()),l===null)return null;o!==null&&(l=rm.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof Mo.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new hs.IncDecExpression(c.identifier,h);}}return l},this.ExpressionNot=()=>{let s=this.Identifier();return s==="not"?s:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let s=this.Parse(this.SingleDivert);return !s||s&&s.isThread?null:(this.Whitespace(),new jo.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new Ke.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new Ke.NumberExpression(s,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let o=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,o===null?o=[new Kt.Text("")]:o.find(l=>l instanceof be.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Dn.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new Ke.NumberExpression(true,"bool"):s==="false"?new Ke.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new us.FunctionCall(s,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,s);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let s=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return s===null||ih.Story.IsReservedKeyword(s[0].name)?null:new Mo.VariableReference(s)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let s=this.Parse(this.Expression);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),s)},this.ExpressionInfixRight=(s,o)=>{if(!s)return null;this.Whitespace();let l=this.Parse(()=>this.Expression(o.precedence));return l?new qg.BinaryExpression(s,l,o.type):null},this.ParseInfixOperator=()=>{for(let s of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(s.type)!==null){if(s.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,s)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let s=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new Zu.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${l?.name}`;}return this.Whitespace(),s},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(s,o,l=false)=>{let u=new Yg.InfixOperator(s,o,l);this._binaryOperators.push(u),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,s.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let s=this.Expect(()=>this.ParseUntilCharactersFromString(`
|
|
34
|
+
\r`),"filename for include statement");s=s.replace(new RegExp(/[ \t]+$/g),"");let o=this.fileHandler.ResolveInkFilename(s);if(this.FilenameIsAlreadyOpen(o))return this.Error(`Recursive INCLUDE detected: '${o}' is already open.`),this.ParseUntilCharactersFromString(`\r
|
|
35
|
+
`),new Qu.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o);}catch(h){this.Error(`Failed to load: '${s}'.
|
|
36
|
+
Error:${h}`);}return u!=null&&(l=new r(u,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new Qu.IncludedFile(l)},this.FilenameIsAlreadyOpen=s=>this._rootParser._openFilenames.includes(s),this.AddOpenFilename=s=>{this._rootParser._openFilenames.push(s);},this.RemoveOpenFilename=s=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(s),1);},this.KnotDefinition=()=>{let s=this.Parse(this.KnotDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(ht.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new Qg.Knot(s.name,l,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,l=s?.name==="function";l?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=s,o===null&&(this.Error(`Expected the name of the ${l?"function":"knot"}`),o=new Wn.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new Yu.FlowDecl(o,u,l)},this.KnotTitleEquals=()=>{let s=this.ParseCharactersFromString("=");return s===null||s.length<=1?null:s},this.StitchDefinition=()=>{let s=this.Parse(this.StitchDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(ht.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new im.Stitch(s.name,l,s.args,s.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let s=this.ParseString("function")!==null;s&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new Yu.FlowDecl(o,l,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new Z.CharacterSet("="),null),[new Kt.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),s===null&&(s=[]),s},this.FlowDeclArgument=()=>{let s=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(s==null&&l===null)return null;let u=new Wg.Argument;return o!==null&&(u.isDivertTarget=true),s!==null&&s.name==="ref"?(l===null&&this.Error("Expected an parameter name after 'ref'"),u.identifier=l,u.isByReference=true):(u.isDivertTarget?u.identifier=l:u.identifier=s,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},this.ExternalDeclaration=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new Wn.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(re.filterUndef);return new Hg.ExternalDeclaration(o,u)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let s=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(s,"expression after '~'",this.SkipToNextLine);if(o===null)return new vt.ContentList;o instanceof Ug.Expression&&!(o instanceof us.FunctionCall||o instanceof hs.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
|
|
37
|
+
~ return
|
|
38
|
+
~ var x = blah
|
|
39
|
+
~ x++
|
|
40
|
+
~ myFunction()`);let l=(0, re.asOrNull)(o,us.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(us.FunctionCall)()!==null&&(o=new vt.ContentList(o,new Kt.Text(`
|
|
41
|
+
`))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u?(u instanceof Ke.NumberExpression||u instanceof Dn.StringExpression||u instanceof jo.DivertTarget||u instanceof Mo.VariableReference||u instanceof Zu.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 Dn.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new qo.VariableAssignment({assignedExpression:u,isGlobalDeclaration:true,variableIdentifier:o})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let l=this.Expect(this.ListDefinition,"list item names");return l?(l.identifier=new Wn.Identifier(o.name),new qo.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new Zg.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let u=null;if(this.ParseString("=")!==null){this.Whitespace();let h=this.Expect(this.ExpressionInt,"value to be assigned to list item");h!==null&&(u=h.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new tm.ListElementDefinition(l,s,u)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l instanceof Ke.NumberExpression||l instanceof jo.DivertTarget||l instanceof Dn.StringExpression?l instanceof Dn.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 $g.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new zg.Glue(new Xg.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let l=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(l===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(l);let u=(0, re.asOrNull)(l,vt.ContentList);return u||(u=new vt.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new nh.Sequence(u,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let l=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let u of l){let h=this.BeginRule(),c=this.ParseObject(u);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let s=this.Parse(this.Expression);return s&&(s.outputWhenComplete=true),s},this.IdentifierWithMetadata=()=>{let s=this.Identifier();return s===null?null:new Wn.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let l of s)if(!(l>="0"&&l<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new Z.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=Q.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new nh.Sequence(l,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case Q.SequenceType.Once:case Q.SequenceType.Cycle:case Q.SequenceType.Stopping:case Q.SequenceType.Shuffle:case Q.SequenceType.Shuffle|Q.SequenceType.Stopping:case Q.SequenceType.Shuffle|Q.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),Q.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new Z.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":s|=Q.SequenceType.Once;break;case "&":s|=Q.SequenceType.Cycle;break;case "~":s|=Q.SequenceType.Shuffle;break;case "$":s|=Q.SequenceType.Stopping;break}return s===0?null:s},this.SequenceTypeWordAnnotation=()=>{let s=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(s===null||s.length===0||this.ParseString(":")===null)return null;let o=0;for(let l of s)o|=l;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=Q.SequenceType.Once;break;case "cycle":s=Q.SequenceType.Cycle;break;case "shuffle":s=Q.SequenceType.Shuffle;break;case "stopping":s=Q.SequenceType.Stopping;break}return s===null?null:s},this.InnerSequenceObjects=()=>{let s=this.Parse(this.Newline)!==null,o=null;return s?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let s=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(s===null)return null;let o=[],l=false;for(let u of s)if(u==="|")l||o.push(new vt.ContentList),l=false;else {let h=u;h===null?this.Error(`Expected content, but got ${u} (this is an ink compiler bug!)`):o.push(new vt.ContentList(h)),l=true;}return l||o.push(new vt.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineSequenceElement);return s===null?null:s},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=this.StatementsAtLevel(ht.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new Kt.Text(`
|
|
42
|
+
`)),new vt.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===ht.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(s),()=>this.StatementsBreakForLevel(s))),this.StatementAtLevel=s=>{let o=this._statementRulesAtLevel[s],l=this.OneOf(o);return s===ht.StatementLevel.Top&&l instanceof eh.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let s=Object.values(ht.StatementLevel);this._statementRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]);for(let o of s){let l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=ht.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>ht.StatementLevel.InnerBlock&&l.push(this.Gather),o>=ht.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<=ht.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=ht.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=ht.StatementLevel.InnerBlock&&(u.push(this.ParseDashNotArrow),u.push(this.String("}"))),this._statementRulesAtLevel[o]=l,this._statementBreakRulesAtLevel[o]=u;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
|
|
43
|
+
\r`),this.ParseNewline(),Ht.ParseSuccess),this.Line=s=>()=>{let o=this.ParseObject(s);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let s=null;if(this.tagActive){let o=new vt.ContentList;o.AddContent(new He.Tag(false)),o.AddContent(new He.Tag(true)),s=o;}else s=new He.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new Z.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Ht.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Ht.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?Ht.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Ht.ParseSuccess:null,this.Spaced=s=>()=>{this.Whitespace();let o=this.ParseObject(s);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let s=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)s=true;return s?Ht.ParseSuccess:null},this.MultiSpaced=s=>()=>{this.AnyWhitespace();let o=this.ParseObject(s);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=e,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new sm.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=i;}PreProcessInputString(t){return new Bg.CommentEliminator(t).Process()}get parsingStringExpression(){return this.GetFlag(Number(ls.CustomFlags.ParsingString))}set parsingStringExpression(t){this.SetFlag(Number(ls.CustomFlags.ParsingString),t);}get tagActive(){return this.GetFlag(Number(ls.CustomFlags.TagActive))}set tagActive(t){this.SetFlag(Number(ls.CustomFlags.TagActive),t);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new Z.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(t){this.tagActive&&(t!=null&&(t instanceof vt.ContentList?t.AddContent(new He.Tag(false)):t.push(new He.Tag(false))),this.tagActive=false);}};cs.InkParser=q;q.LatinBasic=Ft.CharacterRange.Define("A","z",new Z.CharacterSet().AddRange("[","`"));q.LatinExtendedA=Ft.CharacterRange.Define("\u0100","\u017F");q.LatinExtendedB=Ft.CharacterRange.Define("\u0180","\u024F");q.Greek=Ft.CharacterRange.Define("\u0370","\u03FF",new Z.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));q.Cyrillic=Ft.CharacterRange.Define("\u0400","\u04FF",new Z.CharacterSet().AddRange("\u0482","\u0489"));q.Armenian=Ft.CharacterRange.Define("\u0530","\u058F",new Z.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));q.Hebrew=Ft.CharacterRange.Define("\u0590","\u05FF",new Z.CharacterSet);q.Arabic=Ft.CharacterRange.Define("\u0600","\u06FF",new Z.CharacterSet);q.Korean=Ft.CharacterRange.Define("\uAC00","\uD7AF",new Z.CharacterSet);q.Latin1Supplement=Ft.CharacterRange.Define("\x80","\xFF",new Z.CharacterSet);q.Chinese=Ft.CharacterRange.Define("\u4E00","\u9FFF",new Z.CharacterSet);q.ListAllCharacterRanges=()=>[q.LatinBasic,q.LatinExtendedA,q.LatinExtendedB,q.Arabic,q.Armenian,q.Cyrillic,q.Greek,q.Hebrew,q.Korean,q.Latin1Supplement,q.Chinese];});var ah=b(ds=>{Object.defineProperty(ds,"__esModule",{value:true});ds.GenerateStoryStats=void 0;var am=ke(),om=We(),lm=Cn(),um=ro(),hm=ho(),cm=Zt();function dm(r){let t=r.FindAll(cm.Text)(),e=0;for(let l of t){let u=0,h=true;for(let c of l.text)c==" "||c==" "||c==`
|
|
44
|
+
`||c=="\r"?h=true:h&&(u++,h=false);e+=u;}let n=r.FindAll(um.Knot)(),i=r.FindAll(hm.Stitch)(),a=r.FindAll(am.Choice)(),s=r.FindAll(lm.Gather)(l=>l.debugMetadata!=null),o=r.FindAll(om.Divert)();return {words:e,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:i.length,gathers:s.length,diverts:o.length-1,choices:a.length}}ds.GenerateStoryStats=dm;});var oh=b(fs=>{Object.defineProperty(fs,"__esModule",{value:true});fs.JsonFileHandler=void 0;var Go=class{constructor(t){this.fileHierarchy=t,this.ResolveInkFilename=e=>{if(Object.keys(this.fileHierarchy).includes(e))return e;throw new Error(`Cannot locate ${e}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=e=>{if(Object.keys(this.fileHierarchy).includes(e))return this.fileHierarchy[e];throw new Error(`Cannot open ${e}.`)};}};fs.JsonFileHandler=Go;});var uh=b(at=>{Object.defineProperty(at,"__esModule",{value:true});at.Compiler=at.Story=at.InkList=at.JsonFileHandler=at.StatementLevel=at.InkParser=at.CompilerOptions=void 0;var fm=Ts(),pm=Cl(),$o=Kn(),gm=Bo(),mm=$(),Cm=D(),vm=ah(),ym=Ts();Object.defineProperty(at,"CompilerOptions",{enumerable:true,get:function(){return ym.CompilerOptions}});var Sm=Bo();Object.defineProperty(at,"InkParser",{enumerable:true,get:function(){return Sm.InkParser}});var bm=lo();Object.defineProperty(at,"StatementLevel",{enumerable:true,get:function(){return bm.StatementLevel}});var _m=oh();Object.defineProperty(at,"JsonFileHandler",{enumerable:true,get:function(){return _m.JsonFileHandler}});var lh=Pn();Object.defineProperty(at,"InkList",{enumerable:true,get:function(){return lh.InkList}});Object.defineProperty(at,"Story",{enumerable:true,get:function(){return lh.Story}});var Jo=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(t,e=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new gm.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, Cm.asOrNull)(i,mm.StringValue);if(a!==null){let s=new pm.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, vm.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let i=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),n>=i&&n<i+s.length)return a;i+=s.length;}return null},this.OnError=(n,i)=>{switch(i){case $o.ErrorType.Author:this._authorMessages.push(n);break;case $o.ErrorType.Warning:this._warnings.push(n);break;case $o.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=t,this._options=e||new fm.CompilerOptions;}};at.Compiler=Jo;});var xh=Object.defineProperty,Th=(r,t,e)=>t in r?xh(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e,yt=(r,t,e)=>Th(r,typeof t!="symbol"?t+"":t,e),ot;(r=>(r.log=(t,...e)=>console.log(`[Pixi\u2019VN Json] ${t}`,...e),r.warn=(t,...e)=>console.warn(`[Pixi\u2019VN Json] ${t}`,...e),r.error=(t,...e)=>console.error(`[Pixi\u2019VN Json] ${t}`,...e),r.info=(t,...e)=>console.info(`[Pixi\u2019VN Json] ${t}`,...e)))(ot||(ot={}));var ct=class W{static init(t){W._loadAssets=t.loadAssets,W._soundOperation=t.soundOperation,W._imageOperation=t.imageOperation,W._videoOperation=t.videoOperation,W._imageContainerOperation=t.imageContainerOperation,W._canvasElementOperation=t.canvasElementOperation,W._setStorageValue=t.setStorageValue,W._narrationOperation=t.narrationOperation,W._tickerOperation=t.tickerOperation,W._effectOperation=t.effectOperation,W._animateOperation=t.animateOperation,W._getLogichValue=t.getLogichValue,W._getConditionalStep=t.getConditionalStep;}static get loadAssets(){return W._loadAssets}static get soundOperation(){return W._soundOperation}static get imageOperation(){return W._imageOperation}static get videoOperation(){return W._videoOperation}static get imageContainerOperation(){return W._imageContainerOperation}static get canvasElementOperation(){return W._canvasElementOperation}static get setStorageValue(){return W._setStorageValue}static get narrationOperation(){return W._narrationOperation}static get tickerOperation(){return W._tickerOperation}static get effectOperation(){return W._effectOperation}static get animateOperation(){return W._animateOperation}static get getLogichValue(){return W._getLogichValue}static get getConditionalStep(){return W._getConditionalStep}};yt(ct,"_loadAssets",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_soundOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_imageOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_videoOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_imageContainerOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_canvasElementOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_setStorageValue",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_narrationOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_tickerOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_effectOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_animateOperation",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_getLogichValue",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")}),yt(ct,"_getConditionalStep",()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new Error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")});var A=ct;var Ph=Object.defineProperty,Oh=(r,t,e)=>t in r?Ph(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e,Cs=(r,t,e)=>Oh(r,typeof t!="symbol"?t+"":t,e),Mn=class P{static t(t){return Array.isArray(t)?t.map(e=>P.translate(`${e}`)):P.translate(`${t}`)}static set beforeToTranslate(t){P._beforeToTranslate=t;}static set translate(t){P._translate=t;}static get translate(){return t=>{let e=t;return P._beforeToTranslate&&(e=P._beforeToTranslate(e)),e=P._translate(e),P._afterToTranslate&&(e=P._afterToTranslate(e)),e}}static set afterToTranslate(t){P._afterToTranslate=t;}static addKey(t,e,n){let i=n.defaultValue||"empty_string";typeof e=="string"&&(e=[e]),Array.isArray(e)&&e.forEach(a=>{t[a]===void 0&&(i==="empty_string"?t[a]="":i==="copy_key"&&(P._beforeToTranslate?t[a]=P._beforeToTranslate(a):t[a]=a));});}static getConditionalsThenElse(t,e=[]){if(typeof t=="object"&&t&&"type"in t)if(t.type==="ifelse")t.then&&P.getConditionalsThenElse(t.then,e),t.else&&P.getConditionalsThenElse(t.else,e);else if(t.type==="stepswitch"){if(t.elements)if(Array.isArray(t.elements))t.elements.forEach(n=>{P.getConditionalsThenElse(n,e);});else if(t.elements.type==="ifelse"){let n=[];P.getConditionalsThenElse(t.elements,n),n.forEach(i=>{e.push(...i);});}else if(t.elements.type==="stepswitch"){let n=[];P.getConditionalsThenElse(t.elements,n),n.forEach(i=>{e.push(...i);});}else P.getConditionalsThenElse(t.elements,e);}else t.type==="resulttocombine"?(t.firstItem&&P.getConditionalsThenElse(t.firstItem,e),t.secondConditionalItem&&t.secondConditionalItem.forEach(n=>{P.getConditionalsThenElse(n,e);})):e.push(t);else t&&e.push(t);return e}static generateJsonTranslation(t,e={},n={}){let{defaultValue:i="copy_key"}=n;return t.forEach(a=>{if(a.choices){let s=[];Array.isArray(a.choices)?s=[a.choices]:s=P.getConditionalsThenElse(a.choices),s.forEach(o=>o.forEach(l=>{if("type"in l){let u=[];l.type==="ifelse"||l.type==="stepswitch"?P.getConditionalsThenElse(l,u):u=[l],u.map(h=>P.getConditionalsThenElse(h.text)).forEach(h=>{Array.isArray(h)&&h.forEach(c=>{Array.isArray(c)?c.forEach(f=>{typeof f=="string"?P.addKey(e,f,{defaultValue:i}):P.getConditionalsThenElse(f).forEach(p=>{Array.isArray(p)?p.forEach(g=>{typeof g=="string"&&P.addKey(e,g,{defaultValue:i});}):typeof p=="string"&&P.addKey(e,p,{defaultValue:i});});}):typeof c=="string"&&P.addKey(e,c,{defaultValue:i});});});}}));}if(a.dialogue){let s=[];Array.isArray(a.dialogue)?s=[a.dialogue]:s=P.getConditionalsThenElse(a.dialogue),s.forEach(o=>{if(typeof o=="string")P.addKey(e,o,{defaultValue:i});else if("text"in o){let l=P.getConditionalsThenElse(o.text);typeof l=="string"&&(l=[l]),l.forEach(u=>{typeof u=="string"?P.addKey(e,u,{defaultValue:i}):P.getConditionalsThenElse(u).forEach(h=>{typeof h=="string"?P.addKey(e,h,{defaultValue:i}):Array.isArray(h)&&h.forEach(c=>{typeof c=="string"?P.addKey(e,c,{defaultValue:i}):P.getConditionalsThenElse(c).forEach(f=>{typeof f=="string"&&P.addKey(e,f,{defaultValue:i});});});});});}});}a.conditionalStep&&P.getConditionalsThenElse(a.conditionalStep).forEach(s=>{Array.isArray(s)?P.generateJsonTranslation(s,e,n):P.generateJsonTranslation([s],e,n);});}),e}};Cs(Mn,"_beforeToTranslate"),Cs(Mn,"_translate",r=>r),Cs(Mn,"_afterToTranslate");var Nh=Mn,tt=Nh;var Vh=Object.create,ys=Object.defineProperty,Fh=Object.getOwnPropertyDescriptor,kh=Object.getOwnPropertyNames,Rh=Object.getPrototypeOf,Lh=Object.prototype.hasOwnProperty,Dh=(r,t,e)=>t in r?ys(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e,sl=(r=>typeof a<"u"?a:typeof Proxy<"u"?new Proxy(r,{get:(t,e)=>(typeof a<"u"?a:t)[e]}):r)(function(r){if(typeof a<"u")return a.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),ol=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Wh=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of kh(t))!Lh.call(r,i)&&i!==e&&ys(r,i,{get:()=>t[i],enumerable:!(n=Fh(t,i))||n.enumerable});return r},jh=(r,t,e)=>(e=r!=null?Vh(Rh(r)):{},Wh(ys(e,"default",{value:r,enumerable:true}),r)),vs=(r,t,e)=>Dh(r,typeof t!="symbol"?t+"":t,e),qh=ol((r,t)=>{(function(e,n){typeof r=="object"?t.exports=r=n():typeof define=="function"&&define.amd?define([],n):e.CryptoJS=n();})(r,function(){var e=e||(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 sl=="function")try{a=sl("crypto");}catch{}var s=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||(function(){function d(){}return function(S){var v;return d.prototype=S,v=new d,d.prototype=null,v}})(),l={},u=l.lib={},h=u.Base=(function(){return {extend:function(d){var S=o(this);return d&&S.mixIn(d),(!S.hasOwnProperty("init")||this.init===S.init)&&(S.init=function(){S.$super.init.apply(this,arguments);}),S.init.prototype=S,S.$super=this,S},create:function(){var d=this.extend();return d.init.apply(d,arguments),d},init:function(){},mixIn:function(d){for(var S in d)d.hasOwnProperty(S)&&(this[S]=d[S]);d.hasOwnProperty("toString")&&(this.toString=d.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),c=u.WordArray=h.extend({init:function(d,S){d=this.words=d||[],S!=i?this.sigBytes=S:this.sigBytes=d.length*4;},toString:function(d){return (d||p).stringify(this)},concat:function(d){var S=this.words,v=d.words,m=this.sigBytes,E=d.sigBytes;if(this.clamp(),m%4)for(var V=0;V<E;V++){var _t=v[V>>>2]>>>24-V%4*8&255;S[m+V>>>2]|=_t<<24-(m+V)%4*8;}else for(var j=0;j<E;j+=4)S[m+j>>>2]=v[j>>>2];return this.sigBytes+=E,this},clamp:function(){var d=this.words,S=this.sigBytes;d[S>>>2]&=4294967295<<32-S%4*8,d.length=n.ceil(S/4);},clone:function(){var d=h.clone.call(this);return d.words=this.words.slice(0),d},random:function(d){for(var S=[],v=0;v<d;v+=4)S.push(s());return new c.init(S,d)}}),f=l.enc={},p=f.Hex={stringify:function(d){for(var S=d.words,v=d.sigBytes,m=[],E=0;E<v;E++){var V=S[E>>>2]>>>24-E%4*8&255;m.push((V>>>4).toString(16)),m.push((V&15).toString(16));}return m.join("")},parse:function(d){for(var S=d.length,v=[],m=0;m<S;m+=2)v[m>>>3]|=parseInt(d.substr(m,2),16)<<24-m%8*4;return new c.init(v,S/2)}},g=f.Latin1={stringify:function(d){for(var S=d.words,v=d.sigBytes,m=[],E=0;E<v;E++){var V=S[E>>>2]>>>24-E%4*8&255;m.push(String.fromCharCode(V));}return m.join("")},parse:function(d){for(var S=d.length,v=[],m=0;m<S;m++)v[m>>>2]|=(d.charCodeAt(m)&255)<<24-m%4*8;return new c.init(v,S)}},y=f.Utf8={stringify:function(d){try{return decodeURIComponent(escape(g.stringify(d)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(d){return g.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=y.parse(d)),this._data.concat(d),this._nDataBytes+=d.sigBytes;},_process:function(d){var S,v=this._data,m=v.words,E=v.sigBytes,V=this.blockSize,_t=V*4,j=E/_t;d?j=n.ceil(j):j=n.max((j|0)-this._minBufferSize,0);var U=j*V,Et=n.min(U*4,E);if(U){for(var _e=0;_e<U;_e+=V)this._doProcessBlock(m,_e);S=m.splice(0,U),v.sigBytes-=Et;}return new c.init(S,Et)},clone:function(){var d=h.clone.call(this);return d._data=this._data.clone(),d},_minBufferSize:0});u.Hasher=b.extend({cfg:h.extend(),init:function(d){this.cfg=this.cfg.extend(d),this.reset();},reset:function(){b.reset.call(this),this._doReset();},update:function(d){return this._append(d),this._process(),this},finalize:function(d){d&&this._append(d);var S=this._doFinalize();return S},blockSize:16,_createHelper:function(d){return function(S,v){return new d.init(v).finalize(S)}},_createHmacHelper:function(d){return function(S,v){return new _.HMAC.init(d,v).finalize(S)}}});var _=l.algo={};return l})(Math);return e});}),Mh=ol((r,t)=>{(function(e,n){typeof r=="object"?t.exports=r=n(qh()):typeof define=="function"&&define.amd?define(["./core"],n):n(e.CryptoJS);})(r,function(e){return (function(){var n=e,i=n.lib,a=i.WordArray,s=i.Hasher,o=n.algo,l=[],u=o.SHA1=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(h,c){for(var f=this._hash.words,p=f[0],g=f[1],y=f[2],b=f[3],_=f[4],d=0;d<80;d++){if(d<16)l[d]=h[c+d]|0;else {var S=l[d-3]^l[d-8]^l[d-14]^l[d-16];l[d]=S<<1|S>>>31;}var v=(p<<5|p>>>27)+_+l[d];d<20?v+=(g&y|~g&b)+1518500249:d<40?v+=(g^y^b)+1859775393:d<60?v+=(g&y|g&b|y&b)-1894007588:v+=(g^y^b)-899497514,_=b,b=y,y=g<<30|g>>>2,g=p,p=v;}f[0]=f[0]+p|0,f[1]=f[1]+g|0,f[2]=f[2]+y|0,f[3]=f[3]+b|0,f[4]=f[4]+_|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=s.clone.call(this);return h._hash=this._hash.clone(),h}});n.SHA1=s._createHelper(u),n.HmacSHA1=s._createHmacHelper(u);})(),e.SHA1});}),Ee;(r=>(r.log=(t,...e)=>console.log(`[Pixi\u2019VN Json] ${t}`,...e),r.warn=(t,...e)=>console.warn(`[Pixi\u2019VN Json] ${t}`,...e),r.error=(t,...e)=>console.error(`[Pixi\u2019VN Json] ${t}`,...e),r.info=(t,...e)=>console.info(`[Pixi\u2019VN Json] ${t}`,...e)))(Ee||(Ee={}));async function Ss(r,t){let e=A.getLogichValue(r);if(e)switch(e.type){case "sound":A.soundOperation(e);break;case "assets":case "bundle":await A.loadAssets(e);break;case "image":await A.imageOperation(e);break;case "video":await A.videoOperation(e);break;case "imagecontainer":await A.imageContainerOperation(e);break;case "canvaselement":await A.canvasElementOperation(e);break;case "value":A.setStorageValue(e);break;case "operationtoconvert":if(t){let n="";e.values.forEach(a=>{if(typeof a=="string")n+=a;else {let s=A.getLogichValue(a);n+=`${s}`;}});let i=await t(n);i&&await Ss(i,t);}break;case "input":case "dialogue":A.narrationOperation(e);break;case "fade":case "move":case "rotate":case "zoom":A.tickerOperation(e);break;case "shake":await A.effectOperation(e);break;case "animate":case "animate-sequence":A.animateOperation(e);break}}async function ll(r,t={}){let{operationStringConvert:e,skipEmptyDialogs:n}=t;if(!Array.isArray(r))if(typeof r=="object"||typeof r=="string")r=[r];else {Ee.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let i=r.map(async s=>{if(typeof s=="string")try{s=JSON.parse(s);}catch(o){Ee.error("Error parsing imported Pixi'VN JSON",o),s={};}return s}),a=(await Promise.all(i)).map(async s=>{let o=[];if(s.initialOperations){s.initialOperations.forEach(u=>{let h=Ss(u,e?c=>e(c,{},{}):void 0);o.push(h);});let l={};[...storage.storage.keys()].forEach((u,h)=>{l[u]=storage.storage.get(u);}),storage.startingStorage=l;}if(s.labels){let l=s.labels;for(let u in l)try{let h=l[u],c=new $h(u,h,void 0,t);RegisteredLabels.add(c);}catch(h){Ee.error(`Error creating JSON label ${u}`,h);}}return Promise.all(o)});await Promise.all(a);}var Bh=jh(Mh()),al="___param___";function Gh(r){try{if(typeof r>"u")return r;let t=JSON.stringify(r);return JSON.parse(t)}catch(t){throw Ee.error("Error creating exportable element",r,t),new Error("[Pixi\u2019VN] Error creating exportable element")}}var $h=class extends LabelAbstract{constructor(r,t,e,n={}){e||(e={}),e.onLoadingLabel=async()=>{for(let i of t){let a;if(typeof i=="function"?a=i():a=i,a=A.getConditionalStep(a),a.operations){let s=a.operations.map(o=>A.loadAssets(o));await Promise.all(s);}}},super(r,e),vs(this,"_steps"),vs(this,"operationStringConvert"),vs(this,"skipEmptyDialogs",false),this._steps=t,this.operationStringConvert=n.operationStringConvert,this.skipEmptyDialogs=n.skipEmptyDialogs||false;}get steps(){return this._steps.map(r=>this.stepConverter(r))}get stepCount(){return this._steps.length}getStepById(r){if(r<0||r>=this._steps.length)return;let t=this._steps[r];return this.stepConverter(t)}getStepSha(r){if(r<0||r>=this.steps.length)return;let t=this._steps[r];return (0, Bh.default)(t.toString().toLocaleLowerCase()).toString()}getDialogueText(r){let t="";if(Array.isArray(r)){let e=[];r.forEach(n=>{if(typeof n=="string")e.push(n);else if(n&&typeof n=="object"){let i=A.getLogichValue(n);i?(i&&!Array.isArray(i)&&typeof i=="object"&&(i=A.getLogichValue(i)||""),Array.isArray(i)?e=e.concat(i):e.push(`${i}`)):e.push(`${n}`);}}),t=e;}else {let e=A.getLogichValue(r)||"";e&&!Array.isArray(e)&&typeof e=="object"&&(e=A.getLogichValue(e)||""),t=e;}return `${t}`}getDialogue(r){if(r==null)return;let t=A.getLogichValue(r);return t==null?"":typeof t=="object"&&"character"in t&&"text"in t?{character:t.character,text:tt.t(this.getDialogueText(t.text))}:tt.t(this.getDialogueText(t))}getChoices(r){return A.getLogichValue(r)?.map(t=>A.getLogichValue(t)).filter(t=>t!==void 0)}stepConverter(r){return async t=>{let e=typeof r=="function"?r():r;e=Gh(e),e=A.getConditionalStep(e);let n=this.operationStringConvert?f=>this.operationStringConvert(f,e,t):void 0,{operations:i=[]}=e;for(let f of i)await Ss(f,n);let{labelToOpen:a=[]}=e,s=this.getChoices(e.choices),o=A.getLogichValue(e.glueEnabled),l=this.getDialogue(e.dialogue),u=[];Array.isArray(a)||(a=[a]),a.forEach(f=>{let p=A.getLogichValue(f);p&&u.push(p);});let h=A.getLogichValue(e.goNextStep),c=A.getLogichValue(e.end);if(s){let f=s.map(p=>{let g="";if(Array.isArray(p.text)){let y=[];p.text.forEach(b=>{if(typeof b=="string")y.push(tt.t(b));else if(b&&typeof b=="object"){let _=A.getLogichValue(b);_&&!Array.isArray(_)&&typeof _=="object"&&(_=A.getLogichValue(_)||""),_&&(Array.isArray(_)?y=y.concat(tt.t(_)):y.push(tt.t(_)));}}),g=y;}else typeof p.text=="string"&&(g=tt.t(p.text));return {label:p.label,text:g,props:p.props,type:p.type,oneTime:p.oneTime,onlyHaveNoChoice:p.onlyHaveNoChoice,autoSelect:p.autoSelect}});narration.choiceMenuOptions=f;}else narration.choiceMenuOptions=void 0;l!==void 0&&(narration.dialogue=l,this.skipEmptyDialogs&&typeof l=="string"&&(l===""||RegExp(/^\s+$/).test(l))&&(h=true)),o?storage.setFlag(SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,true):o===false&&storage.setFlag(SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,false);for(let f of u){let p=f.label;typeof p=="object"&&(p=A.getLogichValue(p)||"");let g=f.params?.map(y=>A.getLogichValue(y));t={...t,...f.props},f.type==="jump"?(narration.openedLabels.length>0&&narration.closeCurrentLabel(),storage.setTempVariable(`${al}${narration.openedLabels.length}`,g),await narration.callLabel(p,t)):(storage.setTempVariable(`${al}${narration.openedLabels.length}`,g),await narration.callLabel(p,t));}c==="game_end"?(narration.closeAllLabels(),await narration.goNext(t,{runNow:true})):c==="label_end"&&narration.closeCurrentLabel(),h&&await narration.goNext(t,{runNow:true});}}};var _s="___param___";async function dc(r){let t=A.getLogichValue(r);if(t)switch(t.type){case "assets":switch(t.operationType){case "load":await Assets.load(t.aliases);break;case "lazyload":Assets.backgroundLoad(t.aliases);break}break;case "bundle":switch(t.operationType){case "load":await Assets.loadBundle(t.aliases);break;case "lazyload":Assets.backgroundLoadBundle(t.aliases);break}break}}var lt;(r=>(r.log=(t,...e)=>console.log(`[Pixi\u2019VN Json] ${t}`,...e),r.warn=(t,...e)=>console.warn(`[Pixi\u2019VN Json] ${t}`,...e),r.error=(t,...e)=>console.error(`[Pixi\u2019VN Json] ${t}`,...e),r.info=(t,...e)=>console.info(`[Pixi\u2019VN Json] ${t}`,...e)))(lt||(lt={}));async function Es(r,t,e){switch(e.type){case "fade":await showWithFade(t.alias,r,e.props,e.priority);break;case "dissolve":await showWithDissolve(t.alias,r,e.props,e.priority);break;case "movein":case "moveout":await moveIn(t.alias,r,e.props,e.priority);break;case "zoomin":case "zoomout":await zoomIn(t.alias,r,e.props,e.priority);break;case "pushin":case "pushout":await pushIn(t.alias,r,e.props,e.priority);break}}function $n(r){if(r.transition)switch(r.transition.type){case "fade":removeWithFade(r.alias,r.transition.props,r.transition.priority);break;case "dissolve":removeWithDissolve(r.alias,r.transition.props,r.transition.priority);break;case "movein":case "moveout":moveOut(r.alias,r.transition.props,r.transition.priority);break;case "zoomin":case "zoomout":zoomOut(r.alias,r.transition.props,r.transition.priority);break;case "pushin":case "pushout":pushOut(r.alias,r.transition.props,r.transition.priority);break}else canvas.remove(r.alias);}async function fc(r){switch(r.operationType){case "show":if(r.transition){let e=new ImageSprite(r.props,r.url||r.alias);await Es(e,r,r.transition);}else await showImage(r.alias,r.url,r.props);break;case "edit":let t=canvas.find(r.alias);t?r.props&&await t.setMemory({...t.memory,...r.props}):lt.error(`Image with alias ${r.alias} not found.`);break;case "remove":$n(r);break}}async function pc(r){switch(r.operationType){case "show":if(r.transition){let i=new VideoSprite(r.props,r.url||r.alias);await Es(i,r,r.transition);}else await showVideo(r.alias,r.url,r.props);break;case "edit":let t=canvas.find(r.alias);t?r.props&&await t.setMemory({...t.memory,...r.props}):lt.error(`Video with alias ${r.alias} not found.`);break;case "remove":$n(r);break;case "pause":let e=canvas.find(r.alias);e?e.paused=true:lt.error(`Video with alias ${r.alias} not found.`);break;case "resume":let n=canvas.find(r.alias);n?n.paused=false:lt.error(`Video with alias ${r.alias} not found.`);break}}async function gc(r){switch(r.operationType){case "show":if(r.transition){let e=new ImageContainer(r.props,r.urls);await Es(e,r,r.transition);}else await showImageContainer(r.alias,r.urls,r.props);break;case "edit":let t=canvas.find(r.alias);t?r.props&&await t.setMemory({...t.memory,...r.props}):lt.error(`ImageContainer with alias ${r.alias} not found.`);break;case "remove":$n(r);break}}async function mc(r){switch(r.operationType){case "edit":try{let t=canvas.find(r.alias);t?r.props&&(t.memory={...t.memory,...r.props}):lt.error(`Canvas Element with alias ${r.alias} not found.`);}catch(t){lt.error(`There was an error while trying to edit the canvas element with alias ${r.alias}.`,t);}break;case "remove":$n(r);break}}function Cc(r){switch(r.type){case "fade":let t=new FadeAlphaTicker(r.props,r.duration,r.priority);canvas.addTicker(r.alias,t);break;case "move":let e=new MoveTicker(r.props,r.duration,r.priority);canvas.addTicker(r.alias,e);break;case "rotate":let n=new RotateTicker(r.props,r.duration,r.priority);canvas.addTicker(r.alias,n);break;case "zoom":let i=new ZoomTicker(r.props,r.duration,r.priority);canvas.addTicker(r.alias,i);break}}async function vc(r){switch(r.type){case "shake":await shakeEffect(r.alias,r.props,r.priority);break}}function yc(r){switch(r.type){case "animate":canvas.animate(r.alias,r.keyframes,r.options,r.priority);break;case "animate-sequence":canvas.animate(r.alias,r.sequence,r.options,r.priority);break}}function Sc(r){switch(r.type){case "input":narration$1.requestInput({type:r.valueType},r.defaultValue);break;case "dialogue":narration$1.dialogue=void 0;break}}function bc(r){switch(r.operationType){case "play":sound.play(r.alias,r.props);break;case "stop":sound.stop(r.alias);break;case "pause":sound.pause(r.alias);break;case "resume":sound.resume(r.alias);break;case "volume":sound.volume(r.alias,r.value);break}}function _c(r){try{if(typeof r>"u")return r;let t=JSON.stringify(r);return JSON.parse(t)}catch(t){throw lt.error("Error creating exportable element",r,t),new Error("[Pixi\u2019VN] Error creating exportable element")}}function Ec(r){let t=R(r.value),e;switch(t&&typeof t=="object"&&"type"in t?e=R(t):e=t,r.storageType){case "flagStorage":storage.setFlag(r.key,r.value);break;case "storage":storage.setVariable(r.key,e);break;case "tempstorage":storage.setTempVariable(r.key,e);break;case "params":let n=storage.getVariable(`${_s}${narration.openedLabels.length-1}`)||[];n&&n.length-1>=r.key&&(n[r.key]=e),storage.setTempVariable(`${_s}${narration.openedLabels.length-1}`,n);break}}function R(r){let t=Nc(r);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return xc(t);case "arithmetic":case "arithmeticsingle":return wc(t);case "compare":case "valueCondition":case "union":return Tc(t)}return t}function wc(r){let t=R(r.leftValue);switch(r.type){case "arithmetic":let e=R(r.rightValue);switch(r.operator){case "*":return t*e;case "/":return t/e;case "+":return t+e;case "-":return t-e;case "%":return t%e;case "POW":return Math.pow(t,e);case "RANDOM":return narration.getRandomNumber(t,e)}case "arithmeticsingle":switch(r.operator){case "INT":return parseInt(t);case "FLOOR":return Math.floor(t);case "FLOAT":return parseFloat(t)}break}}function xc(r){if(r&&typeof r=="object"&&"type"in r&&r.type==="value"&&r.storageOperationType==="get")switch(r.storageType){case "storage":case "tempstorage":return storage.getVariable(r.key);case "flagStorage":return storage.getFlag(r.key);case "label":return narration.getTimesLabelOpened(r.label);case "choice":return narration.getTimesChoiceMade(r.index);case "logic":return R(r.operation);case "params":let t=storage.getVariable(`${_s}${narration.openedLabels.length-1}`)||[];if(t&&t.length>r.key)return t[r.key];lt.warn("getValue params not found");return}return r}function Tc(r){if(!r)return false;if(typeof r!="object"||!("type"in r))return !!r;switch(r.type){case "compare":let t=R(r.leftValue),e=R(r.rightValue);switch(r.operator){case "==":return t===e;case "!=":return t!==e;case "<":return t<e;case "<=":return t<=e;case ">":return t>e;case ">=":return t>=e;case "CONTAINS":return t.toString().includes(e.toString())}break;case "valueCondition":return !!R(r.value);case "union":return Pc(r)}return !!r}function Pc(r){if(r.unionType==="not")return !R(r.condition);let t=r.unionType==="and";for(let e=0;e<r.conditions.length;e++)if(t=R(r.conditions[e])||false,r.unionType==="and"){if(!t)return false}else if(t)return true;return t}function Oc(r,t){return Math.floor(Math.random()*(t-r+1)+r)}function Nc(r){if(Array.isArray(r)||!r)return r;if(r&&typeof r=="object"&&"type"in r)switch(r.type){case "resulttocombine":return Ac(r);case "ifelse":return R(r.condition)?R(r.then):R(r.else);case "stepswitch":let t=R(r.elements)||[];if(t.length===0){lt.error("getValueFromConditionalStatements elements.length === 0");return}switch(r.choiceType){case "random":let e=Oc(0,t.length-1);return R(t[e]);case "loop":let n=NarrationManagerStatic.getCurrentStepTimesCounter(r.nestedId)-1;return n>t.length-1&&(n=n%t.length),R(t[n]);case "sequential":let i,a=NarrationManagerStatic.getCurrentStepTimesCounter(r.nestedId)-1;return r.end=="lastItem"&&(i=R(t[t.length-1])),a>t.length-1?i:R(t[a]);case "sequentialrandom":let s=NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:r.nestedId,onceOnly:true});if(s==null&&r.end=="lastItem"){let o=NarrationManagerStatic.getCurrentStepTimesCounterData(r.nestedId);if(!o||!o?.usedRandomNumbers){lt.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let l=o.usedRandomNumbers[`0-${t.length-1}`];return R(t[l[l.length-1]])}if(s==null){lt.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return R(t[s])}}return r}function ws(r){if(r.conditionalStep){let t=_c(R(r.conditionalStep));if(t?.glueEnabled===void 0&&delete t?.glueEnabled,t?.goNextStep===void 0&&delete t?.goNextStep,t?.end===void 0&&delete t?.end,t?.choices===void 0&&delete t?.choices,t?.dialogue===void 0&&delete t?.dialogue,t?.labelToOpen===void 0&&delete t?.labelToOpen,t?.operations===void 0&&delete t?.operations,t){let e={...r,conditionalStep:void 0,...t};return ws(e)}else storage.getFlag(SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY)&&storage.setFlag(SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,false);}return r}function Ac(r){let t=r.firstItem,e=[];r.secondConditionalItem?.forEach(i=>{if(Array.isArray(i))i.forEach(a=>{let s=R(a);e.push(s);});else {let a=R(i);e.push(a);}});let n=t?[t,...e]:e;if(n.length===0){lt.warn("combinateResult toCheck.length === 0");return}if(typeof n[0]=="string")return tt.t(n);if(typeof n[0]=="object"){let i=n,a,s=i.map((b,_)=>{b=ws(b);let d=R(b.dialogue)||"";return _===0?(a=R(b.glueEnabled)||false,d):(typeof d=="object"&&"text"in d&&(d=d.character+": "+d.text),a===false&&(d=`
|
|
45
|
+
|
|
46
|
+
`+d),a=R(b.glueEnabled)||false,d)}),o=R(s[0]),l=typeof o=="object"&&"character"in o?o.character:void 0,u=s.flatMap(b=>{let _;b&&typeof b=="object"&&"text"in b?_=b.text:_=b;let d;return Array.isArray(_)?d=_.map(S=>{let v=R(S);return tt.t(`${v}`)}):d=R(_)||"",tt.t(d)}),h=i.find(b=>b.end),c=i.find(b=>b.choices),f=false,p=false;i.length>0&&(i[0].glueEnabled&&i[0].goNextStep&&i[0].dialogue===void 0&&storage.setFlag(SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,true),f=i[i.length-1].glueEnabled,p=i.reverse().find(b=>!(b.operations&&(!b.dialogue||!b.choices)))?.goNextStep);let g=i.find(b=>b.labelToOpen),y=[];return i.forEach(b=>{b.operations&&y.forEach(_=>{y.push(_);});}),{dialogue:l?{character:l,text:u}:u,end:h?.end,choices:c?.choices,glueEnabled:f,goNextStep:p,labelToOpen:g?.labelToOpen,operations:y}}}function hl(){A.init({animateOperation:yc,canvasElementOperation:mc,effectOperation:vc,imageContainerOperation:gc,imageOperation:fc,narrationOperation:Sc,loadAssets:dc,soundOperation:bc,tickerOperation:Cc,videoOperation:pc,setStorageValue:Ec,getLogichValue:R,getConditionalStep:ws});}var F;(i=>(i.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),i.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),i.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),i.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(F||(F={}));var cl="\xA7SPACE\xA7",dl="\xA7DOUBLE_QUOTES\xA7",fl="\xA7QUOTES\xA7",pl="SPECIAL_\xA7QUOTES\xA7",gl="\xA7CURLY_BRACKETS1\xA7",ml="\xA7CURLY_BRACKETS2\xA7",Ic=["add","play","pause","resume","remove","volume"],T=class T{static runCustomHashtagScript(t,e){return T._customHashtagScript(t,e,T.convertListStringToObj)}static set customHashtagScript(t){T._customHashtagScript=t;}static async generateOrRunOperationFromHashtagScript(t,e,n){try{t=t.replaceAll('\\"',dl),t=t.replaceAll("\\'",fl),t=t.replaceAll("\\`",pl),t=t.replaceAll("\\{",gl),t=t.replaceAll("\\}",ml),t=t.replaceAll("{"," { "),t=t.replaceAll("}"," } "),t=t.replaceAll(gl,"{"),t=t.replaceAll(ml,"}");let i=[],a,s="";for(let h=0;h<t.length;h++){let c=t[h];c==='"'||c==="'"||c==="`"?a===void 0?(i.push(s),s="",a=c,s+=c):a===c?(a=void 0,s+=c,i.push(s),s=""):s+=c:s+=c;}s!==""&&i.push(s),i.forEach((h,c)=>{c%2===1&&(i[c]=h.replaceAll(" ",cl));}),t=i.join(""),i=t.split(" ").filter(h=>h!==""),i=i.map(h=>h.replaceAll(cl," ").replaceAll(dl,'"').replaceAll(fl,"'").replaceAll(pl,"`"));let o=T.runCustomHashtagScript(i,n);if(o===!0)return;if(typeof o=="string")return o.startsWith("#")&&(o=o.substring(1)),T.generateOrRunOperationFromHashtagScript(o,e,n);let l=i.length>1?T.removeExtraDoubleQuotes(i[1]):"",u=i.length>0?T.removeExtraDoubleQuotes(i[0]):"";switch(l){case "image":case "imagecontainer":case "canvaselement":case "video":return l==="video"&&(u==="pause"||u==="resume")?{type:"video",operationType:u,alias:T.removeExtraDoubleQuotes(i[2])}:T.getCanvasOperationFromComment(i,l);case "sound":return T.getSoundOperationFromComment(i);case "input":if(u==="request"){let h={type:"input",operationType:"request"};if(i.length>2)try{let c=i.slice(2),f=T.convertListStringToObj(c);"type"in f&&typeof f.type=="string"&&(h.valueType=f.type),"default"in f&&(h.defaultValue=f.default);}catch{}return h}break;case "assets":case "bundle":switch(u){case "load":case "lazyload":return {type:l,operationType:u,aliases:i.slice(2)}}break;default:if(l)switch(u){case "call":case "jump":e.labelToOpen={label:l,type:u},e.goNextStep=void 0;return;case "fade":case "move":case "rotate":case "zoom":case "shake":let h={};if(i.length>2)try{h=T.convertListStringToObj(i.slice(2));}catch{}if(u=="move"&&"x"in h&&"y"in h&&(h.destination={x:h.x,y:h.y,type:"pixel"},delete h.x,delete h.y),u=="move"&&"xAlign"in h&&"yAlign"in h&&(h.destination={x:h.xAlign,y:h.yAlign,type:"align"},delete h.xAlign,delete h.yAlign),u=="move"&&"xPercentage"in h&&"yPercentage"in h&&(h.destination={x:h.xPercentage,y:h.yPercentage,type:"percentage"},delete h.xPercentage,delete h.yPercentage),u=="move"&&!("destination"in h)){F.error("The move operation don't have a destination or destination is not valid",h);return}return {alias:l,type:u,props:h};case "animate":let f={},p={};if(i.length>2){let y=i.slice(2),b=[];if(y.includes("options")){let _=y.indexOf("options");b=y.slice(_+1),y=y.slice(0,_);}try{f=T.convertListStringToObj(y);}catch{}if(b.length>0)try{p=T.convertListStringToObj(b);}catch{}}return {alias:l,type:u,keyframes:f,options:p}}else switch(u){case "pause":return "dialogue"in e&&delete e.dialogue,"goNextStep"in e&&delete e.goNextStep,{type:"dialogue",operationType:"clean"}}}}catch(i){throw F.error("Error parsing ink hashtag-script",t),i}F.error("The operation is not valid",t);}static getCanvasOperationFromComment(t,e){let n=T.removeExtraDoubleQuotes(t[0]),i=T.removeExtraDoubleQuotes(t[2]),a=T.convertListStringToPropList(t.slice(3));switch(n){case "show":switch(e){case "image":case "video":return T.getImageOperationFromComment(e,i,a);case "imagecontainer":return T.getContainerOperationFromComment(e,i,a);case "canvaselement":default:F.error("This show operation is not valid for this type of element",e);}case "edit":return {type:e,operationType:"edit",alias:i,props:T.convertPropListStringToObj(a)};case "remove":let o={type:e,operationType:"remove",alias:i};if(a.length>1&&a[0]==="with"){let l=t[t.indexOf("with")+1],u=t.slice(t.indexOf("with")+2),h=T.getTransition(l,u);h!==void 0&&(o.transition=h);}return o;default:F.error("The operation type is not valid",n);}}static getImageOperationFromComment(t,e,n){let i,a;n.length%2===0?(i=e,a=n):(i=T.removeExtraDoubleQuotes(n[0]),a=T.convertListStringToPropList(n.slice(1)));let s={type:t,operationType:"show",alias:e,url:i};return T.setShowProps(s,a)}static getContainerOperationFromComment(t,e,n){let i=[],a=n.findIndex(u=>u.startsWith("[")),s=n.findIndex(u=>u.endsWith("]"));if(a===-1||s===-1){F.error("Show imagecontainer must have a list of image ulrs",n);return}if(i=n.slice(a,s+1),i.length<2){F.error("Show imagecontainer must have a list of image ulrs",n);return}i[0]==="["?i.shift():i[0]=i[0].substring(1),i[i.length-1]==="]"?i.pop():i[i.length-1]=i[i.length-1].substring(0,i[i.length-1].length-1);let o={type:t,operationType:"show",alias:e,urls:i.map(u=>T.removeExtraDoubleQuotes(u))},l=T.convertListStringToPropList(n.slice(s+1));return T.setShowProps(o,l)}static getSoundOperationFromComment(t){let e=T.removeExtraDoubleQuotes(t[0]);if(!Ic.includes(e))return;let n=T.removeExtraDoubleQuotes(t[2]);switch(e){case "play":let i={type:"sound",operationType:"play",alias:n};if(t.length>3){let u=T.getSoundPlayOptions(t.slice(3));u!==void 0&&(i.props=u);}return i;case "pause":case "resume":return {type:"sound",operationType:e,alias:n};case "stop":case "remove":return {type:"sound",operationType:"stop",alias:n};case "volume":let o=parseFloat(t[3]);return {type:"sound",operationType:"volume",alias:n,value:o}}}static setShowProps(t,e){if(e.length>0){if(e.includes("with")&&e.length>e.indexOf("with")+1){let n=e[e.indexOf("with")+1],i=e.slice(e.indexOf("with")+2);e=e.slice(0,e.indexOf("with"));let a=T.getTransition(n,i);a!==void 0&&(t.transition=a);}if(e.length>0){let n=T.convertListStringToObj(e);t.props=n;}}return t}static getTransition(t,e){switch(t){case "dissolve":case "fade":case "movein":case "moveout":case "zoomin":case "zoomout":case "pushin":case "pushout":break;default:return}let n={type:t};if(e.length>0)try{let i=T.convertPropListStringToObj(e);n.props=i;}catch{}return n}static getSoundOption(t){try{return T.convertListStringToObj(t)}catch{return}}static getSoundPlayOptions(t){try{return T.convertListStringToObj(t)}catch{return}}static convertListStringToObj(t){let e=T.convertListStringToPropList(t);return T.convertPropListStringToObj(e)}static convertListStringToPropList(t){let e=[],n=0,i="";for(let a=0;a<t.length;a++){let s=t[a];s.startsWith("{")?(n++,i+=s):s.endsWith("}")&&n>0?(n--,i+=s,n===0&&(e.push(i),i="")):n>0?i+=s:e.push(s);}return e}static convertPropListStringToObj(t){if(t.length===0)return {};if(t.length%2!==0)throw F.error("The props list must have a pair number of elements",t),new Error("The props list must have a pair number of elements");let e="{";t.forEach((n,i)=>{if(i%2===0)e+=`"${n}": `;else {switch(n){case "null":case "undefined":case "true":case "false":e+=`${n}`;break;default:T.containExtraDoubleQuotes(n)?(n=T.removeExtraDoubleQuotes(n),e+=`"${n}"`):n.startsWith("{")&&n.endsWith("}")?e+=`${n}`:n.startsWith('"')&&n.endsWith('"')?e+=`${n}`:isNaN(parseFloat(n))?e+=`"${n}"`:e+=`${n}`;}i<t.length-1&&(e+=", ");}}),e+="}";try{return JSON.parse(e)}catch(n){throw F.error("Error parsing ink json",e),n}}static removeExtraDoubleQuotes(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")||t.startsWith("`")&&t.endsWith("`")?t.substring(1,t.length-1):t}static containExtraDoubleQuotes(t){return !!(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")||t.startsWith("`")&&t.endsWith("`"))}};d(T,"_customHashtagScript",t=>false);var ue=T;function Vc(r){ue.customHashtagScript=r;}var Eh=c(uh(),1);var ps="global decl",se="___external_value___";function jn(r,t){if(r.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(r)&&(r=r.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!r.startsWith(".")))return r.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(r)&&r.includes("g-")){let n=r.split("g-");return Uo(t)+"_|_"+"g-"+n[n.length-1]}let e=0;for(;new RegExp(/^\.\^.*$/).test(r);)e++,r=r.substring(2);if(e=e-1,new RegExp(/^\..*$/).test(r)&&t){let n=r.substring(1);return Uo(t,e)+"_|_"+n.replaceAll(".","_|_")}return r.replaceAll(".","_|_")||Uo(t,e).replaceAll(".","_|_")}function Uo(r,t=0){let e=r.split("_|_");for(;e.length>1&&t>0;)e.pop()?.includes("g-")&&t--,t--;return e.join("_|_")}var hh="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function $t(r){return r.startsWith("^")&&(r=r.substring(1)),r=r.replaceAll("\\\\",hh),r=r.replaceAll("\\n",`
|
|
47
|
+
`),r=r.replaceAll("\\t"," "),r=r.replaceAll(" "," "),r=r.replaceAll(hh,"\\\\"),r}var ch=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],dh=["+","-","/","*","%","POW","RANDOM"],fh=["INT","FLOOR","FLOAT"],ph=["==",">","<",">=","<=","!=","CONTAINS"];function ze(r,t,e){r=r.map(i=>{if(typeof i=="string"){if(i==="rnd")return "RANDOM";if(i==="?")return "CONTAINS"}return i});let n=[];return r.forEach(i=>{if(typeof i=="object"&&"CNT?"in i)if(new RegExp(/.*\.[0-9]\..*/).test(i["CNT?"])){let a=i["CNT?"].split("."),s=a.pop(),o=a.pop();if(o===void 0||s===void 0){F.error("Error parsing ink file: Conditional statement is not valid",r);return}let l=parseInt(o),u=a.join(".");if(u.includes("^.")){let c=u.split("."),f=c[c.length-1].replaceAll(".","_|_");c.pop(),u=c.join(".")+"."+f,s.includes("c-")&&(u=u+"_|_"+s);}else u=u.replaceAll(".","_|_");let h=jn(u,t);if(!h)return;n.push({type:"compare",leftValue:gh(h),operator:">=",rightValue:{type:"value",value:l}});}else {let a=jn(i["CNT?"],t);if(!a)return;n.push(gh(a));}else if(typeof i=="object"&&"VAR?"in i)n.push(Xe(i["VAR?"],e));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)F.error("Error parsing ink file: Conditional statement is not valid",r);else {let a={type:"union",unionType:"not",condition:n[n.length-1]};n[n.length-1]=a;}else if(i&&typeof i=="string"&&ph.includes(i))if(n.length<2)F.error("Error parsing ink file: Conditional statement is not valid",r);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"&&dh.includes(i))if(n.length<2)F.error("Error parsing ink file: Conditional statement is not valid",r);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"&&fh.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($t(i)):typeof i=="object"&&"^->"in i?i["^->"].includes("$r")||n.push(i["^->"]):n.push(i);}),n}function gh(r){return {type:"value",storageType:"label",storageOperationType:"get",label:r}}function mh(r,t,e){return ze(r,t,e)}function Xe(r,t,e="storage"){let n=t.indexOf(r);return n>=0?{type:"value",storageType:"params",storageOperationType:"get",key:n}:{type:"value",storageOperationType:"get",storageType:e,key:r}}function Ho(r,t,e,n="storage"){let i=t.indexOf(r);return i>=0?{type:"value",storageType:"params",storageOperationType:"set",key:i,value:e}:{type:"value",storageOperationType:"set",storageType:n,key:r,value:e}}function gs(r,t){t&&(typeof t=="string"?t.startsWith("^")&&r.push($t(t)):typeof t=="object"&&"type"in t&&t.type!=="value"&&r.push(t));}function Ko(r,t,e,n,i=true,a=false){return wm(r,t,e,n,i,a)}function wm(r,t,e,n,i,a=false){if(t){if(a)Array.isArray(t)&&t.length>0&&r.push({operations:[{type:"operationtoconvert",values:t}],goNextStep:true});else if(typeof t=="string"&&t.startsWith("^")||t&&typeof t=="object"&&"type"in t&&t.type=="value"&&t.storageOperationType==="get"){if(!i&&r.length>0){let s=r[r.length-1];!s.glueEnabled&&!s.operations&&(s.glueEnabled=true,s.labelToOpen||(s.goNextStep=true)),r[r.length-1]=s;}typeof t=="string"?r.push(xm($t(t))):r.push({dialogue:t});}else if(typeof t=="string"){if(t==="end")r.push({end:"game_end"});else if(t==="done")r.push({end:"label_end",goNextStep:true});else if(t=="<>")if(r.length>0){let s=r[r.length-1];s.glueEnabled=true,s.labelToOpen||(s.goNextStep=true),r[r.length-1]=s;}else r.push({glueEnabled:true,goNextStep:false});}else if(typeof t=="object"){if("type"in t&&t.type!=="value"){if(!i&&r.length>0){let s=r[r.length-1];!s.glueEnabled&&!s.operations&&(s.glueEnabled=true,s.labelToOpen||(s.goNextStep=true)),r[r.length-1]=s;}r.push({conditionalStep:t});}else if("->"in t){let s=i?void 0:true;if(!i&&r.length>0){let o=r[r.length-1];o.labelToOpen||(o.goNextStep=true),r[r.length-1]=o;}if(t.params&&t.params.length===0&&(t.params=void 0),t.var)r.push({labelToOpen:{label:Xe(t["->"],n),type:"jump",params:t.params},glueEnabled:s});else {let o=jn(t["->"],e);if(!o)return;r.push({labelToOpen:{label:o,type:"jump",params:t.params},glueEnabled:s});}}"type"in t&&t.type=="value"&&t.storageOperationType==="set"&&(typeof t.value=="string"&&t.value.startsWith("^")&&(t.value=$t(t.value)),r.push({goNextStep:true,operations:[t]}));}}}function xm(r){let t;if(r.includes(": ")){let e=r.split(": "),n=e[0],i=e.slice(1).join(": ");RegisteredCharacters.get(n)&&(t=n,r=i);}return t?{dialogue:{character:t,text:r}}:{dialogue:r}}function zo(r,t,e,n=true,i=false){return Tm(r,t,e,n,i)}function Tm(r,t,e,n,i=false){t&&(typeof t=="string"&&t.startsWith("^")||t&&typeof t=="object"&&"type"in t&&t.type=="value"&&t.storageOperationType==="get"?typeof t=="string"?r.push($t(t)):r.push(t):typeof t=="object"&&"type"in t&&r.push(t));}function ms(r,t,e){if(r.length===0){F.error("Error parsing ink file: Arithmetic statement is not valid",r);return}let n=ze(r,t,e);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 Ye(r,t,e,n="",i,a,s=void 0){let o=[],l="sequential",u=false,h=true;r.forEach(p=>{p==="%"&&(l="loop"),p==="seq"&&(l="random"),p==="MIN"&&(u=true);});let c=r[r.length-1];return Object.keys(c).forEach(p=>{let g=c[p];if(Array.isArray(g)&&g.length>3){g=g.slice(1,g.length-2);let y=[];ae(g,n,i,y,t,t,e,Qe,s,true,a),y.length===1?o.push(y[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:y});}else Array.isArray(g)&&g.length===3&&(h=false);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:h?"lastItem":void 0,nestedId:s}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:h?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:l}}function Xo(r="",t=""){let e=Array.isArray(r)?r:[r],n=Array.isArray(t)?t:[t];return [...new Set([...e,...n])]}function Qe(r,t,e,n,i){if(r.length>0){let a={};Ch(r,a,i);for(let[s,o]of Object.entries(a)){let l=e+"_|_"+s,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=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let h=Yo(u,o.conditions,i,e)||u,c=t[t.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),t.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let f=c.choices;f&&Array.isArray(f)?f.push(h):F.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,f),c.choices=f.sort((p,g)=>{try{let y=p.label.split("."),b=y[y.length-1].replaceAll(".","_|_"),_=g.label.split("."),d=_[_.length-1].replaceAll(".","_|_");if(b.includes("c-")&&d.includes("c-")){let S=b.split("c-")[1],v=parseInt(S),m=d.split("c-")[1],E=parseInt(m);return v-E}}catch{}return 0});}else t.push({choices:[h]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function Ch(r,t,e,n){let i=[],a="",s="",o=false,l=[];for(let u=0;u<r.length;u++){let h=r[u];if(typeof h=="string")h.startsWith("^")?i.push($t(h)):ch.includes(h)&&l.push(h);else if(Array.isArray(h)&&h.includes("visit")){let c=Ye(h,gs,(f,p,g)=>{},n,{preDialog:{}},e);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=true));else if("s"in h&&h.s instanceof Array){let c=vh(h.s),f=h.s.includes("<>");c&&(n&&t[n]?(t[n].preDialog={text:c,glue:f},t[n].text=Xo(c,t[n].text)):(i.push(c),s=c));}else "CNT?"in h&&l.push(h);else l.push(h);if(a){t[a]?t[a].text=Xo(i,t[a].text):t[a]={text:i,onetime:o,conditions:l},s&&(t[a].preDialog={text:s,glue:false});let c=r.slice(u+1);Ch(c,t,e,a);return}}}function vh(r){for(let t of r)if(typeof t=="string"){if(t.startsWith("^"))return $t(t)}else if(t instanceof Array){let e=vh(t);if(e)return e}}function Yo(r,t,e,n,i){if(t.length===0)return;let a=ze(t,n,e);if(a.length===1){let s={type:"ifelse",condition:a[0],then:r,else:i};return s.else||delete s.else,s}else if(a.length>1){let s={type:"ifelse",condition:{type:"union",unionType:"and",conditions:a},then:r,else:i};return s.else||delete s.else,s}}function yh(r,t,e,n,i,a,s=void 0){if(r.length===0){F.error("Error parsing ink file: Conditional statement is not valid",r);return}let o=[],l=[];if(r.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){F.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=Qo(l[0],t,e,n+"_|_"+"then",i,a,`${s||""}then`),h;return l.length===2?h=Qo(l[1],t,e,n+"_|_"+"else",i,a,`${s||""}else`):l.length>2&&(l.shift(),l.push("nop"),l=[{b:l}],h=Qo(l,t,e,n+"_|_"+"else",i,a,`${s||""}else`)),i.du=void 0,Yo(u,o,a,n,h)}function Qo(r,t,e,n,i,a,s=void 0){let o=[];for(let u of r)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["->"]))),ae(u.b,n,i,o,t,t,e,Qe,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function ae(r,t,e,n=[],i,a,s,o,l=void 0,u=true,h=[]){let c=false,f=[],p=false,g=false,y=[],b=[];if(e.preDialog[t]&&(u=false,i(n,"^"+e.preDialog[t].text,t,h,u,g),e.preDialog[t].glue&&i(n,"<>",t,h,u,g),delete e.preDialog[t]),r.includes("visit")){let d=Ye(r,a,s,t,e,h,l);d&&(!u&&n.length>0&&i(n,"<>",t,h,u,g),i(n,d,t,h,u,g));return}let _=r[0];if(_&&typeof _=="object"&&"temp="in _){for(;r[0]&&typeof r[0]=="object"&&"temp="in r[0];)h.push(r[0]["temp="]),r.shift();h=h.reverse();}if(r.forEach((d,S)=>{if(g){if(typeof d=="string"&&d=="/#"){let v=[];ae(b,t,e,v,zo,zo,s,o,l,u),i(n,v,t,h,u,g),g=false,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)S>0&&r[S-1]=="ev"?(p=true,y.push(d)):p?y.push(d):(f.push(d),u=false);else if("VAR="in d||"temp="in d){let v=Ho("VAR="in d?d["VAR="]:d["temp="],h,r[S-1],"VAR="in d?"storage":"tempstorage");if(v.value&&typeof v.value=="string"&&v.value=="/str"&&(v.value=r[S-2]),v.value&&typeof v.value=="object"&&"^->"in v.value&&(v.value=v.value["^->"]),f.length>1){let m=ms(f,t,h);f=[],m&&typeof m=="object"&&"type"in m&&m.type=="value"&&"storageType"in m&&m.storageType=="logic"&&(v.value=m.operation);}(typeof v.key!="string"||!v.key.includes("$r"))&&(i(n,v,t,h,u,g),u=true);}else "VAR?"in d?f.push(d):"^->"in d&&(d["^->"].includes("$r")||f.push(d));else if(typeof d=="string"&&d=="/ev")p&&y.push(d),c=false,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 m=Xe(v["VAR?"],h,"storage");i(n,m,t,h,u,g);}else {let m=[];for(;f.length>0&&f[f.length-1]!="/ev";)m.push(f.pop());m=m.reverse();let E=ms(m,t,h);f=[],E&&typeof E=="object"&&"type"in E&&E.type=="value"&&"storageType"in E&&E.storageType=="logic"?i(n,{storageOperationType:"get",storageType:"logic",operation:E.operation,type:"value"},t,h,u,g):(i(n,"<>",t,h,u,g),E=`^${E}`,i(n,E,t,h,u,g));}u=false;}}else f.push(d);else if(typeof d=="string")if(d.startsWith("^"))i(n,d,t,h,u,g),u=false;else if(d=="ev")c=true;else if(d==`
|
|
48
|
+
`)u=true;else if(d=="done"||d=="end")i(n,d,t,h,u,g),u=false;else if(d=="<>")i(n,d,t,h,u,g),u=false;else if(d=="nop"&&p){let v=yh(y,a,s,t,e,h,l);v&&i(n,v,t,h,u,g),p=false,y=[];}else d=="#"&&(g=true);else if(d instanceof Array)if(p)y.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=[],m=[];for(;f.length>0&&f[f.length-1]!="/ev";)v.push(f.pop());y=[...y,...v.reverse()],p=true,m.push(d.pop()),m.push(d.pop()),y=[...y,...d],y.push(m);}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){F.error("Error parsing ink file: el is undefined");return}let m=v["#n"];delete v["#n"],d.push(v),i(n,{"->":t?t+"_|_"+m:m},t,h,u,g),s({[m]:d},t,e);}else ae(d,t,e,n,i,a,s,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=mh(["ev",...f],t,h)),d.params=v,i(n,d,t,h,u,g),u=false;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(f.push(d),u=false);else if("s"in d&&d.s instanceof Array)f.push(d),u=false;else if("CNT?"in d)f.push(d),u=false;else if("VAR="in d||"temp="in d){let v=[],m=Ho("VAR="in d?d["VAR="]:d["temp="],h,void 0,"VAR="in d?"storage":"tempstorage");if(m.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(),m.value=ms(v,t,h),f=[],(m.value!==void 0||m.value!==null)&&i(n,m,t,h,u,g),u=false;}}else s(d,t,e);}),o(f,n,t,e,h),t.includes("_|_")&&n.length==2){let d=n[0],S=n[1];d&&S&&typeof d=="object"&&"dialogue"in d&&typeof S=="object"&&"labelToOpen"in S&&d.dialogue==" "&&S.labelToOpen&&(n.shift(),delete S.glueEnabled,n[0]=S);}}function Sh(r){try{let t={};return bh(r,t),t}catch(t){F.error("Error parsing ink file",t);}}function bh(r,t,e={externalSwitch:void 0}){for(let n of r)if(n)if(n instanceof Array)if(n.includes("visit")){let i=Ye(n,gs,(a,s,o)=>{},"",{preDialog:{}},[]);i&&(e.externalSwitch=i);}else bh(n,t,e);else typeof n=="object"&&(n&&"VAR="in n&&e.externalSwitch&&(t[se]||(t[se]=[]),t[se].push({operations:[{type:"value",value:e.externalSwitch,key:n["VAR="],storageType:"storage",storageOperationType:"set"}]})),_h(n,t));}function _h(r,t,e="",n={preDialog:{}}){if(r!==null){for(let[i,a]of Object.entries(r))if(a instanceof Array){let s=[],o={},l=(e?e+"_|_":"")+i;ae(a,l,n,s,Ko,Ko,(u,h,c)=>{_h(u,o,h,c);},Qe);for(let[u,h]of Object.entries(o))t[u]=h;s.length>0&&(t[l]=s);}}}function Zo(r){let t={},e=Pm(r),n;try{n=JSON.parse(e);}catch{F.error("Error parsing ink file");return}if(t.labels=Sh(n.root),t.labels&&ps in t.labels){let i=t.labels[ps];delete t.labels[ps],i.forEach(a=>{a.operations&&(t.initialOperations=t.initialOperations?[...t.initialOperations,...a.operations]:[...a.operations]);});}if(t.labels&&se in t.labels){let i=t.labels[se];delete t.labels[se],i.forEach(a=>{a.operations&&(t.initialOperations=t.initialOperations?[...t.initialOperations,...a.operations]:[...a.operations]);});}return t}function Pm(r){try{return new Eh.Compiler(r).Compile().ToJson()||""}catch(t){return F.error("Error compiling ink file",t),""}}async function Om(r){Array.isArray(r)||(r=[r]),hl();let t=r.map(async e=>{let n=Zo(e);n&&await ll(n,{operationStringConvert:ue.generateOrRunOperationFromHashtagScript,skipEmptyDialogs:true});});return await Promise.all(t)}function Nm(r){tt.afterToTranslate=t=>tl(t,r);}function Am(r){tt.beforeToTranslate=t=>tl(t,r);}function tl(r,t){let e=r.match(/\[([^\]]+)\]/);if(e){let n=e[1],i=t(n);return i&&(r=r.replaceAll(e[0],i)),tl(r,t)}return r}function Im(r){tt.translate=r;}function Vm(r,t={},e={}){let n=[];return r.labels&&Object.values(r.labels).forEach(i=>{n=n.concat(i);}),tt.generateJsonTranslation(n,t,e)}export{Vc as a,Zo as b,Om as c,Nm as d,Am as e,Im as f,Vm as g};
|