@drincs/pixi-vn-ink 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,102 +1,102 @@
1
- 'use strict';var pixiVn=require('@drincs/pixi-vn'),canvas=require('@drincs/pixi-vn/canvas'),characters=require('@drincs/pixi-vn/characters'),v=require('zod'),narration=require('@drincs/pixi-vn/narration'),sound=require('@drincs/pixi-vn/sound'),storage=require('@drincs/pixi-vn/storage');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var v__default=/*#__PURE__*/_interopDefault(v);var _c=Object.create;var Bl=Object.defineProperty;var Tc=Object.getOwnPropertyDescriptor;var Oc=Object.getOwnPropertyNames;var Pc=Object.getPrototypeOf,Fc=Object.prototype.hasOwnProperty;var wt=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var x=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Nc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oc(e))!Fc.call(r,i)&&i!==t&&Bl(r,i,{get:()=>e[i],enumerable:!(n=Tc(e,i))||n.enumerable});return r};var zs=(r,e,t)=>(t=r!=null?_c(Pc(r)):{},Nc(Bl(t,"default",{value:r,enumerable:true}),r));var fa=x(bi=>{Object.defineProperty(bi,"__esModule",{value:true});bi.CompilerOptions=void 0;var pa=class{constructor(e=null,t=[],n=false,i=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=a;}};bi.CompilerOptions=pa;});var Pu=x(Ai=>{Object.defineProperty(Ai,"__esModule",{value:true});Ai.DebugSourceRange=void 0;var ma=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};Ai.DebugSourceRange=ma;});var Ut=x(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.ErrorType=void 0;var Fu;(function(r){r[r.Author=0]="Author",r[r.Warning=1]="Warning",r[r.Error=2]="Error";})(Fu||(xi.ErrorType=Fu={}));});var Nu=x(wi=>{Object.defineProperty(wi,"__esModule",{value:true});wi.Argument=void 0;var ga=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};wi.Argument=ga;});var H=x(ue=>{Object.defineProperty(ue,"__esModule",{value:true});ue.filterUndef=ue.isEquatable=ue.nullIfUndefined=ue.asINamedContentOrNull=ue.asBooleanOrThrows=ue.asNumberOrThrows=ue.asOrThrows=ue.asOrNull=void 0;function Kd(r,e){return r instanceof e?Iu(r):null}ue.asOrNull=Kd;function Xd(r,e){if(r instanceof e)return Iu(r);throw new Error(`${r} is not of type ${e}`)}ue.asOrThrows=Xd;function Yd(r){if(typeof r=="number")return r;throw new Error(`${r} is not a number`)}ue.asNumberOrThrows=Yd;function Qd(r){if(typeof r=="boolean")return r;throw new Error(`${r} is not a boolean`)}ue.asBooleanOrThrows=Qd;function Zd(r){return r.hasValidName&&r.name?r:null}ue.asINamedContentOrNull=Zd;function ep(r){return typeof r>"u"?null:r}ue.nullIfUndefined=ep;function tp(r){return typeof r=="object"&&typeof r.Equals=="function"}ue.isEquatable=tp;function Iu(r,e){return r}function np(r){return r!=null}ue.filterUndef=np;});var Q=x(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.ParsedObject=void 0;var Vu=H(),Ca=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=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let n of t)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let n=(0, Vu.asOrNull)(this,e);if(n!==null&&(t===null||t(n)===true))return n;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,n)=>{let i=Array.isArray(n)?n:[],a=(0, Vu.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&i.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,n=false){if(t===null&&(t=this),!(t._alreadyHadError&&!n||t._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(e,t,n);else throw new Error(`No parent object to send error to: ${e}`);n?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};_i.ParsedObject=Ca;});var Oi=x(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.AuthorWarning=void 0;var ip=Q(),ya=class extends ip.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Ti.AuthorWarning=ya;});var xe=x(wn=>{Object.defineProperty(wn,"__esModule",{value:true});wn.Path=void 0;var Kt=class r{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof r.Component&&arguments[1]instanceof r){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new r(e)}else return r.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new r;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new r,n=0;for(let i=0;i<e._components.length&&e._components[i].isParent;++i)n++;for(let i=0;i<this._components.length-n;++i)t._components.push(this._components[i]);for(let i=n;i<e._components.length;++i)t._components.push(e._components[i]);return t}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let t=this._componentsString.split(".");for(let n of t)/^(\-|\+)?([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(e){if(e==null||e._components.length!=this._components.length||e.isRelative!=this.isRelative)return false;for(let t=0,n=e._components.length;t<n;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new r;return t._components.push(...this._components),t._components.push(e),t}};wn.Path=Kt;Kt.parentId="^";(function(r){class e{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 e(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=e;})(Kt||(wn.Path=Kt={}));});var _n=x(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.Debug=void 0;var ku;(function(r){function e(n,i,a){t(n instanceof i,a);}r.AssertType=e;function t(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}r.Assert=t;})(ku||(Pi.Debug=ku={}));});var fe=x(Xt=>{Object.defineProperty(Xt,"__esModule",{value:true});Xt.throwNullException=Xt.NullException=void 0;var Fi=class extends Error{};Xt.NullException=Fi;function rp(r){throw new Fi(`${r} is null or undefined`)}Xt.throwNullException=rp;});var we=x(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.InkObject=void 0;var Yt=xe(),Tn=ie(),va=_n(),Qt=H(),Ni=fe(),Sa=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let n=t.ContentAtPath(e).obj;if(n){let i=n.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Yt.Path;else {let e=[],t=this,n=(0, Qt.asOrNull)(t.parent,Tn.Container);for(;n!==null;){let i=(0, Qt.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Ni.throwNullException)("namedChild.name");e.unshift(new Yt.Path.Component(i.name));}else e.unshift(new Yt.Path.Component(n.content.indexOf(t)));t=n,n=(0, Qt.asOrNull)(n.parent,Tn.Container);}this._path=new Yt.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Ni.throwNullException)("path");if(e.isRelative){let t=(0, Qt.asOrNull)(this,Tn.Container);return t===null&&(va.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, Qt.asOrNull)(this.parent,Tn.Container),va.Debug.Assert(t!==null,"Expected parent to be a container"),va.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Ni.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Ni.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,n=Math.min(e.length,t.length),i=-1;for(let u=0;u<n;++u){let l=t.GetComponent(u),h=e.GetComponent(u);if(l.Equals(h))i=u;else break}if(i==-1)return e;let a=t.componentCount-1-i,s=[];for(let u=0;u<a;++u)s.push(Yt.Path.Component.ToParent());for(let u=i+1;u<e.componentCount;++u)s.push(e.GetComponent(u));return new Yt.Path(s,true)}CompactPathString(e){let t=null,n=null;return e.isRelative?(n=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(n=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),n.length<t.length?n:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, Qt.asOrNull)(e,Tn.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,n){e[t]&&(e[t]=null),e[t]=n,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};Ii.InkObject=Sa;});var Ft=x(Vi=>{Object.defineProperty(Vi,"__esModule",{value:true});Vi.StringBuilder=void 0;var Ea=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=`
2
- `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(n,i)=>typeof t[i]<"u"?t[i]:n);}toString(){return this.string}Clear(){this.string="";}};Vi.StringBuilder=Ea;});var Te=x(Zt=>{Object.defineProperty(Zt,"__esModule",{value:true});Zt.InkList=Zt.InkListItem=void 0;var Ue=fe(),sp=Ft(),_e=class r{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new 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(e){if(e instanceof r){let t=e;return t.itemName==this.itemName&&t.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(e){let t=JSON.parse(e);if(!r.isLikeInkListItem(t))return r.Null;let n=t;return new r(n.originName,n.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};Zt.InkListItem=_e;var Da=class r extends Map{constructor(){if(super(arguments[0]instanceof r?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof r){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, Ue.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, Ue.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var n;if(e==null||e=="")return new r;let i=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(i)return i.value===null?(0, Ue.throwNullException)("listValue.value"):new r(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof _e){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, Ue.throwNullException)("this.origins");for(let i of this.origins)if(i.name==n.originName){let a=i.TryGetValueForItem(n,0);if(a.exists){this.Add(n,a.result);return}else throw new Error("Could not add the item "+n+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let n=e,i=null;if(this.origins===null)return (0, Ue.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, Ue.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=r.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new _e(i.name,n),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(_e.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let n=e.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${e}`);this.set(n,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(n=>n.name==e?(t=n,false):true),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=_e.fromSerializedKey(e);if(t.originName===null)return (0, Ue.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:_e.Null,Value:0};for(let[t,n]of this){let i=_e.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:i,Value:n});}return e}get minItem(){let e={Key:_e.Null,Value:0};for(let[t,n]of this){let i=_e.fromSerializedKey(t);(e.Key.isNull||n<e.Value)&&(e={Key:i,Value:n});}return e}get inverse(){let e=new r;if(this.origins!=null)for(let t of this.origins)for(let[n,i]of t.items){let a=_e.fromSerializedKey(n);this.ContainsKey(a)||e.Add(a,i);}return e}get all(){let e=new r;if(this.origins!=null)for(let t of this.origins)for(let[n,i]of t.items){let a=_e.fromSerializedKey(n);e.set(a.serialized(),i);}return e}Union(e){let t=new r(this);for(let[n,i]of e)t.set(n,i);return t}Intersect(e){let t=new r;for(let[n,i]of this)e.has(n)&&t.set(n,i);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new r(this);for(let[n]of e)t.delete(n);return t}Contains(e){if(typeof e=="string")return this.ContainsItemNamed(e);let t=e;if(t.size==0||this.size==0)return false;for(let[n]of t)if(!this.has(n))return false;return true}GreaterThan(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>e.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<e.minItem.Value}LessThanOrEquals(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<=e.maxItem.Value&&this.minItem.Value<=e.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(e,t){if(this.Count==0)return new r;let n=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof r&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof r&&t.Count>0&&(a=t.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(e){if(!(e instanceof r)||e.Count!=this.Count)return false;for(let[t]of this)if(!e.has(t))return false;return true}get orderedItems(){let e=new Array;for(let[t,n]of this){let i=_e.fromSerializedKey(t);e.push({Key:i,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, Ue.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, Ue.throwNullException)("y.Key.originName"):t.Value==n.Value?t.Key.originName.localeCompare(n.Key.originName):t.Value<n.Value?-1:t.Value>n.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new sp.StringBuilder;for(let n=0;n<e.length;n++){n>0&&t.Append(", ");let i=e[n].Key;if(i.itemName===null)return (0, Ue.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};Zt.InkList=Da;});var On=x(ki=>{Object.defineProperty(ki,"__esModule",{value:true});ki.StoryException=void 0;var ba=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};ki.StoryException=ba;});var en=x(gt=>{Object.defineProperty(gt,"__esModule",{value:true});gt.tryParseFloat=gt.tryParseInt=gt.tryGetValueFromMap=void 0;function ap(r,e,t){if(r===null)return {result:t,exists:false};let n=r.get(e);return typeof n>"u"?{result:t,exists:false}:{result:n,exists:true}}gt.tryGetValueFromMap=ap;function op(r,e=0){let t=parseInt(r);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}gt.tryParseInt=op;function lp(r,e=0){let t=parseFloat(r);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}gt.tryParseFloat=lp;});var ee=x(te=>{Object.defineProperty(te,"__esModule",{value:true});te.ValueType=te.ListValue=te.VariablePointerValue=te.DivertTargetValue=te.StringValue=te.FloatValue=te.IntValue=te.BoolValue=te.Value=te.AbstractValue=void 0;var Ru=we(),Lu=xe(),Nt=Te(),up=On(),Pn=H(),Bu=en(),Re=fe(),Ri=class r extends Ru.InkObject{static Create(e,t){if(t){if(t===Y.Int&&Number.isInteger(Number(e)))return new Xe(Number(e));if(t===Y.Float&&!isNaN(e))return new Ye(Number(e))}if(typeof e=="boolean")return new tn(!!e);if(typeof e=="string")return new ut(String(e));if(Number.isInteger(Number(e)))return new Xe(Number(e));if(isNaN(e)){if(e instanceof Lu.Path)return new Li((0, Pn.asOrThrows)(e,Lu.Path));if(e instanceof Nt.InkList)return new Bi((0, Pn.asOrThrows)(e,Nt.InkList))}else return new Ye(Number(e));return null}Copy(){return (0, Pn.asOrThrows)(r.Create(this.valueObject),Ru.InkObject)}BadCastException(e){return new up.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};te.AbstractValue=Ri;var Ke=class extends Ri{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value.toString()}};te.Value=Ke;var tn=class extends Ke{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return Y.Bool}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Y.Int)return new Xe(this.value?1:0);if(e==Y.Float)return new Ye(this.value?1:0);if(e==Y.String)return new ut(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};te.BoolValue=tn;var Xe=class extends Ke{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return Y.Int}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Y.Bool)return new tn(this.value!==0);if(e==Y.Float)return new Ye(this.value);if(e==Y.String)return new ut(""+this.value);throw this.BadCastException(e)}};te.IntValue=Xe;var Ye=class extends Ke{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return Y.Float}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Y.Bool)return new tn(this.value!==0);if(e==Y.Int)return new Xe(this.value);if(e==Y.String)return new ut(""+this.value);throw this.BadCastException(e)}};te.FloatValue=Ye;var ut=class extends Ke{constructor(e){if(super(e||""),this._isNewline=this.value==`
3
- `,this._isInlineWhitespace=true,this.value===null)return (0, Re.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return Y.String}get isTruthy(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==Y.Int){let t=(0, Bu.tryParseInt)(this.value);if(t.exists)return new Xe(t.result);throw this.BadCastException(e)}if(e==Y.Float){let t=(0, Bu.tryParseFloat)(this.value);if(t.exists)return new Ye(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};te.StringValue=ut;var Li=class extends Ke{constructor(e=null){super(e);}get valueType(){return Y.DivertTarget}get targetPath(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};te.DivertTargetValue=Li;var Aa=class r extends Ke{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return Y.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new r(this.variableName,this.contextIndex)}};te.VariablePointerValue=Aa;var Bi=class r extends Ke{get isTruthy(){return this.value===null?(0, Re.throwNullException)("this.value"):this.value.Count>0}get valueType(){return Y.List}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==Y.Int){let t=this.value.maxItem;return t.Key.isNull?new Xe(0):new Xe(t.Value)}else if(e==Y.Float){let t=this.value.maxItem;return t.Key.isNull?new Ye(0):new Ye(t.Value)}else if(e==Y.String){let t=this.value.maxItem;return t.Key.isNull?new ut(""):new ut(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new Nt.InkList:e instanceof Nt.InkList?this.value=new Nt.InkList(e):e instanceof Nt.InkListItem&&typeof t=="number"&&(this.value=new Nt.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, Pn.asOrNull)(e,r),i=(0, Pn.asOrNull)(t,r);if(i&&i.value===null)return (0, Re.throwNullException)("newList.value");if(n&&n.value===null)return (0, Re.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};te.ListValue=Bi;var Y;(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";})(Y||(te.ValueType=Y={}));});var Wu=x(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.SearchResult=void 0;var hp=ie(),xa=class r{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof hp.Container?this.obj:null}copy(){let e=new r;return e.obj=this.obj,e.approximate=this.approximate,e}};Wi.SearchResult=xa;});var ie=x(Nn=>{Object.defineProperty(Nn,"__esModule",{value:true});Nn.Container=void 0;var cp=ee(),ju=fe(),dp=Ft(),nn=we(),pp=Wu(),qu=xe(),Mu=_n(),fp=en(),Ct=H(),Fn=class r extends nn.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(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,n]of this.namedContent){let i=(0, Ct.asOrThrows)(n,nn.InkObject);e.set(t,i);}for(let t of this.content){let n=(0, Ct.asINamedContentOrNull)(t);n!=null&&n.hasValidName&&e.delete(n.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[n]of t)this.namedContent.delete(n);if(e!=null)for(let[,n]of e){let i=(0, Ct.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=r.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=r.CountFlags.Turns),this.countingAtStartOnly&&(e|=r.CountFlags.CountStartOnly),e==r.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&r.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&r.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&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 e=[],t=this;for(;t instanceof r;)t.content.length>0&&(e.push(new qu.Path.Component(0)),t=t.content[0]);return new qu.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let n of t)this.AddContent(n);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, Ct.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Mu.Debug.AssertType(e,nn.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, Ct.asOrThrows)(e,nn.InkObject);if(t.parent=this,e.name===null)return (0, ju.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let i=new pp.SearchResult;i.approximate=false;let a=this,s=this;for(let o=t;o<n;++o){let u=e.GetComponent(o);if(a==null){i.approximate=true;break}let l=a.ContentWithPathComponent(u);if(l==null){i.approximate=true;break}let h=(0, Ct.asOrNull)(l,r);if(o<n-1&&h==null){i.approximate=true;break}s=l,a=h;}return i.obj=s,i}InsertContent(e,t){if(this.content.splice(t,0,e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}AddContentsOfContainer(e){this.content.push(...e.content);for(let t of e.content)t.parent=this,this.TryAddNamedContent(t);}ContentWithPathComponent(e){if(e.isIndex)return e.index>=0&&e.index<this.content.length?this.content[e.index]:null;if(e.isParent)return this.parent;{if(e.name===null)return (0, ju.throwNullException)("component.name");let t=(0, fp.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, Ct.asOrThrows)(t.result,nn.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new dp.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],n=arguments[2];function i(){for(let o=0;o<4*t;++o)e.Append(" ");}i(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==n&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof r?o.BuildStringOfHierarchy(e,t,n):(i(),o instanceof cp.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
4
- `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof r)&&o==n&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, Ct.asOrThrows)(o,nn.InkObject))>=0||a.set(s,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,s]of a)Mu.Debug.AssertType(s,r,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,i(),e.Append("]");}};Nn.Container=Fn;(function(r){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(r.CountFlags||(r.CountFlags={}));})(Fn||(Nn.Container=Fn={}));});var me=x(Vn=>{Object.defineProperty(Vn,"__esModule",{value:true});Vn.ControlCommand=void 0;var mp=we(),In=class r extends mp.InkObject{get commandType(){return this._commandType}constructor(e=r.CommandType.NotSet){super(),this._commandType=e;}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()}};Vn.ControlCommand=In;(function(r){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(r.CommandType||(r.CommandType={}));})(In||(Vn.ControlCommand=In={}));});var Le=x(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.Expression=void 0;var Gu=ie(),wa=me(),gp=Q(),_a=class extends gp.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new Gu.Container;return e.AddContent(wa.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(wa.ControlCommand.EvalOutput()),e.AddContent(wa.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new Gu.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let n=t.Copy();n&&e.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};ji.Expression=_a;});var It=x(qi=>{Object.defineProperty(qi,"__esModule",{value:true});qi.Void=void 0;var Cp=we(),Ta=class extends Cp.InkObject{toString(){return "Void"}};qi.Void=Ta;});var Qe=x(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.NativeFunctionCall=void 0;var O=ee(),kn=On(),yp=It(),Mi=Te(),vp=we(),Be=H(),Oe=fe(),B=class r extends vp.InkObject{static CallWithName(e){return new r(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, Oe.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(r._nativeFunctions===null?(0, Oe.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=r._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof yp.Void)throw new kn.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 O.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),i=n[0].valueType;return i==O.ValueType.Int?this.CallType(n):i==O.ValueType.Float?this.CallType(n):i==O.ValueType.String?this.CallType(n):i==O.ValueType.DivertTarget?this.CallType(n):i==O.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, Be.asOrThrows)(e[0],O.Value),n=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, Oe.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){let o=O.ValueType[n];throw new kn.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let u=(0, Be.asOrThrows)(e[1],O.Value),l=s;if(i.value===null||u.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=l(i.value,u.value);return O.Value.Create(h)}else {let o=s;if(i.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=o(i.value);return this.name===r.Int?O.Value.Create(u,O.ValueType.Int):this.name===r.Float?O.Value.Create(u,O.ValueType.Float):O.Value.Create(u,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof O.ListValue&&e[1]instanceof O.IntValue)return this.CallListIncrementOperation(e);let t=(0, Be.asOrThrows)(e[0],O.Value),n=(0, Be.asOrThrows)(e[1],O.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=O.ValueType.List||n.valueType!=O.ValueType.List)){if(this._operationFuncs===null)return (0, Oe.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(O.ValueType.Int);if(i===null)return (0, Oe.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, Be.asBooleanOrThrows)(i(t.isTruthy?1:0,n.isTruthy?1:0));return new O.BoolValue(a)}if(t.valueType==O.ValueType.List&&n.valueType==O.ValueType.List)return this.CallType([t,n]);throw new kn.StoryException("Can not call use "+this.name+" operation on "+O.ValueType[t.valueType]+" and "+O.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, Be.asOrThrows)(e[0],O.ListValue),n=(0, Be.asOrThrows)(e[1],O.IntValue),i=new Mi.InkList;if(t.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=Mi.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, Oe.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(O.ValueType.Int);if(n.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(s,n.value),h=null;if(t.value.origins===null)return (0, Oe.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of t.value.origins)if(c.name==o.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(l,Mi.InkListItem.Null);c.exists&&i.Add(c.result,l);}}return new O.ListValue(i)}CoerceValuesToSingleType(e){let t=O.ValueType.Int,n=null;for(let a of e){let s=(0, Be.asOrThrows)(a,O.Value);s.valueType>t&&(t=s.valueType),s.valueType==O.ValueType.List&&(n=(0, Be.asOrNull)(s,O.ListValue));}let i=[];if(O.ValueType[t]==O.ValueType[O.ValueType.List])for(let a of e){let s=(0, Be.asOrThrows)(a,O.Value);if(s.valueType==O.ValueType.List)i.push(s);else if(s.valueType==O.ValueType.Int){let o=parseInt(s.valueObject);if(n=(0, Be.asOrThrows)(n,O.ListValue),n.value===null)return (0, Oe.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=n.value.originOfMaxItem;if(u===null)return (0, Oe.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(o,Mi.InkListItem.Null);if(l.exists){let h=new O.ListValue(l.result,o);i.push(h);}else throw new kn.StoryException("Could not find List item with the value "+o+" in "+u.name)}else {let o=O.ValueType[s.valueType];throw new kn.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, Be.asOrThrows)(a,O.Value).Cast(t);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 e=arguments[0];r.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=true,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,i)=>n+i),this.AddIntBinaryOp(this.Subtract,(n,i)=>n-i),this.AddIntBinaryOp(this.Multiply,(n,i)=>n*i),this.AddIntBinaryOp(this.Divide,(n,i)=>Math.floor(n/i)),this.AddIntBinaryOp(this.Mod,(n,i)=>n%i),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,i)=>n==i),this.AddIntBinaryOp(this.Greater,(n,i)=>n>i),this.AddIntBinaryOp(this.Less,(n,i)=>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 e=(n,i)=>n.Equals(i),t=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,O.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,O.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,n,i){if(this._nativeFunctions===null)return (0, Oe.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new r(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,O.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,O.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,O.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,O.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,O.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,O.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,O.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};Gi.NativeFunctionCall=B;B.Add="+";B.Subtract="-";B.Divide="/";B.Multiply="*";B.Mod="%";B.Negate="_";B.Equal="==";B.Greater=">";B.Less="<";B.GreaterThanOrEquals=">=";B.LessThanOrEquals="<=";B.NotEquals="!=";B.Not="!";B.And="&&";B.Or="||";B.Min="MIN";B.Max="MAX";B.Pow="POW";B.Floor="FLOOR";B.Ceiling="CEILING";B.Int="INT";B.Float="FLOAT";B.Has="?";B.Hasnt="!?";B.Intersect="^";B.ListMin="LIST_MIN";B.ListMax="LIST_MAX";B.All="LIST_ALL";B.Count="LIST_COUNT";B.ValueOfList="LIST_VALUE";B.Invert="LIST_INVERT";B._nativeFunctions=null;});var Ji=x($i=>{Object.defineProperty($i,"__esModule",{value:true});$i.NumberExpression=void 0;var Sp=Le(),Oa=ee(),Ep=H(),Pa=class r extends Sp.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new Oa.IntValue(this.value)):this.isFloat()?n.AddContent(new Oa.FloatValue(this.value)):this.isBool()&&n.AddContent(new Oa.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, Ep.asOrNull)(e,r);return t?t.subtype==this.subtype&&t.value==this.value:false}};$i.NumberExpression=Pa;});var Fa=x(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.UnaryExpression=void 0;var Dp=Le(),bp=Qe(),rn=Ji(),Ap=H(),Rn=class extends Dp.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(bp.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};Hi.UnaryExpression=Rn;Rn.WithInner=(r,e)=>{let t=(0, Ap.asOrNull)(r,rn.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new rn.NumberExpression(-t.value,"int");if(t.isFloat())return new rn.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new rn.NumberExpression(t.value==0,"bool");if(t.isFloat())return new rn.NumberExpression(t.value==0,"bool");if(t.isBool())return new rn.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new Rn(r,e)};});var Ia=x(zi=>{Object.defineProperty(zi,"__esModule",{value:true});zi.BinaryExpression=void 0;var xp=Le(),wp=Qe(),_p=Fa(),Tp=H(),Na=class extends xp.Expression{constructor(e,t,n){super(),this.opName=n,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(wp.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, Tp.asOrNull)(this.leftExpression,_p.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};zi.BinaryExpression=Na;});var Bn=x(Ui=>{Object.defineProperty(Ui,"__esModule",{value:true});Ui.CharacterSet=void 0;var Ln=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,n)=>{for(let i=t.charCodeAt(0);i<=n.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let n of t)this.Add(n);else for(let n of t.set)this.Add(n);return this},e&&this.AddCharacters(e);}};Ui.CharacterSet=Ln;Ln.FromRange=(r,e)=>new Ln().AddRange(r,e);});var Ju=x(Ki=>{Object.defineProperty(Ki,"__esModule",{value:true});Ki.CharacterRange=void 0;var $u=Bn(),Wn=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new $u.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 $u.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}};Ki.CharacterRange=Wn;Wn.Define=(r,e,t=[])=>new Wn(r,e,t);});var Yi=x(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.ChoicePoint=void 0;var Op=we(),Pp=xe(),Va=fe(),ka=class extends Op.InkObject{constructor(e=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, Va.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Va.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new Pp.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Va.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};Xi.ChoicePoint=ka;});var Vt=x(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.PushPopType=void 0;var Hu;(function(r){r[r.Tunnel=0]="Tunnel",r[r.Function=1]="Function",r[r.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Hu||(Qi.PushPopType=Hu={}));});var jn=x(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.Pointer=void 0;var Fp=xe(),Ra=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 Fp.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(e){return new r(e,0)}static get Null(){return new r(null,-1)}};Zi.Pointer=Ra;});var Ze=x(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.Divert=void 0;var Np=xe(),Ip=Vt(),Vp=Ft(),kp=we(),La=jn(),zu=ie(),er=fe(),Ba=class r extends kp.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=La.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, er.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, er.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, er.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof zu.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=La.Pointer.StartOf(e instanceof zu.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new Np.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=La.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof e<"u"&&(this.pushesToStack=true,this.stackPushType=e);}Equals(e){let t=e;return t instanceof r&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, er.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new Vp.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==Ip.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};tr.Divert=Ba;});var ht=x(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.SymbolType=void 0;var Uu;(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";})(Uu||(nr.SymbolType=Uu={}));});var yt=x(ir=>{Object.defineProperty(ir,"__esModule",{value:true});ir.VariableAssignment=void 0;var Rp=we(),Wa=class extends Rp.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};ir.VariableAssignment=Wa;});var sn=x(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.Choice=void 0;var Lp=Yi(),rr=ie(),vt=me(),ja=Ze(),Ku=ee(),Bp=Q(),Wp=ht(),Xu=yt(),qa=class extends Bp.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,n){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new rr.Container,this._runtimeChoice=new Lp.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(vt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Ku.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Xu.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(vt.ControlCommand.BeginString()),this._divertToStartContentOuter=new ja.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new ja.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new rr.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(vt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(vt.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(vt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(vt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new rr.Container,this.startContent){this._returnToR2=new Ku.DivertTargetValue,this._innerContentContainer.AddContent(vt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(vt.ControlCommand.EvalEnd());let i=new Xu.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new ja.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new rr.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=e,this.choiceOnlyContent=t,this.innerContent=n,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(e){var t;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(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Wp.SymbolType.SubFlowAndWeave);}};sr.Choice=qa;});var Yu=x(or=>{Object.defineProperty(or,"__esModule",{value:true});or.StringParserElement=void 0;var ar=class r{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{r._uniqueIdCounter++,this.uniqueId=r._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};or.StringParserElement=ar;ar._uniqueIdCounter=1e3;});var Zu=x(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.StringParserState=void 0;var Qu=Yu(),Ma=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new Qu.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(t),n.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],n=this._stack[this._numElements-1];t.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new Qu.StringParserElement;this._numElements=1;}};lr.StringParserState=Ma;});var $a=x(kt=>{Object.defineProperty(kt,"__esModule",{value:true});kt.StringParser=kt.ParseSuccess=void 0;var Ga=Bn(),jp=Zu();kt.ParseSuccess=Symbol("ParseSuccessStruct");var qn=class r{constructor(e){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,u=this.LineRemainder();u===null||u.length===0?o="end of line":o=`'${u}'`,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(),u=[],l=this.ParseObject(n);if(l===null)return this.FailRule(o);this.TryAddResultToList(l,u,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,u,s),c=null,h!==null){if(c=this.ParseObject(n),c===null)break;this.TryAddResultToList(c,u,s);}}while((h!==null||c!==null)&&!(h===r.ParseSuccess&&c==r.ParseSuccess)&&this.remainingLength>0);return u.length===0?this.FailRule(o):this.SucceedRule(o,u)},this.ParseString=n=>{if(n.length>this.remainingLength)return null;let i=this.BeginRule(),a=this.index,s=this.characterInLineIndex,o=this.lineIndex,u=true;for(let l=0;l<n.length;l+=1){let h=n[l];if(this._chars[a]!==h){u=false;break}h===`
6
- `&&(o++,s=-1),a++,s++;}return this.index=a,this.characterInLineIndex=s,this.lineIndex=o,u?this.SucceedRule(i,n):this.FailRule(i)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){let n=this._chars[this.index];return n===`
7
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,i=-1)=>this.ParseCharactersFromString(n,false,i),this.ParseUntilCharactersFromCharSet=(n,i=-1)=>this.ParseCharactersFromCharSet(n,false,i),this.ParseCharactersFromString=(n,i=-1,a=-1)=>{let s=new Ga.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,u=this.characterInLineIndex,l=this.lineIndex,h=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===i&&h<a;)this._chars[o]===`
8
- `&&(l+=1,u=-1),o+=1,u+=1,h+=1;return this.index=o,this.characterInLineIndex=u,this.lineIndex=l,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(`
1
+ 'use strict';var pixiVn=require('@drincs/pixi-vn'),canvas=require('@drincs/pixi-vn/canvas'),characters=require('@drincs/pixi-vn/characters'),S=require('zod'),narration=require('@drincs/pixi-vn/narration'),sound=require('@drincs/pixi-vn/sound'),storage=require('@drincs/pixi-vn/storage'),qC=require('ajv');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var S__default=/*#__PURE__*/_interopDefault(S);var qC__default=/*#__PURE__*/_interopDefault(qC);var Pc=Object.create;var Ll=Object.defineProperty;var Tc=Object.getOwnPropertyDescriptor;var Fc=Object.getOwnPropertyNames;var Nc=Object.getPrototypeOf,Ic=Object.prototype.hasOwnProperty;var _t=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var x=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Vc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fc(e))!Ic.call(r,i)&&i!==t&&Ll(r,i,{get:()=>e[i],enumerable:!(n=Tc(e,i))||n.enumerable});return r};var Hs=(r,e,t)=>(t=r!=null?Pc(Nc(r)):{},Vc(Ll(t,"default",{value:r,enumerable:true}),r));var da=x(Di=>{Object.defineProperty(Di,"__esModule",{value:true});Di.CompilerOptions=void 0;var pa=class{constructor(e=null,t=[],n=false,i=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=n,this.errorHandler=i,this.fileHandler=a;}};Di.CompilerOptions=pa;});var Fu=x(bi=>{Object.defineProperty(bi,"__esModule",{value:true});bi.DebugSourceRange=void 0;var fa=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};bi.DebugSourceRange=fa;});var Ut=x(Ai=>{Object.defineProperty(Ai,"__esModule",{value:true});Ai.ErrorType=void 0;var Nu;(function(r){r[r.Author=0]="Author",r[r.Warning=1]="Warning",r[r.Error=2]="Error";})(Nu||(Ai.ErrorType=Nu={}));});var Iu=x(wi=>{Object.defineProperty(wi,"__esModule",{value:true});wi.Argument=void 0;var ma=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};wi.Argument=ma;});var z=x(ue=>{Object.defineProperty(ue,"__esModule",{value:true});ue.filterUndef=ue.isEquatable=ue.nullIfUndefined=ue.asINamedContentOrNull=ue.asBooleanOrThrows=ue.asNumberOrThrows=ue.asOrThrows=ue.asOrNull=void 0;function Yp(r,e){return r instanceof e?Vu(r):null}ue.asOrNull=Yp;function Qp(r,e){if(r instanceof e)return Vu(r);throw new Error(`${r} is not of type ${e}`)}ue.asOrThrows=Qp;function Zp(r){if(typeof r=="number")return r;throw new Error(`${r} is not a number`)}ue.asNumberOrThrows=Zp;function ed(r){if(typeof r=="boolean")return r;throw new Error(`${r} is not a boolean`)}ue.asBooleanOrThrows=ed;function td(r){return r.hasValidName&&r.name?r:null}ue.asINamedContentOrNull=td;function nd(r){return typeof r>"u"?null:r}ue.nullIfUndefined=nd;function id(r){return typeof r=="object"&&typeof r.Equals=="function"}ue.isEquatable=id;function Vu(r,e){return r}function rd(r){return r!=null}ue.filterUndef=rd;});var Z=x(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.ParsedObject=void 0;var ku=z(),ga=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=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let n of t)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let n=(0, ku.asOrNull)(this,e);if(n!==null&&(t===null||t(n)===true))return n;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,n)=>{let i=Array.isArray(n)?n:[],a=(0, ku.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&i.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,n=false){if(t===null&&(t=this),!(t._alreadyHadError&&!n||t._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(e,t,n);else throw new Error(`No parent object to send error to: ${e}`);n?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};xi.ParsedObject=ga;});var Oi=x(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.AuthorWarning=void 0;var sd=Z(),Ca=class extends sd.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};_i.AuthorWarning=Ca;});var Oe=x(xn=>{Object.defineProperty(xn,"__esModule",{value:true});xn.Path=void 0;var Kt=class r{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof r.Component&&arguments[1]instanceof r){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new r(e)}else return r.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new r;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new r,n=0;for(let i=0;i<e._components.length&&e._components[i].isParent;++i)n++;for(let i=0;i<this._components.length-n;++i)t._components.push(this._components[i]);for(let i=n;i<e._components.length;++i)t._components.push(e._components[i]);return t}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let t=this._componentsString.split(".");for(let n of t)/^(\-|\+)?([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(e){if(e==null||e._components.length!=this._components.length||e.isRelative!=this.isRelative)return false;for(let t=0,n=e._components.length;t<n;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new r;return t._components.push(...this._components),t._components.push(e),t}};xn.Path=Kt;Kt.parentId="^";(function(r){class e{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 e(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=e;})(Kt||(xn.Path=Kt={}));});var _n=x(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.Debug=void 0;var Ru;(function(r){function e(n,i,a){t(n instanceof i,a);}r.AssertType=e;function t(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}r.Assert=t;})(Ru||(Pi.Debug=Ru={}));});var fe=x(Xt=>{Object.defineProperty(Xt,"__esModule",{value:true});Xt.throwNullException=Xt.NullException=void 0;var Ti=class extends Error{};Xt.NullException=Ti;function ad(r){throw new Ti(`${r} is null or undefined`)}Xt.throwNullException=ad;});var Pe=x(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.InkObject=void 0;var Yt=Oe(),On=re(),ya=_n(),Qt=z(),Fi=fe(),va=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let n=t.ContentAtPath(e).obj;if(n){let i=n.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Yt.Path;else {let e=[],t=this,n=(0, Qt.asOrNull)(t.parent,On.Container);for(;n!==null;){let i=(0, Qt.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Fi.throwNullException)("namedChild.name");e.unshift(new Yt.Path.Component(i.name));}else e.unshift(new Yt.Path.Component(n.content.indexOf(t)));t=n,n=(0, Qt.asOrNull)(n.parent,On.Container);}this._path=new Yt.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Fi.throwNullException)("path");if(e.isRelative){let t=(0, Qt.asOrNull)(this,On.Container);return t===null&&(ya.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, Qt.asOrNull)(this.parent,On.Container),ya.Debug.Assert(t!==null,"Expected parent to be a container"),ya.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Fi.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Fi.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,n=Math.min(e.length,t.length),i=-1;for(let l=0;l<n;++l){let u=t.GetComponent(l),h=e.GetComponent(l);if(u.Equals(h))i=l;else break}if(i==-1)return e;let a=t.componentCount-1-i,s=[];for(let l=0;l<a;++l)s.push(Yt.Path.Component.ToParent());for(let l=i+1;l<e.componentCount;++l)s.push(e.GetComponent(l));return new Yt.Path(s,true)}CompactPathString(e){let t=null,n=null;return e.isRelative?(n=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(n=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),n.length<t.length?n:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, Qt.asOrNull)(e,On.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,n){e[t]&&(e[t]=null),e[t]=n,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};Ni.InkObject=va;});var Nt=x(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.StringBuilder=void 0;var Sa=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=`
2
+ `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(n,i)=>typeof t[i]<"u"?t[i]:n);}toString(){return this.string}Clear(){this.string="";}};Ii.StringBuilder=Sa;});var Fe=x(Zt=>{Object.defineProperty(Zt,"__esModule",{value:true});Zt.InkList=Zt.InkListItem=void 0;var Ke=fe(),od=Nt(),Te=class r{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new 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(e){if(e instanceof r){let t=e;return t.itemName==this.itemName&&t.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(e){let t=JSON.parse(e);if(!r.isLikeInkListItem(t))return r.Null;let n=t;return new r(n.originName,n.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};Zt.InkListItem=Te;var Ea=class r extends Map{constructor(){if(super(arguments[0]instanceof r?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof r){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, Ke.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, Ke.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var n;if(e==null||e=="")return new r;let i=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(i)return i.value===null?(0, Ke.throwNullException)("listValue.value"):new r(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof Te){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, Ke.throwNullException)("this.origins");for(let i of this.origins)if(i.name==n.originName){let a=i.TryGetValueForItem(n,0);if(a.exists){this.Add(n,a.result);return}else throw new Error("Could not add the item "+n+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let n=e,i=null;if(this.origins===null)return (0, Ke.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, Ke.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=r.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new Te(i.name,n),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(Te.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let n=e.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${e}`);this.set(n,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(n=>n.name==e?(t=n,false):true),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=Te.fromSerializedKey(e);if(t.originName===null)return (0, Ke.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:Te.Null,Value:0};for(let[t,n]of this){let i=Te.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:i,Value:n});}return e}get minItem(){let e={Key:Te.Null,Value:0};for(let[t,n]of this){let i=Te.fromSerializedKey(t);(e.Key.isNull||n<e.Value)&&(e={Key:i,Value:n});}return e}get inverse(){let e=new r;if(this.origins!=null)for(let t of this.origins)for(let[n,i]of t.items){let a=Te.fromSerializedKey(n);this.ContainsKey(a)||e.Add(a,i);}return e}get all(){let e=new r;if(this.origins!=null)for(let t of this.origins)for(let[n,i]of t.items){let a=Te.fromSerializedKey(n);e.set(a.serialized(),i);}return e}Union(e){let t=new r(this);for(let[n,i]of e)t.set(n,i);return t}Intersect(e){let t=new r;for(let[n,i]of this)e.has(n)&&t.set(n,i);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new r(this);for(let[n]of e)t.delete(n);return t}Contains(e){if(typeof e=="string")return this.ContainsItemNamed(e);let t=e;if(t.size==0||this.size==0)return false;for(let[n]of t)if(!this.has(n))return false;return true}GreaterThan(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>e.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<e.minItem.Value}LessThanOrEquals(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<=e.maxItem.Value&&this.minItem.Value<=e.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(e,t){if(this.Count==0)return new r;let n=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof r&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof r&&t.Count>0&&(a=t.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(e){if(!(e instanceof r)||e.Count!=this.Count)return false;for(let[t]of this)if(!e.has(t))return false;return true}get orderedItems(){let e=new Array;for(let[t,n]of this){let i=Te.fromSerializedKey(t);e.push({Key:i,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, Ke.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, Ke.throwNullException)("y.Key.originName"):t.Value==n.Value?t.Key.originName.localeCompare(n.Key.originName):t.Value<n.Value?-1:t.Value>n.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new od.StringBuilder;for(let n=0;n<e.length;n++){n>0&&t.Append(", ");let i=e[n].Key;if(i.itemName===null)return (0, Ke.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};Zt.InkList=Ea;});var Pn=x(Vi=>{Object.defineProperty(Vi,"__esModule",{value:true});Vi.StoryException=void 0;var Da=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};Vi.StoryException=Da;});var en=x(Ct=>{Object.defineProperty(Ct,"__esModule",{value:true});Ct.tryParseFloat=Ct.tryParseInt=Ct.tryGetValueFromMap=void 0;function ld(r,e,t){if(r===null)return {result:t,exists:false};let n=r.get(e);return typeof n>"u"?{result:t,exists:false}:{result:n,exists:true}}Ct.tryGetValueFromMap=ld;function ud(r,e=0){let t=parseInt(r);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ct.tryParseInt=ud;function hd(r,e=0){let t=parseFloat(r);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ct.tryParseFloat=hd;});var ee=x(te=>{Object.defineProperty(te,"__esModule",{value:true});te.ValueType=te.ListValue=te.VariablePointerValue=te.DivertTargetValue=te.StringValue=te.FloatValue=te.IntValue=te.BoolValue=te.Value=te.AbstractValue=void 0;var Lu=Pe(),Bu=Oe(),It=Fe(),cd=Pn(),Tn=z(),Wu=en(),Re=fe(),ki=class r extends Lu.InkObject{static Create(e,t){if(t){if(t===Q.Int&&Number.isInteger(Number(e)))return new Ye(Number(e));if(t===Q.Float&&!isNaN(e))return new Qe(Number(e))}if(typeof e=="boolean")return new tn(!!e);if(typeof e=="string")return new ht(String(e));if(Number.isInteger(Number(e)))return new Ye(Number(e));if(isNaN(e)){if(e instanceof Bu.Path)return new Ri((0, Tn.asOrThrows)(e,Bu.Path));if(e instanceof It.InkList)return new Li((0, Tn.asOrThrows)(e,It.InkList))}else return new Qe(Number(e));return null}Copy(){return (0, Tn.asOrThrows)(r.Create(this.valueObject),Lu.InkObject)}BadCastException(e){return new cd.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};te.AbstractValue=ki;var Xe=class extends ki{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value.toString()}};te.Value=Xe;var tn=class extends Xe{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return Q.Bool}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Q.Int)return new Ye(this.value?1:0);if(e==Q.Float)return new Qe(this.value?1:0);if(e==Q.String)return new ht(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};te.BoolValue=tn;var Ye=class extends Xe{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return Q.Int}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Q.Bool)return new tn(this.value!==0);if(e==Q.Float)return new Qe(this.value);if(e==Q.String)return new ht(""+this.value);throw this.BadCastException(e)}};te.IntValue=Ye;var Qe=class extends Xe{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return Q.Float}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==Q.Bool)return new tn(this.value!==0);if(e==Q.Int)return new Ye(this.value);if(e==Q.String)return new ht(""+this.value);throw this.BadCastException(e)}};te.FloatValue=Qe;var ht=class extends Xe{constructor(e){if(super(e||""),this._isNewline=this.value==`
3
+ `,this._isInlineWhitespace=true,this.value===null)return (0, Re.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return Q.String}get isTruthy(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==Q.Int){let t=(0, Wu.tryParseInt)(this.value);if(t.exists)return new Ye(t.result);throw this.BadCastException(e)}if(e==Q.Float){let t=(0, Wu.tryParseFloat)(this.value);if(t.exists)return new Qe(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};te.StringValue=ht;var Ri=class extends Xe{constructor(e=null){super(e);}get valueType(){return Q.DivertTarget}get targetPath(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};te.DivertTargetValue=Ri;var ba=class r extends Xe{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, Re.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return Q.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new r(this.variableName,this.contextIndex)}};te.VariablePointerValue=ba;var Li=class r extends Xe{get isTruthy(){return this.value===null?(0, Re.throwNullException)("this.value"):this.value.Count>0}get valueType(){return Q.List}Cast(e){if(this.value===null)return (0, Re.throwNullException)("Value.value");if(e==Q.Int){let t=this.value.maxItem;return t.Key.isNull?new Ye(0):new Ye(t.Value)}else if(e==Q.Float){let t=this.value.maxItem;return t.Key.isNull?new Qe(0):new Qe(t.Value)}else if(e==Q.String){let t=this.value.maxItem;return t.Key.isNull?new ht(""):new ht(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new It.InkList:e instanceof It.InkList?this.value=new It.InkList(e):e instanceof It.InkListItem&&typeof t=="number"&&(this.value=new It.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, Tn.asOrNull)(e,r),i=(0, Tn.asOrNull)(t,r);if(i&&i.value===null)return (0, Re.throwNullException)("newList.value");if(n&&n.value===null)return (0, Re.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};te.ListValue=Li;var Q;(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";})(Q||(te.ValueType=Q={}));});var ju=x(Bi=>{Object.defineProperty(Bi,"__esModule",{value:true});Bi.SearchResult=void 0;var pd=re(),Aa=class r{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof pd.Container?this.obj:null}copy(){let e=new r;return e.obj=this.obj,e.approximate=this.approximate,e}};Bi.SearchResult=Aa;});var re=x(Nn=>{Object.defineProperty(Nn,"__esModule",{value:true});Nn.Container=void 0;var dd=ee(),qu=fe(),fd=Nt(),nn=Pe(),md=ju(),Mu=Oe(),Gu=_n(),gd=en(),yt=z(),Fn=class r extends nn.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(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,n]of this.namedContent){let i=(0, yt.asOrThrows)(n,nn.InkObject);e.set(t,i);}for(let t of this.content){let n=(0, yt.asINamedContentOrNull)(t);n!=null&&n.hasValidName&&e.delete(n.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[n]of t)this.namedContent.delete(n);if(e!=null)for(let[,n]of e){let i=(0, yt.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=r.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=r.CountFlags.Turns),this.countingAtStartOnly&&(e|=r.CountFlags.CountStartOnly),e==r.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&r.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&r.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&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 e=[],t=this;for(;t instanceof r;)t.content.length>0&&(e.push(new Mu.Path.Component(0)),t=t.content[0]);return new Mu.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let n of t)this.AddContent(n);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, yt.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Gu.Debug.AssertType(e,nn.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, yt.asOrThrows)(e,nn.InkObject);if(t.parent=this,e.name===null)return (0, qu.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let i=new md.SearchResult;i.approximate=false;let a=this,s=this;for(let o=t;o<n;++o){let l=e.GetComponent(o);if(a==null){i.approximate=true;break}let u=a.ContentWithPathComponent(l);if(u==null){i.approximate=true;break}let h=(0, yt.asOrNull)(u,r);if(o<n-1&&h==null){i.approximate=true;break}s=u,a=h;}return i.obj=s,i}InsertContent(e,t){if(this.content.splice(t,0,e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}AddContentsOfContainer(e){this.content.push(...e.content);for(let t of e.content)t.parent=this,this.TryAddNamedContent(t);}ContentWithPathComponent(e){if(e.isIndex)return e.index>=0&&e.index<this.content.length?this.content[e.index]:null;if(e.isParent)return this.parent;{if(e.name===null)return (0, qu.throwNullException)("component.name");let t=(0, gd.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, yt.asOrThrows)(t.result,nn.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new fd.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],n=arguments[2];function i(){for(let o=0;o<4*t;++o)e.Append(" ");}i(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==n&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof r?o.BuildStringOfHierarchy(e,t,n):(i(),o instanceof dd.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
4
+ `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof r)&&o==n&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, yt.asOrThrows)(o,nn.InkObject))>=0||a.set(s,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,s]of a)Gu.Debug.AssertType(s,r,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,i(),e.Append("]");}};Nn.Container=Fn;(function(r){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(r.CountFlags||(r.CountFlags={}));})(Fn||(Nn.Container=Fn={}));});var me=x(Vn=>{Object.defineProperty(Vn,"__esModule",{value:true});Vn.ControlCommand=void 0;var Cd=Pe(),In=class r extends Cd.InkObject{get commandType(){return this._commandType}constructor(e=r.CommandType.NotSet){super(),this._commandType=e;}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()}};Vn.ControlCommand=In;(function(r){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(r.CommandType||(r.CommandType={}));})(In||(Vn.ControlCommand=In={}));});var Le=x(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.Expression=void 0;var $u=re(),wa=me(),yd=Z(),xa=class extends yd.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new $u.Container;return e.AddContent(wa.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(wa.ControlCommand.EvalOutput()),e.AddContent(wa.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new $u.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let n=t.Copy();n&&e.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};Wi.Expression=xa;});var Vt=x(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.Void=void 0;var vd=Pe(),_a=class extends vd.InkObject{toString(){return "Void"}};ji.Void=_a;});var Ze=x(Mi=>{Object.defineProperty(Mi,"__esModule",{value:true});Mi.NativeFunctionCall=void 0;var F=ee(),kn=Pn(),Sd=Vt(),qi=Fe(),Ed=Pe(),Be=z(),Ne=fe(),W=class r extends Ed.InkObject{static CallWithName(e){return new r(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, Ne.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(r._nativeFunctions===null?(0, Ne.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=r._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof Sd.Void)throw new kn.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 F.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),i=n[0].valueType;return i==F.ValueType.Int?this.CallType(n):i==F.ValueType.Float?this.CallType(n):i==F.ValueType.String?this.CallType(n):i==F.ValueType.DivertTarget?this.CallType(n):i==F.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, Be.asOrThrows)(e[0],F.Value),n=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, Ne.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){let o=F.ValueType[n];throw new kn.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, Be.asOrThrows)(e[1],F.Value),u=s;if(i.value===null||l.value===null)return (0, Ne.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(i.value,l.value);return F.Value.Create(h)}else {let o=s;if(i.value===null)return (0, Ne.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(i.value);return this.name===r.Int?F.Value.Create(l,F.ValueType.Int):this.name===r.Float?F.Value.Create(l,F.ValueType.Float):F.Value.Create(l,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof F.ListValue&&e[1]instanceof F.IntValue)return this.CallListIncrementOperation(e);let t=(0, Be.asOrThrows)(e[0],F.Value),n=(0, Be.asOrThrows)(e[1],F.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=F.ValueType.List||n.valueType!=F.ValueType.List)){if(this._operationFuncs===null)return (0, Ne.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(F.ValueType.Int);if(i===null)return (0, Ne.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, Be.asBooleanOrThrows)(i(t.isTruthy?1:0,n.isTruthy?1:0));return new F.BoolValue(a)}if(t.valueType==F.ValueType.List&&n.valueType==F.ValueType.List)return this.CallType([t,n]);throw new kn.StoryException("Can not call use "+this.name+" operation on "+F.ValueType[t.valueType]+" and "+F.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, Be.asOrThrows)(e[0],F.ListValue),n=(0, Be.asOrThrows)(e[1],F.IntValue),i=new qi.InkList;if(t.value===null)return (0, Ne.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=qi.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, Ne.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(F.ValueType.Int);if(n.value===null)return (0, Ne.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(s,n.value),h=null;if(t.value.origins===null)return (0, Ne.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let c of t.value.origins)if(c.name==o.originName){h=c;break}if(h!=null){let c=h.TryGetItemWithValue(u,qi.InkListItem.Null);c.exists&&i.Add(c.result,u);}}return new F.ListValue(i)}CoerceValuesToSingleType(e){let t=F.ValueType.Int,n=null;for(let a of e){let s=(0, Be.asOrThrows)(a,F.Value);s.valueType>t&&(t=s.valueType),s.valueType==F.ValueType.List&&(n=(0, Be.asOrNull)(s,F.ListValue));}let i=[];if(F.ValueType[t]==F.ValueType[F.ValueType.List])for(let a of e){let s=(0, Be.asOrThrows)(a,F.Value);if(s.valueType==F.ValueType.List)i.push(s);else if(s.valueType==F.ValueType.Int){let o=parseInt(s.valueObject);if(n=(0, Be.asOrThrows)(n,F.ListValue),n.value===null)return (0, Ne.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, Ne.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,qi.InkListItem.Null);if(u.exists){let h=new F.ListValue(u.result,o);i.push(h);}else throw new kn.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=F.ValueType[s.valueType];throw new kn.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, Be.asOrThrows)(a,F.Value).Cast(t);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 e=arguments[0];r.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=true,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(n,i)=>n+i),this.AddIntBinaryOp(this.Subtract,(n,i)=>n-i),this.AddIntBinaryOp(this.Multiply,(n,i)=>n*i),this.AddIntBinaryOp(this.Divide,(n,i)=>Math.floor(n/i)),this.AddIntBinaryOp(this.Mod,(n,i)=>n%i),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,i)=>n==i),this.AddIntBinaryOp(this.Greater,(n,i)=>n>i),this.AddIntBinaryOp(this.Less,(n,i)=>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 e=(n,i)=>n.Equals(i),t=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,F.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,F.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,n,i){if(this._nativeFunctions===null)return (0, Ne.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new r(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,F.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,F.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,F.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,F.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,F.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,F.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,F.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};Mi.NativeFunctionCall=W;W.Add="+";W.Subtract="-";W.Divide="/";W.Multiply="*";W.Mod="%";W.Negate="_";W.Equal="==";W.Greater=">";W.Less="<";W.GreaterThanOrEquals=">=";W.LessThanOrEquals="<=";W.NotEquals="!=";W.Not="!";W.And="&&";W.Or="||";W.Min="MIN";W.Max="MAX";W.Pow="POW";W.Floor="FLOOR";W.Ceiling="CEILING";W.Int="INT";W.Float="FLOAT";W.Has="?";W.Hasnt="!?";W.Intersect="^";W.ListMin="LIST_MIN";W.ListMax="LIST_MAX";W.All="LIST_ALL";W.Count="LIST_COUNT";W.ValueOfList="LIST_VALUE";W.Invert="LIST_INVERT";W._nativeFunctions=null;});var $i=x(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.NumberExpression=void 0;var Dd=Le(),Oa=ee(),bd=z(),Pa=class r extends Dd.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new Oa.IntValue(this.value)):this.isFloat()?n.AddContent(new Oa.FloatValue(this.value)):this.isBool()&&n.AddContent(new Oa.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, bd.asOrNull)(e,r);return t?t.subtype==this.subtype&&t.value==this.value:false}};Gi.NumberExpression=Pa;});var Ta=x(Ji=>{Object.defineProperty(Ji,"__esModule",{value:true});Ji.UnaryExpression=void 0;var Ad=Le(),wd=Ze(),rn=$i(),xd=z(),Rn=class extends Ad.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(wd.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};Ji.UnaryExpression=Rn;Rn.WithInner=(r,e)=>{let t=(0, xd.asOrNull)(r,rn.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new rn.NumberExpression(-t.value,"int");if(t.isFloat())return new rn.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new rn.NumberExpression(t.value==0,"bool");if(t.isFloat())return new rn.NumberExpression(t.value==0,"bool");if(t.isBool())return new rn.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new Rn(r,e)};});var Na=x(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.BinaryExpression=void 0;var _d=Le(),Od=Ze(),Pd=Ta(),Td=z(),Fa=class extends _d.Expression{constructor(e,t,n){super(),this.opName=n,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(Od.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, Td.asOrNull)(this.leftExpression,Pd.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};Hi.BinaryExpression=Fa;});var Bn=x(zi=>{Object.defineProperty(zi,"__esModule",{value:true});zi.CharacterSet=void 0;var Ln=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,n)=>{for(let i=t.charCodeAt(0);i<=n.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let n of t)this.Add(n);else for(let n of t.set)this.Add(n);return this},e&&this.AddCharacters(e);}};zi.CharacterSet=Ln;Ln.FromRange=(r,e)=>new Ln().AddRange(r,e);});var Hu=x(Ui=>{Object.defineProperty(Ui,"__esModule",{value:true});Ui.CharacterRange=void 0;var Ju=Bn(),Wn=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Ju.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 Ju.CharacterSet)this._excludes=n.set;else for(let i of n)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};Ui.CharacterRange=Wn;Wn.Define=(r,e,t=[])=>new Wn(r,e,t);});var Xi=x(Ki=>{Object.defineProperty(Ki,"__esModule",{value:true});Ki.ChoicePoint=void 0;var Fd=Pe(),Nd=Oe(),Ia=fe(),Va=class extends Fd.InkObject{constructor(e=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, Ia.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Ia.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new Nd.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Ia.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};Ki.ChoicePoint=Va;});var kt=x(Yi=>{Object.defineProperty(Yi,"__esModule",{value:true});Yi.PushPopType=void 0;var zu;(function(r){r[r.Tunnel=0]="Tunnel",r[r.Function=1]="Function",r[r.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(zu||(Yi.PushPopType=zu={}));});var jn=x(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.Pointer=void 0;var Id=Oe(),ka=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 Id.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(e){return new r(e,0)}static get Null(){return new r(null,-1)}};Qi.Pointer=ka;});var et=x(er=>{Object.defineProperty(er,"__esModule",{value:true});er.Divert=void 0;var Vd=Oe(),kd=kt(),Rd=Nt(),Ld=Pe(),Ra=jn(),Uu=re(),Zi=fe(),La=class r extends Ld.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=Ra.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, Zi.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, Zi.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, Zi.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof Uu.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Ra.Pointer.StartOf(e instanceof Uu.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new Vd.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=Ra.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof e<"u"&&(this.pushesToStack=true,this.stackPushType=e);}Equals(e){let t=e;return t instanceof r&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, Zi.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new Rd.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==kd.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};er.Divert=La;});var ct=x(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.SymbolType=void 0;var Ku;(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";})(Ku||(tr.SymbolType=Ku={}));});var vt=x(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.VariableAssignment=void 0;var Bd=Pe(),Ba=class extends Bd.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};nr.VariableAssignment=Ba;});var sn=x(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.Choice=void 0;var Wd=Xi(),ir=re(),St=me(),Wa=et(),Xu=ee(),jd=Z(),qd=ct(),Yu=vt(),ja=class extends jd.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,n){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new ir.Container,this._runtimeChoice=new Wd.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(St.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Xu.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Yu.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(St.ControlCommand.BeginString()),this._divertToStartContentOuter=new Wa.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Wa.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new ir.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(St.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(St.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(St.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(St.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new ir.Container,this.startContent){this._returnToR2=new Xu.DivertTargetValue,this._innerContentContainer.AddContent(St.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(St.ControlCommand.EvalEnd());let i=new Yu.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Wa.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new ir.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=e,this.choiceOnlyContent=t,this.innerContent=n,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),n&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(e){var t;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(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,qd.SymbolType.SubFlowAndWeave);}};rr.Choice=ja;});var Qu=x(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.StringParserElement=void 0;var sr=class r{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{r._uniqueIdCounter++,this.uniqueId=r._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};ar.StringParserElement=sr;sr._uniqueIdCounter=1e3;});var eh=x(or=>{Object.defineProperty(or,"__esModule",{value:true});or.StringParserState=void 0;var Zu=Qu(),qa=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new Zu.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(t),n.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],n=this._stack[this._numElements-1];t.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new Zu.StringParserElement;this._numElements=1;}};or.StringParserState=qa;});var Ga=x(Rt=>{Object.defineProperty(Rt,"__esModule",{value:true});Rt.StringParser=Rt.ParseSuccess=void 0;var Ma=Bn(),Md=eh();Rt.ParseSuccess=Symbol("ParseSuccessStruct");var qn=class r{constructor(e){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 Ma.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
9
  `)===null?this.FailRule(n):this.SucceedRule(n,`
10
- `)};let t=this.PreProcessInputString(e);this.state=new jp.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,n=null){let i=this.BeginRule(),a=new Ga.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let s="",o=null;do{let u=this.ParseUntilCharactersFromCharSet(a);if(u&&(s+=u),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let l=this.currentCharacter;if(t!==null&&t.set.has(l)){s+=l,l===`
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)}};kt.StringParser=qn;qn.ParseSuccess=kt.ParseSuccess;qn.numbersCharacterSet=new Ga.CharacterSet("0123456789");});var eh=x(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.CommentEliminator=void 0;var Ja=Bn(),qp=$a(),Ha=class extends qp.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Ja.CharacterSet(`/\r
12
- `),this._commentBlockEndCharacter=new Ja.CharacterSet("*"),this._newlineCharacters=new Ja.CharacterSet(`
10
+ `)};let t=this.PreProcessInputString(e);this.state=new Md.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,n=null){let i=this.BeginRule(),a=new Ma.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let s="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(s+=l),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(t!==null&&t.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)}};Rt.StringParser=qn;qn.ParseSuccess=Rt.ParseSuccess;qn.numbersCharacterSet=new Ma.CharacterSet("0123456789");});var th=x(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.CommentEliminator=void 0;var $a=Bn(),Gd=Ga(),Ja=class extends Gd.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new $a.CharacterSet(`/\r
12
+ `),this._commentBlockEndCharacter=new $a.CharacterSet("*"),this._newlineCharacters=new $a.CharacterSet(`
13
13
  \r`),this.Process=()=>{let e=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return e!==null?e.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let e=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return e!==null?e.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>this.ParseString("//")===null?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(this.ParseString("/*")===null)return null;let e=this.lineIndex,t=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),t!=null?`
14
- `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};ur.CommentEliminator=Ha;});var cr=x(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.Conditional=void 0;var Mp=ie(),th=me(),Gp=Q(),za=class extends Gp.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new Mp.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(th.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=th.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=t;}super.ResolveReferences(e);}};hr.Conditional=za;});var St=x(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.Text=void 0;var $p=Q(),Jp=ee(),Ua=class extends $p.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new Jp.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};dr.Text=Ua;});var fr=x(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.ConstantDeclaration=void 0;var Hp=Q(),zp=ht(),Ka=class extends Hp.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,zp.SymbolType.Var);}};pr.ConstantDeclaration=Ka;});var an=x(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.FlowLevel=void 0;var nh;(function(r){r[r.Story=0]="Story",r[r.Knot=1]="Knot",r[r.Stitch=2]="Stitch",r[r.WeavePoint=3]="WeavePoint";})(nh||(mr.FlowLevel=nh={}));});var Mn=x(gr=>{Object.defineProperty(gr,"__esModule",{value:true});gr.Gather=void 0;var Up=ie(),Kp=Q(),Xp=ht(),Xa=class extends Kp.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let n=new Up.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"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Xp.SymbolType.SubFlowAndWeave);}};gr.Gather=Xa;});var Rt=x(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.Path=void 0;var Cr=H(),ih=et(),on=an(),Yp=Lt(),Ya=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?on.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(Cr.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===on.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,u=(0, Cr.asOrNull)(i,ih.FlowBase);if(u!==null?o=u.flowLevel+1:o=on.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,s,o),i===null)break}return i},this.GetChildFromContext=(n,i,a,s=false)=>{let o=a===null,u=(0, Cr.asOrNull)(n,Yp.Weave);if(i&&u!==null&&(o||a===on.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, Cr.asOrNull)(n,ih.FlowBase);if(i&&l!==null){let h=s||l.flowLevel===on.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,a,h)}return null},Object.values(on.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};yr.Path=Ya;});var eo=x(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.ReturnType=void 0;var Qp=Q(),Zp=ie(),Qa=me(),ef=It(),Za=class extends Qp.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new Zp.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(Qa.ControlCommand.EvalStart()),t.AddContent(new ef.Void),t.AddContent(Qa.ControlCommand.EvalEnd())),t.AddContent(Qa.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};vr.ReturnType=Za;});var Gn=x(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.ClosestFlowBase=void 0;function tf(r){let e=r.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}Sr.ClosestFlowBase=tf;});var Dr=x(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.Identifier=void 0;var to=class r{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new r("DONE")}};Er.Identifier=to;});var et=x(br=>{Object.defineProperty(br,"__esModule",{value:true});br.FlowBase=void 0;var nf=sn(),no=un(),rf=ln(),tt=an(),sf=Mn(),af=Q(),of=Rt(),lf=eo(),uf=ie(),hf=Ze(),cf=yt(),io=ht(),df=Lt(),pf=Gn(),ff=Dr(),rh=H(),ro=class r extends af.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,n=null,i=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 u,l;let h=[],c=[];this._subFlowsByName=new Map;for(let f of s){let m=(0, rh.asOrNull)(f,r);m?(this._firstChildFlow===null&&(this._firstChildFlow=m),c.push(f),!((u=m.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=m.identifier)===null||l===void 0?void 0:l.name,m)):h.push(f);}o&&h.push(new sf.Gather(null,1),new no.Divert(new of.Path(ff.Identifier.Done())));let d=[];return h.length>0&&(this._rootWeave=new df.Weave(h,0),d.push(this._rootWeave)),c.length>0&&d.push(...c),d},this.ResolveVariableWithName=(s,o)=>{var u;let l={},h=o===null?this:(0, pf.ClosestFlowBase)(o);if(h){if(h.args!==null){for(let c of h.args)if(((u=c.identifier)===null||u===void 0?void 0:u.name)===s)return l.found=true,l.isArgument=true,l.ownerFlow=h,l}if(h!==this.story&&h.variableDeclarations.has(s))return l.found=true,l.ownerFlow=h,l.isTemporary=true,l}return this.story.variableDeclarations.has(s)?(l.found=true,l.ownerFlow=this.story,l.isGlobal=true,l):(l.found=false,l)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let u=this.variableDeclarations.get(o),l="";u.debugMetadata&&(l=` (${u.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${l}`,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===tt.FlowLevel.Knot||this.flowLevel===tt.FlowLevel.Stitch)&&(o=this.Find(lf.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let u=new uf.Container;u.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(u.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(u);let l=0;for(;this.content!==null&&l<this.content.length;){let h=this.content[l];if(h instanceof r){let c=h,d=c.runtimeObject;l===0&&!c.hasParameters&&this.flowLevel===tt.FlowLevel.Knot&&(this._startingSubFlowDivert=new hf.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=d);let f=d,m=u.namedContent.get(f.name)||null;if(m){let g=`${this.GetType()} already contains flow named '${f.name}' (at ${m.debugMetadata})`;this.Error(g,c);}u.AddToNamedContentOnly(f);}else h&&u.AddContent(h.runtimeObject);l+=1;}return this.flowLevel!==tt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),u},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let u=this.args.length-1;u>=0;--u){let l=((o=this.args[u].identifier)===null||o===void 0?void 0:o.name)||null,h=new cf.VariableAssignment(l,true);s.AddContent(h);}},this.ContentWithNameAtLevel=(s,o=null,u=false)=>{var l;if((o===this.flowLevel||o===null)&&s===((l=this.identifier)===null||l===void 0?void 0:l.name))return this;if(o===tt.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(s),c))return c;if(o===tt.FlowLevel.WeavePoint)return u?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:u?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,tt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,u]of this._subFlowsByName){let l=u.ContentWithNameAtLevel(s,null,true);if(l)return l}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==tt.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[u,l]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${u}' within the function '${this.identifier}'`,l);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(no.Divert)();for(let u of s)!u.isFunctionCall&&!(u.parent instanceof rf.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let o=this._rootWeave.FindAll(nf.Choice)();for(let u of o)this.Error(`Functions may not contain choices, but saw '${u}'`,u);},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 u=(0, rh.asOrNull)(s,no.Divert);u&&u.isTunnel&&(o+=` When final tunnel to '${u.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,io.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((t=this.args[i].identifier)===null||t===void 0?void 0:t.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!==tt.FlowLevel.Story){let i=this.flowLevel===tt.FlowLevel.Knot?io.SymbolType.Knot:io.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};br.FlowBase=ro;});var xr=x(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.ContentList=void 0;var mf=ie(),gf=Q(),Cf=St(),yf=H(),so=class extends gf.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let i=(0, yf.asOrNull)(this.content[n],Cf.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 mf.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};Ar.ContentList=so;});var hn=x(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.VariableReference=void 0;var vf=we(),Sf=xe(),ao=class extends vf.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new Sf.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};wr.VariableReference=ao;});var cn=x(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.VariableReference=void 0;var Ef=xr(),Df=Le(),sh=et(),bf=Rt(),Af=hn(),xf=Lt(),wf=Dr(),ah=H(),oo=class extends Df.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(ah.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new wf.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=t=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new Af.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);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new bf.Path(this.pathIdentifiers),n=t.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, ah.asOrNull)(n,sh.FlowBase);i&&i.isFunction&&(this.parent instanceof xf.Weave||this.parent instanceof Ef.ContentList||this.parent instanceof sh.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${t}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};_r.VariableReference=oo;});var $n=x(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.FunctionCall=void 0;var nt=me(),_f=un(),Tf=ln(),Of=Le(),Pf=Te(),Ff=ee(),Or=Qe(),oh=Ji(),Nf=Rt(),If=ee(),Vf=cn(),Tr=H(),Pr=class r extends Of.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(e,t){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=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(nt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(nt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, Tr.asOrNull)(this.args[0],Tf.DivertTarget),o=(0, Tr.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(nt.ControlCommand.TurnsSince()):n.AddContent(nt.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, Tr.asOrNull)(this.args[s],oh.NumberExpression);if(o&&!o.isInt()){let u=s===0?"minimum":"maximum";this.Error(`RANDOM's ${u} parameter should be an integer`);}this.args[s].GenerateIntoContainer(n);}n.AddContent(nt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, Tr.asOrNull)(this.args[0],oh.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(nt.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(nt.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(nt.ControlCommand.ListRandom());else if(Or.NativeFunctionCall.CallExistsWithName(this.name)){let s=Or.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(Or.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 If.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(nt.ControlCommand.ListFromInt());else {let s=new Pf.InkList;s.SetInitialOriginName(this.name),n.AddContent(new Ff.ListValue(s));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(nt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new _f.Divert(new Nf.Path(e),t),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,n=t.runtimeDivert.variableDivertName!=null;if(n){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let i=t.targetContent;if(i===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${r.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Fr.FunctionCall=Pr;Pr.IsBuiltIn=r=>Or.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 uo=x(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.MultipleConditionExpression=void 0;var kf=Le(),Rf=Qe(),lo=class extends kf.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let n=true;for(let i of this.subExpressions)i.GenerateIntoContainer(t),n||t.AddContent(Rf.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Nr.MultipleConditionExpression=lo;});var ln=x(Ir=>{Object.defineProperty(Ir,"__esModule",{value:true});Ir.DivertTarget=void 0;var Lf=Ia(),Bf=sn(),Wf=cr(),jf=fo(),qf=ee(),ho=Le(),Mf=et(),lh=$n(),Gf=uo(),uh=cn(),co=H(),po=class r extends ho.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new qf.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, co.asOrNull)(t,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(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof ho.Expression;){let i=false,a=false,s=t.parent;if(s instanceof Lf.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof r||o.leftExpression instanceof uh.VariableReference)&&(o.rightExpression instanceof r||o.rightExpression instanceof uh.VariableReference)||(i=true),a=true;}else if(s instanceof lh.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof ho.Expression||s instanceof Gf.MultipleConditionExpression||s instanceof Bf.Choice&&s.condition===t||s instanceof Wf.Conditional||s instanceof jf.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;t=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, co.asOrNull)(this.parent,lh.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, co.asOrNull)(n,Mf.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}').`);}}};Ir.DivertTarget=po;});var un=x(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.Divert=void 0;var $f=ie(),Jn=me(),Jf=Ze(),mo=ln(),go=et(),Hf=$n(),zf=Q(),hh=Rt(),Uf=xe(),ch=Vt(),Kf=ee(),dh=cn(),Xf=Gn(),Hn=H(),Co=class extends zf.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return Jn.ControlCommand.End();if(this.isDone)return Jn.ControlCommand.Done();this.runtimeDivert=new Jf.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 $f.Container;if(n){this.isFunctionCall||i.AddContent(Jn.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],u=null;if(a&&s<a.length&&(u=a[s]),u&&u.isByReference){let l=(0, Hn.asOrNull)(o,dh.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${o}`);break}let h=new hh.Path(l.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let d=new Kf.VariablePointerValue(l.name);i.AddContent(d);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Jn.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Jn.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?ch.PushPopType.Function:ch.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, Hn.asOrNull)((0, Xf.ClosestFlowBase)(this),go.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 u;return ((u=o.identifier)===null||u===void 0?void 0:u.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, Hn.asOrNull)(this.targetContent,go.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 mo.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],u=this.args[s];if(o.isDivertTarget){let l=(0, Hn.asOrNull)(u,dh.VariableReference);if(!(u instanceof mo.DivertTarget)&&l===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${u}`,u);else if(l){let h=new hh.Path(l.pathIdentifiers);h.ResolveFromContext(l)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let i=this.target?this.target.firstComponent:null,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},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, Hn.asOrNull)(this.targetContent,go.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof mo.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let n=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=Hf.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new Uf.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,n=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,n):super.Error(`Divert ${e}`,t,n);}};Vr.Divert=Co;});var ph=x(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.GatherPointToResolve=void 0;var yo=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};kr.GatherPointToResolve=yo;});var fh=x(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.SequenceDivertToResolve=void 0;var vo=class{constructor(e,t){this.divert=e,this.targetContent=t;}};Rr.SequenceDivertToResolve=vo;});var So=x(Lr=>{Object.defineProperty(Lr,"__esModule",{value:true});Lr.SequenceType=void 0;var mh;(function(r){r[r.Stopping=1]="Stopping",r[r.Cycle=2]="Cycle",r[r.Shuffle=4]="Shuffle",r[r.Once=8]="Once";})(mh||(Lr.SequenceType=mh={}));});var bo=x(jr=>{Object.defineProperty(jr,"__esModule",{value:true});jr.Sequence=void 0;var gh=ie(),Je=me(),Eo=Ze(),zn=ee(),Br=Qe(),Yf=Q(),Qf=fh(),Wr=So(),Zf=Lt(),Do=class extends Yf.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new gh.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(Je.ControlCommand.EvalStart()),n.AddContent(Je.ControlCommand.VisitIndex());let i=(this.sequenceType&Wr.SequenceType.Once)>0,a=(this.sequenceType&Wr.SequenceType.Cycle)>0,s=(this.sequenceType&Wr.SequenceType.Stopping)>0,o=(this.sequenceType&Wr.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),s||i?(n.AddContent(new zn.IntValue(u-1)),n.AddContent(Br.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new zn.IntValue(this.sequenceElements.length)),n.AddContent(Br.NativeFunctionCall.CallWithName("%"))),o){let h=Je.ControlCommand.NoOp();if(i||s){let d=s?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(Je.ControlCommand.Duplicate()),n.AddContent(new zn.IntValue(d)),n.AddContent(Br.NativeFunctionCall.CallWithName("=="));let f=new Eo.Divert;f.isConditional=true,n.AddContent(f),this.AddDivertToResolve(f,h);}let c=this.sequenceElements.length;s&&(c-=1),n.AddContent(new zn.IntValue(c)),n.AddContent(Je.ControlCommand.SequenceShuffleIndex()),(i||s)&&n.AddContent(h);}n.AddContent(Je.ControlCommand.EvalEnd());let l=Je.ControlCommand.NoOp();for(let h=0;h<u;h+=1){n.AddContent(Je.ControlCommand.EvalStart()),n.AddContent(Je.ControlCommand.Duplicate()),n.AddContent(new zn.IntValue(h)),n.AddContent(Br.NativeFunctionCall.CallWithName("==")),n.AddContent(Je.ControlCommand.EvalEnd());let c=new Eo.Divert;c.isConditional=true,n.AddContent(c);let d;h<this.sequenceElements.length?d=this.sequenceElements[h].runtimeObject:d=new gh.Container,d.name=`s${h}`,d.InsertContent(Je.ControlCommand.PopEvaluatedValue(),0);let f=new Eo.Divert;d.AddContent(f),n.AddToNamedContentOnly(d),this.AddDivertToResolve(c,d),this.AddDivertToResolve(f,l);}return n.AddContent(l),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new Qf.SequenceDivertToResolve(n,i));},this.sequenceType=t,this.sequenceElements=[];for(let n of e){let i=n.content,a=null;i===null||i.length===0?a=n:a=new Zf.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};jr.Sequence=Do;});var xo=x(qr=>{Object.defineProperty(qr,"__esModule",{value:true});qr.TunnelOnwards=void 0;var em=ie(),Un=me(),tm=Ze(),nm=ee(),im=Q(),rm=It(),sm=H(),am=hn(),Ao=class extends im.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new em.Container;if(e.AddContent(Un.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let u=0;u<n.content.length;u+=1){let l=n.content[u];l&&(s==-1&&l.commandType===Un.ControlCommand.CommandType.EvalStart?s=u:l.commandType===Un.ControlCommand.CommandType.EvalEnd&&(o=u));}for(let u=s+1;u<o;u+=1){let l=n.content[u];l.parent=null,e.AddContent(n.content[u]);}}}let i=(0, sm.asOrNull)(t,tm.Divert);if(i!=null&&i.hasVariableTarget){let a=new am.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new nm.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new rm.Void);return e.AddContent(Un.ControlCommand.EvalEnd()),e.AddContent(Un.ControlCommand.PopTunnel()),e},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};qr.TunnelOnwards=Ao;});var To=x(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.ListDefinition=void 0;var wo=Te(),_o=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let n=new wo.InkListItem(this.name,e);this._items.set(n.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?false:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[n,i]of this._itemNameToValues)if(i==e)return t=new wo.InkListItem(this.name,n),{result:t,exists:true};return t=wo.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(e.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};Mr.ListDefinition=_o;});var $r=x(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.ListDefinition=void 0;var om=Te(),lm=Te(),um=To(),hm=ee(),cm=Q(),dm=ht(),Oo=class extends cm.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let n of this.itemDefinitions)t.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):t.set(n.name,n.seriesValue);return new um.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,i;let a=new om.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new lm.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 hm.ListValue(a)};let t=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(t=n.explicitValue),n.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,dm.SymbolType.List);}};Gr.ListDefinition=Oo;});var Fo=x(Jr=>{Object.defineProperty(Jr,"__esModule",{value:true});Jr.VariableAssignment=void 0;var pm=ie(),fm=Gn(),mm=$r(),gm=Q(),Ch=ht(),Cm=yt(),ym=cn(),vm=H(),Po=class extends gm.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, fm.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new pm.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Cm.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!n,i instanceof mm.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?Ch.SymbolType.Var:Ch.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, vm.asOrNull)(this.expression,ym.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};Jr.VariableAssignment=Po;});var Lt=x(Ur=>{Object.defineProperty(Ur,"__esModule",{value:true});Ur.Weave=void 0;var yh=Oi(),We=sn(),Hr=cr(),Sm=fr(),Em=ie(),zr=un(),Dm=Ze(),bm=ln(),Am=et(),it=Mn(),xm=ph(),wm=Q(),No=bo(),_m=St(),Tm=xo(),Om=Fo(),je=H(),Io=class r extends wm.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let n=this.content.length-1;n>=0;--n){e=this.content[n];let i=(0, je.asOrNull)(e,_m.Text);if(!(i&&i.text===`
15
- `)&&!this.IsGlobalDeclaration(e))break}let t=(0, je.asOrNull)(e,r);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-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(it.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(We.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let u=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(u){let l=u instanceof it.Gather?"gather":"choice",h=u;this.Error(`A ${l} 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 We.Choice||i instanceof it.Gather){let s=i.indentationDepth-1;if(s>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let c=(0, je.asOrNull)(this.content[n],We.Choice)||(0, je.asOrNull)(this.content[n],it.Gather);if(c!==null&&c.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let u=n-o,l=this.content.slice(o,o+u);this.content.splice(o,u);let h=new r(l,s);this.InsertContent(o,h),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let i of n)if(i instanceof We.Choice||i instanceof it.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new Em.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof We.Choice||n instanceof it.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 it.Gather&&o.indentationDepth==n.indentationDepth)continue;let u=null;if(o instanceof zr.Divert)u=o.runtimeObject;else {u=new Dm.Divert;let l=o;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new xm.GatherPointToResolve(u,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof it.Gather)this.AddRuntimeForGather(n);else if(n instanceof We.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof it.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, je.asOrNull)(n,We.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, je.asOrNull)(s,r);o&&(!a&&n===null&&(n=o),a&&i===null&&(i=o)),(s instanceof No.Sequence||s instanceof Hr.Conditional)&&(a=true);}if(!(n===null&&i===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],u=false;if(a){if(o instanceof We.Choice&&n!==null)n.ReceiveLooseEnd(o),u=true;else if(!(o instanceof We.Choice)){let l=n||i;l!==null&&(l.ReceiveLooseEnd(o),u=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(o),u=true;u&&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, je.asOrNull)(n,Om.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, je.asOrNull)(n,Sm.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let i=[],a=n;if(a.content!==null)for(let u of a.content)this.IsGlobalDeclaration(u)||i.push(u);let s=(0, je.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 u=o+1;u<s.content.length;u+=1){let l=s.content[u];if(!this.IsGlobalDeclaration(l)){if(l instanceof We.Choice||l instanceof it.Gather||l instanceof r)break;i.push(l);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof yh.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 We.Choice||a instanceof zr.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 No.Sequence||s instanceof Hr.Conditional){i=(0, je.asOrNull)(s,Hr.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(We.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 u of n){if(u.Find(zr.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof bm.DivertTarget))!==null&&(s=true),u.Find(Tm.TunnelOnwards)()!=null){s=true;break}o=u;}if(!s){if(o instanceof yh.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, je.asOrNull)(n.content[i],zr.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, je.asOrNull)(i,Am.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 u=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(u,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof No.Sequence||n instanceof Hr.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};Ur.Weave=Io;});var fo=x(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.ConditionalSingleBranch=void 0;var vh=ie(),Kr=me(),Sh=Ze(),Pm=Q(),Fm=Qe(),Nm=ee(),Im=St(),Vm=Lt(),km=H(),Vo=class extends Pm.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=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, km.asOrNull)(i,Im.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new vh.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(Kr.ControlCommand.Duplicate()),this._conditionalDivert=new Sh.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(Kr.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(Fm.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(Kr.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new Nm.StringValue(`
16
- `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Kr.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Sh.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new vh.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new Vm.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};Xr.ConditionalSingleBranch=Vo;});var Dh=x(Yr=>{Object.defineProperty(Yr,"__esModule",{value:true});Yr.CustomFlags=void 0;var Eh;(function(r){r[r.ParsingString=1]="ParsingString",r[r.TagActive=2]="TagActive";})(Eh||(Yr.CustomFlags=Eh={}));});var bh=x(Qr=>{Object.defineProperty(Qr,"__esModule",{value:true});Qr.DebugMetadata=void 0;var ko=class r{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new r;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumber<e.startLineNumber?(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>e.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<e.endLineNumber?(t.endLineNumber=e.endLineNumber,t.endCharacterNumber=e.endCharacterNumber):(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=Math.max(this.endCharacterNumber,e.endCharacterNumber)),t}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};Qr.DebugMetadata=ko;});var Ah=x(Zr=>{Object.defineProperty(Zr,"__esModule",{value:true});Zr.ExternalDeclaration=void 0;var Rm=Q(),Ro=class extends Rm.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};Zr.ExternalDeclaration=Ro;});var xh=x(es=>{Object.defineProperty(es,"__esModule",{value:true});es.FlowDecl=void 0;var Lo=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};es.FlowDecl=Lo;});var Wo=x(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.Wrap=void 0;var Lm=Q(),Bo=class extends Lm.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};ts.Wrap=Bo;});var wh=x(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.Glue=void 0;var Bm=Wo(),jo=class extends Bm.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};ns.Glue=jo;});var rs=x(is=>{Object.defineProperty(is,"__esModule",{value:true});is.Glue=void 0;var Wm=we(),qo=class extends Wm.InkObject{toString(){return "Glue"}};is.Glue=qo;});var Th=x(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.IncDecExpression=void 0;var jm=xr(),_h=Le(),qm=et(),Mm=Qe(),Gm=ee(),$m=yt(),Jm=hn(),Hm=Lt(),Mo=class extends _h.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new Jm.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new Gm.IntValue(1)),i.AddContent(Mm.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new $m.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?"++":"--")},t instanceof _h.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!n):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let n=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof Hm.Weave)&&!(this.parent instanceof qm.FlowBase)&&!(this.parent instanceof jm.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};ss.IncDecExpression=Mo;});var $o=x(as=>{Object.defineProperty(as,"__esModule",{value:true});as.IncludedFile=void 0;var zm=Q(),Go=class extends zm.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};as.IncludedFile=Go;});var Oh=x(os=>{Object.defineProperty(os,"__esModule",{value:true});os.InfixOperator=void 0;var Jo=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};os.InfixOperator=Jo;});var zo=x(ls=>{Object.defineProperty(ls,"__esModule",{value:true});ls.Knot=void 0;var Um=et(),Ph=an(),Ho=class extends Um.FlowBase{get flowLevel(){return Ph.FlowLevel.Knot}constructor(e,t,n,i){super(e,t,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let n in this.subFlowsByName){let i=t.ContentWithNameAtLevel(n,Ph.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);}}}};ls.Knot=Ho;});var Fh=x(us=>{Object.defineProperty(us,"__esModule",{value:true});us.List=void 0;var Km=Le(),Xm=Te(),Ym=Te(),Qm=ee(),Uo=class extends Km.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,i;let a=new Xm.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((n=s?.name)===null||n===void 0?void 0:n.split("."))||[],u=null,l="";o.length>1?(u=o[0],l=o[1]):l=o[0];let h=this.story.ResolveListItem(u,l,this);if(h===null)u===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}u||(u=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new Ym.InkListItem(u,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(c,h.seriesValue);}}t.AddContent(new Qm.ListValue(a));};}get typeName(){return "List"}};us.List=Uo;});var Xo=x(hs=>{Object.defineProperty(hs,"__esModule",{value:true});hs.ListElementDefinition=void 0;var Zm=Q(),eg=ht(),Ko=class extends Zm.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,n=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=n,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,eg.SymbolType.ListItem);}};hs.ListElementDefinition=Ko;});var Yo=x(cs=>{Object.defineProperty(cs,"__esModule",{value:true});cs.StatementLevel=void 0;var Nh;(function(r){r[r.InnerBlock=0]="InnerBlock",r[r.Stitch=1]="Stitch",r[r.Knot=2]="Knot",r[r.Top=3]="Top";})(Nh||(cs.StatementLevel=Nh={}));});var Zo=x(ds=>{Object.defineProperty(ds,"__esModule",{value:true});ds.Stitch=void 0;var tg=et(),ng=an(),Qo=class extends tg.FlowBase{get flowLevel(){return ng.FlowLevel.Stitch}constructor(e,t,n,i){super(e,t,n,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};ds.Stitch=Qo;});var fs=x(ps=>{Object.defineProperty(ps,"__esModule",{value:true});ps.Tag=void 0;var ig=we(),el=class extends ig.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};ps.Tag=el;});var nl=x(ms=>{Object.defineProperty(ms,"__esModule",{value:true});ms.Choice=void 0;var rg=xe(),sg=fe(),ag=we(),tl=class r extends ag.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, sg.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new rg.Path(e);}Clone(){let e=new r;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};ms.Choice=tl;});var rl=x(gs=>{Object.defineProperty(gs,"__esModule",{value:true});gs.ListDefinitionsOrigin=void 0;var og=Te(),lg=ee(),ug=fe(),il=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[n,i]of t.items){let a=og.InkListItem.fromSerializedKey(n),s=new lg.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 e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let n=this._lists.get(e);return n?{result:n,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, ug.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};gs.ListDefinitionsOrigin=il;});var pn=x(Ss=>{Object.defineProperty(Ss,"__esModule",{value:true});Ss.JsonSerialisation=void 0;var Cs=ie(),Pe=ee(),Ih=rs(),j=me(),dn=Vt(),Vh=Ze(),kh=Yi(),sl=hn(),Rh=yt(),al=Qe(),Lh=It(),Bh=fs(),hg=xe(),Wh=nl(),cg=To(),dg=rl(),ys=Te(),re=H(),Bt=fe(),vs=class r{static JArrayToRuntimeObjList(e,t=false){let n=e.length;t&&n--;let i=[];for(let a=0;a<n;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, Bt.throwNullException)("runtimeObj");i.push(o);}return i}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[n,i]of t)e.WritePropertyStart(n),this.WriteRuntimeObject(e,i),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let n of t)this.WriteRuntimeObject(e,n);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[n,i]of t)e.WriteIntProperty(n,i);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let n=(0, re.asOrNull)(t,Cs.Container);if(n){this.WriteRuntimeContainer(e,n);return}let i=(0, re.asOrNull)(t,Vh.Divert);if(i){let C="->";i.isExternal?C="x()":i.pushesToStack&&(i.stackPushType==dn.PushPopType.Function?C="f()":i.stackPushType==dn.PushPopType.Tunnel&&(C="->t->"));let E;i.hasVariableTarget?E=i.variableDivertName:E=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(C,E),i.hasVariableTarget&&e.WriteProperty("var",true),i.isConditional&&e.WriteProperty("c",true),i.externalArgs>0&&e.WriteIntProperty("exArgs",i.externalArgs),e.WriteObjectEnd();return}let a=(0, re.asOrNull)(t,kh.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, re.asOrNull)(t,Pe.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, re.asOrNull)(t,Pe.IntValue);if(o){e.WriteInt(o.value);return}let u=(0, re.asOrNull)(t,Pe.FloatValue);if(u){e.WriteFloat(u.value);return}let l=(0, re.asOrNull)(t,Pe.StringValue);if(l){l.isNewline?e.Write(`
17
- `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(l.value),e.WriteStringEnd());return}let h=(0, re.asOrNull)(t,Pe.ListValue);if(h){this.WriteInkList(e,h);return}let c=(0, re.asOrNull)(t,Pe.DivertTargetValue);if(c){if(e.WriteObjectStart(),c.value===null)return (0, Bt.throwNullException)("divTargetVal.value");e.WriteProperty("^->",c.value.componentsString),e.WriteObjectEnd();return}let d=(0, re.asOrNull)(t,Pe.VariablePointerValue);if(d){e.WriteObjectStart(),e.WriteProperty("^var",d.value),e.WriteIntProperty("ci",d.contextIndex),e.WriteObjectEnd();return}if((0, re.asOrNull)(t,Ih.Glue)){e.Write("<>");return}let m=(0, re.asOrNull)(t,j.ControlCommand);if(m){e.Write(r._controlCommandNames[m.commandType]);return}let g=(0, re.asOrNull)(t,al.NativeFunctionCall);if(g){let C=g.name;C=="^"&&(C="L^"),e.Write(C);return}let b=(0, re.asOrNull)(t,sl.VariableReference);if(b){e.WriteObjectStart();let C=b.pathStringForCount;C!=null?e.WriteProperty("CNT?",C):e.WriteProperty("VAR?",b.name),e.WriteObjectEnd();return}let S=(0, re.asOrNull)(t,Rh.VariableAssignment);if(S){e.WriteObjectStart();let C=S.isGlobal?"VAR=":"temp=";e.WriteProperty(C,S.variableName),S.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, re.asOrNull)(t,Lh.Void)){e.Write("void");return}let p=(0, re.asOrNull)(t,Bh.Tag);if(p){e.WriteObjectStart(),e.WriteProperty("#",p.text),e.WriteObjectEnd();return}let D=(0, re.asOrNull)(t,Wh.Choice);if(D){this.WriteChoice(e,D);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(e[n]);if(i===null)return (0, Bt.throwNullException)("inkObject");t.set(n,i);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let n in e)e.hasOwnProperty(n)&&t.set(n,parseInt(e[n]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return Pe.Value.Create(e);if(typeof e=="string"){let t=e.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(t);if(n)return new Pe.FloatValue(parseFloat(n[0]));let i=t[0];if(i=="^")return new Pe.StringValue(t.substring(1));if(i==`
18
- `&&t.length==1)return new Pe.StringValue(`
19
- `);if(t=="<>")return new Ih.Glue;for(let a=0;a<r._controlCommandNames.length;++a){let s=r._controlCommandNames[a];if(t==s)return new j.ControlCommand(a)}if(t=="L^"&&(t="^"),al.NativeFunctionCall.CallExistsWithName(t))return al.NativeFunctionCall.CallWithName(t);if(t=="->->")return j.ControlCommand.PopTunnel();if(t=="~ret")return j.ControlCommand.PopFunction();if(t=="void")return new Lh.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new Pe.DivertTargetValue(new hg.Path(n.toString()));if(t["^var"]){n=t["^var"];let h=new Pe.VariablePointerValue(n.toString());return "ci"in t&&(n=t.ci,h.contextIndex=parseInt(n)),h}let i=false,a=false,s=dn.PushPopType.Function,o=false;if((n=t["->"])?i=true:(n=t["f()"])?(i=true,a=true,s=dn.PushPopType.Function):(n=t["->t->"])?(i=true,a=true,s=dn.PushPopType.Tunnel):(n=t["x()"])&&(i=true,o=true,a=false,s=dn.PushPopType.Function),i){let h=new Vh.Divert;h.pushesToStack=a,h.stackPushType=s,h.isExternal=o;let c=n.toString();return (n=t.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!t.c,o&&(n=t.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=t["*"]){let h=new kh.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=t.flg)&&(h.flags=parseInt(n)),h}if(n=t["VAR?"])return new sl.VariableReference(n.toString());if(n=t["CNT?"]){let h=new sl.VariableReference;return h.pathStringForCount=n.toString(),h}let u=false,l=false;if((n=t["VAR="])?(u=true,l=true):(n=t["temp="])&&(u=true,l=false),u){let h=n.toString(),c=!t.re,d=new Rh.VariableAssignment(h,c);return d.isGlobal=l,d}if(t["#"]!==void 0)return n=t["#"],new Bh.Tag(n.toString());if(n=t.list){let h=n,c=new ys.InkList;if(n=t.origins){let d=n;c.SetInitialOriginNames(d);}for(let d in h)if(h.hasOwnProperty(d)){let f=h[d],m=new ys.InkListItem(d),g=parseInt(f);c.Add(m,g);}return new Pe.ListValue(c)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,n){return JSON.stringify(e,(i,a)=>t?.some(s=>s===i)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=false){if(e.WriteArrayStart(),t===null)return (0, Bt.throwNullException)("container");for(let u of t.content)this.WriteRuntimeObject(e,u);let i=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!n,o=i!=null||a>0||s;if(o&&e.WriteObjectStart(),i!=null)for(let[u,l]of i){let h=u,c=(0, re.asOrNull)(l,Cs.Container);e.WritePropertyStart(h),this.WriteRuntimeContainer(e,c,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),s&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new Cs.Container;t.content=this.JArrayToRuntimeObjList(e,true);let n=e[e.length-1];if(n!=null){let i=new Map;for(let a in n)if(a=="#f")t.countFlags=parseInt(n[a]);else if(a=="#n")t.name=n[a].toString();else {let s=this.JTokenToRuntimeObject(n[a]),o=(0, re.asOrNull)(s,Cs.Container);o&&(o.name=a),i.set(a,s);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new Wh.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t.isInvisibleDefault=!!e.isInvisibleDefault,t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),e.WriteProperty("isInvisibleDefault",t.isInvisibleDefault),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, Bt.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of n){let s=ys.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, Bt.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(s.originName?s.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(s.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of n.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let i={};for(let[a,s]of n.items){let o=ys.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Bt.throwNullException)("item.itemName");i[o.itemName]=s;}t[n.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),s=t[i],o=new Map;for(let l in s)if(t.hasOwnProperty(i)){let h=s[l];o.set(l,parseInt(h));}let u=new cg.ListDefinition(a,o);n.push(u);}return new dg.ListDefinitionsOrigin(n)}};Ss.JsonSerialisation=vs;vs._controlCommandNames=(()=>{let r=[];r[j.ControlCommand.CommandType.EvalStart]="ev",r[j.ControlCommand.CommandType.EvalOutput]="out",r[j.ControlCommand.CommandType.EvalEnd]="/ev",r[j.ControlCommand.CommandType.Duplicate]="du",r[j.ControlCommand.CommandType.PopEvaluatedValue]="pop",r[j.ControlCommand.CommandType.PopFunction]="~ret",r[j.ControlCommand.CommandType.PopTunnel]="->->",r[j.ControlCommand.CommandType.BeginString]="str",r[j.ControlCommand.CommandType.EndString]="/str",r[j.ControlCommand.CommandType.NoOp]="nop",r[j.ControlCommand.CommandType.ChoiceCount]="choiceCnt",r[j.ControlCommand.CommandType.Turns]="turn",r[j.ControlCommand.CommandType.TurnsSince]="turns",r[j.ControlCommand.CommandType.ReadCount]="readc",r[j.ControlCommand.CommandType.Random]="rnd",r[j.ControlCommand.CommandType.SeedRandom]="srnd",r[j.ControlCommand.CommandType.VisitIndex]="visit",r[j.ControlCommand.CommandType.SequenceShuffleIndex]="seq",r[j.ControlCommand.CommandType.StartThread]="thread",r[j.ControlCommand.CommandType.Done]="done",r[j.ControlCommand.CommandType.End]="end",r[j.ControlCommand.CommandType.ListFromInt]="listInt",r[j.ControlCommand.CommandType.ListRange]="range",r[j.ControlCommand.CommandType.ListRandom]="lrnd",r[j.ControlCommand.CommandType.BeginTag]="#",r[j.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<j.ControlCommand.CommandType.TOTAL_VALUES;++e)if(r[e]==null)throw new Error("Control command not accounted for in serialisation");return r})();});var ul=x(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.CallStack=void 0;var ol=Vt(),jh=xe(),pg=Qn(),qh=pn(),fg=ee(),mg=Ft(),Kn=jn(),gg=_n(),Mh=en(),ll=fe(),Xn=class r{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){gg.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=Kn.Pointer.Null,arguments[0]instanceof pg.Story){let e=arguments[0];this._startOfRoot=Kn.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new r.Thread),this._threads[0].callstack.push(new r.Element(ol.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let i of n){let a=i,s=new r.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=Kn.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let n of this._threads)n.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==ol.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let i=new r.Element(e,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=t,i.functionStartInOutputStream=n,this.callStack.push(i);}CanPop(e=null){return this.canPop?e==null?true:this.currentElement.type==e:false}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let n=this.callStack[t-1],i=(0, Mh.tryGetValueFromMap)(n.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, Mh.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&fg.ListValue.RetainListOriginsForAssignment(s.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new mg.StringBuilder;for(let t=0;t<this._threads.length;t++){let n=this._threads[t],i=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
20
- `,t+1,this._threads.length,i?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==ol.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=n.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, ll.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Yn.CallStack=Xn;(function(r){class e{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 e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}r.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=Kn.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 u of s){let l=u,h=parseInt(l.type),c=Kn.Pointer.Null,d,f=l.cPath;if(typeof f<"u"){d=f.toString();let S=a.ContentAtPath(new jh.Path(d));if(c.container=S.container,c.index=parseInt(l.idx),S.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+d+". Has the story changed since this save data was created?");S.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+d+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+d+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let m=!!l.exp,g=new e(h,c,m),b=l.temp;typeof b<"u"?g.temporaryVariables=qh.JsonSerialisation.JObjectToDictionaryRuntimeObjs(b):g.temporaryVariables.clear(),this.callstack.push(g);}let o=i.previousContentObject;if(typeof o<"u"){let u=new jh.Path(o.toString());this.previousPointer=a.PointerAtPath(u);}}}Copy(){let i=new t;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, ll.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"),qh.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, ll.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}r.Thread=t;})(Xn||(Yn.CallStack=Xn={}));});var $h=x(Ds=>{Object.defineProperty(Ds,"__esModule",{value:true});Ds.VariablesState=void 0;var pe=ee(),Cg=On(),Gh=pn(),ge=H(),Zn=en(),Et=fe();function yg(){return class{}}var Es=class r extends yg(){variableChangedEvent(e,t){for(let n of this.variableChangedEventCallbacks)n(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let n=this._globalVariables.get(t);this.variableChangedEvent(t,n);}if(this.patch!=null)for(let t of this.patch.changedVariables){let n=this.patch.TryGetGlobal(t,null);n.exists&&e.set(t,n);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,n]of e)this.variableChangedEvent(t,n);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(e),typeof n>"u"&&(n=this._defaultGlobalVariables.get(e)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new Cg.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=pe.Value.Create(t);if(n==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,n);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,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, Et.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,n]of this._defaultGlobalVariables){let i=e[t];if(typeof i<"u"){let a=Gh.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Et.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let i=t,a=n;if(r.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let s=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(i),Gh.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Et.throwNullException)("obj1");if(t===null)return (0, Et.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let n=(0, ge.asOrNull)(e,pe.BoolValue);if(n!==null)return n.value===(0, ge.asOrThrows)(t,pe.BoolValue).value;let i=(0, ge.asOrNull)(e,pe.IntValue);if(i!==null)return i.value===(0, ge.asOrThrows)(t,pe.IntValue).value;let a=(0, ge.asOrNull)(e,pe.FloatValue);if(a!==null)return a.value===(0, ge.asOrThrows)(t,pe.FloatValue).value;let s=(0, ge.asOrNull)(e,pe.Value),o=(0, ge.asOrNull)(t,pe.Value);if(s!==null&&o!==null)return (0, ge.isEquatable)(s.valueObject)&&(0, ge.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let n=this.GetRawVariableWithName(e,t),i=(0, ge.asOrNull)(n,pe.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(e){let t=(0, Zn.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let n=null;if(t==0||t==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(e,null),i.exists)||(i=(0, Zn.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Zn.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Et.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(e,t),n}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let n=e.variableName;if(n===null)return (0, Et.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let s=(0, ge.asOrNull)(t,pe.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, ge.asOrNull)(this.GetRawVariableWithName(n,i),pe.VariablePointerValue),s!=null&&(n=s.variableName,i=s.contextIndex,a=i==0);while(s!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, ge.asOrThrows)(e,pe.ListValue),i=(0, ge.asOrThrows)(t,pe.ListValue);n.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(e,t){let n=null;if(this.patch===null&&(n=(0, Zn.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, Zn.tryGetValueFromMap)(this._globalVariables,e,null))),pe.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, Et.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&n!==null&&t!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Et.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let n=this.GetRawVariableWithName(e.variableName,t),i=(0, ge.asOrNull)(n,pe.VariablePointerValue);return i??new pe.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Ds.VariablesState=Es;Es.dontSaveDefaultValues=true;});var cl=x(bs=>{Object.defineProperty(bs,"__esModule",{value:true});bs.PRNG=void 0;var hl=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};bs.PRNG=hl;});var Jh=x(As=>{Object.defineProperty(As,"__esModule",{value:true});As.StatePatch=void 0;var dl=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:true}:{result:t,exists:false}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:true}:{result:t,exists:false}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:true}:{result:t,exists:false}}};As.StatePatch=dl;});var pl=x(ti=>{Object.defineProperty(ti,"__esModule",{value:true});ti.SimpleJson=void 0;var ei=class r{static TextToDictionary(e){return new r.Reader(e).ToDictionary()}static TextToArray(e){return new r.Reader(e).ToArray()}};ti.SimpleJson=ei;(function(r){class e{constructor(i){if(JSON.parse("0",(s,o,u)=>u!=null)){let s=(o,u,l)=>Number.isInteger(u)&&l.source.endsWith(".0")?l.source+"f":u;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=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(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=t,(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;})(t=r.Writer||(r.Writer={}));})(ei||(ti.SimpleJson=ei={}));});var zh=x(ws=>{Object.defineProperty(ws,"__esModule",{value:true});ws.Flow=void 0;var Hh=ul(),xs=pn(),vg=fe(),fl=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new Hh.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=xs.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=xs.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let i=n.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),e.WriteProperty("outputStream",n=>xs.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, vg.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let i of this.currentChoices)xs.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let a=e[`${n.originalThreadIndex}`];n.threadAtGeneration=new Hh.CallStack.Thread(a,t);}}}};ws.Flow=fl;});var Xh=x(Ts=>{Object.defineProperty(Ts,"__esModule",{value:true});Ts.StoryState=void 0;var Sg=ul(),Eg=$h(),he=ee(),Dt=Vt(),Dg=fs(),ml=rs(),Uh=xe(),De=me(),gl=Ft(),bt=pn(),bg=cl(),Ag=It(),fn=jn(),ni=en(),ae=H(),xg=_n(),qe=fe(),wg=Qn(),_g=Jh(),Kh=pl(),_s=zh(),Tg=Te(),Cl=class r{ToJson(e=false){let t=new Kh.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=Kh.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let n=this.story.ContentAtPath(new Uh.Path(e)).container;if(n===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(n,0),t.exists)return t.result}return t=(0, ni.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, qe.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(e,0);if(i.exists)return i.result}let t=e.path.toString(),n=(0, ni.tryGetValueFromMap)(this._visitCounts,t,null);return n.exists?n.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let i=this.VisitCountForContainer(e);i++,this._patch.SetVisitCount(e,i);return}let t=e.path.toString(),n=(0, ni.tryGetValueFromMap)(this._visitCounts,t,null);n.exists?this._visitCounts.set(t,n.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(e,0);if(i.exists)return this.currentTurnIndex-i.result}let t=e.path.toString(),n=(0, ni.tryGetValueFromMap)(this._turnIndices,t,0);return n.exists?this.currentTurnIndex-n.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, qe.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, qe.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new gl.StringBuilder,t=false;for(let n of this.outputStream){let i=(0, ae.asOrNull)(n,he.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, ae.asOrNull)(n,De.ControlCommand);a!==null&&(a.commandType==De.ControlCommand.CommandType.BeginTag?t=true:a.commandType==De.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new gl.StringBuilder,n=-1,i=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&n==-1&&(n=a),o||(s!=`
14
+ `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};lr.CommentEliminator=Ja;});var hr=x(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.Conditional=void 0;var $d=re(),nh=me(),Jd=Z(),Ha=class extends Jd.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new $d.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(nh.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=nh.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=t;}super.ResolveReferences(e);}};ur.Conditional=Ha;});var Et=x(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.Text=void 0;var Hd=Z(),zd=ee(),za=class extends Hd.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new zd.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};cr.Text=za;});var dr=x(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.ConstantDeclaration=void 0;var Ud=Z(),Kd=ct(),Ua=class extends Ud.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,Kd.SymbolType.Var);}};pr.ConstantDeclaration=Ua;});var an=x(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.FlowLevel=void 0;var ih;(function(r){r[r.Story=0]="Story",r[r.Knot=1]="Knot",r[r.Stitch=2]="Stitch",r[r.WeavePoint=3]="WeavePoint";})(ih||(fr.FlowLevel=ih={}));});var Mn=x(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.Gather=void 0;var Xd=re(),Yd=Z(),Qd=ct(),Ka=class extends Yd.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let n=new Xd.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"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Qd.SymbolType.SubFlowAndWeave);}};mr.Gather=Ka;});var Lt=x(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.Path=void 0;var gr=z(),rh=tt(),on=an(),Zd=Bt(),Xa=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?on.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(gr.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===on.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, gr.asOrNull)(i,rh.FlowBase);if(l!==null?o=l.flowLevel+1:o=on.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, gr.asOrNull)(n,Zd.Weave);if(i&&l!==null&&(o||a===on.FlowLevel.WeavePoint))return l.WeavePointNamed(i);let u=(0, gr.asOrNull)(n,rh.FlowBase);if(i&&u!==null){let h=s||u.flowLevel===on.FlowLevel.Knot;return u.ContentWithNameAtLevel(i,a,h)}return null},Object.values(on.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};Cr.Path=Xa;});var Za=x(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.ReturnType=void 0;var ef=Z(),tf=re(),Ya=me(),nf=Vt(),Qa=class extends ef.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new tf.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(Ya.ControlCommand.EvalStart()),t.AddContent(new nf.Void),t.AddContent(Ya.ControlCommand.EvalEnd())),t.AddContent(Ya.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};yr.ReturnType=Qa;});var Gn=x(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.ClosestFlowBase=void 0;function rf(r){let e=r.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}vr.ClosestFlowBase=rf;});var Er=x(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.Identifier=void 0;var eo=class r{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new r("DONE")}};Sr.Identifier=eo;});var tt=x(Dr=>{Object.defineProperty(Dr,"__esModule",{value:true});Dr.FlowBase=void 0;var sf=sn(),to=un(),af=ln(),nt=an(),of=Mn(),lf=Z(),uf=Lt(),hf=Za(),cf=re(),pf=et(),df=vt(),no=ct(),ff=Bt(),mf=Gn(),gf=Er(),sh=z(),io=class r extends lf.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,n=null,i=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 d of s){let f=(0, sh.asOrNull)(d,r);f?(this._firstChildFlow===null&&(this._firstChildFlow=f),c.push(d),!((l=f.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=f.identifier)===null||u===void 0?void 0:u.name,f)):h.push(d);}o&&h.push(new of.Gather(null,1),new to.Divert(new uf.Path(gf.Identifier.Done())));let p=[];return h.length>0&&(this._rootWeave=new ff.Weave(h,0),p.push(this._rootWeave)),c.length>0&&p.push(...c),p},this.ResolveVariableWithName=(s,o)=>{var l;let u={},h=o===null?this:(0, mf.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===nt.FlowLevel.Knot||this.flowLevel===nt.FlowLevel.Stitch)&&(o=this.Find(hf.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 cf.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,p=c.runtimeObject;u===0&&!c.hasParameters&&this.flowLevel===nt.FlowLevel.Knot&&(this._startingSubFlowDivert=new pf.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=p);let d=p,f=l.namedContent.get(d.name)||null;if(f){let g=`${this.GetType()} already contains flow named '${d.name}' (at ${f.debugMetadata})`;this.Error(g,c);}l.AddToNamedContentOnly(d);}else h&&l.AddContent(h.runtimeObject);u+=1;}return this.flowLevel!==nt.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 df.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===nt.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(s),c))return c;if(o===nt.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,nt.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!==nt.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(to.Divert)();for(let l of s)!l.isFunctionCall&&!(l.parent instanceof af.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(sf.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, sh.asOrNull)(s,to.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=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,no.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((t=this.args[i].identifier)===null||t===void 0?void 0:t.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!==nt.FlowLevel.Story){let i=this.flowLevel===nt.FlowLevel.Knot?no.SymbolType.Knot:no.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};Dr.FlowBase=io;});var Ar=x(br=>{Object.defineProperty(br,"__esModule",{value:true});br.ContentList=void 0;var Cf=re(),yf=Z(),vf=Et(),Sf=z(),ro=class extends yf.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let i=(0, Sf.asOrNull)(this.content[n],vf.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 Cf.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};br.ContentList=ro;});var hn=x(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.VariableReference=void 0;var Ef=Pe(),Df=Oe(),so=class extends Ef.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new Df.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};wr.VariableReference=so;});var cn=x(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.VariableReference=void 0;var bf=Ar(),Af=Le(),ah=tt(),wf=Lt(),xf=hn(),_f=Bt(),Of=Er(),oh=z(),ao=class extends Af.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(oh.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new Of.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=t=>{let n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new xf.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);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new wf.Path(this.pathIdentifiers),n=t.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, oh.asOrNull)(n,ah.FlowBase);i&&i.isFunction&&(this.parent instanceof _f.Weave||this.parent instanceof bf.ContentList||this.parent instanceof ah.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${t}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};xr.VariableReference=ao;});var $n=x(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.FunctionCall=void 0;var it=me(),Pf=un(),Tf=ln(),Ff=Le(),Nf=Fe(),If=ee(),Or=Ze(),lh=$i(),Vf=Lt(),kf=ee(),Rf=cn(),_r=z(),Pr=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(e,t){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(it.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(it.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, _r.asOrNull)(this.args[0],Tf.DivertTarget),o=(0, _r.asOrNull)(this.args[0],Rf.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(it.ControlCommand.TurnsSince()):n.AddContent(it.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, _r.asOrNull)(this.args[s],lh.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(it.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, _r.asOrNull)(this.args[0],lh.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(it.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(it.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(it.ControlCommand.ListRandom());else if(Or.NativeFunctionCall.CallExistsWithName(this.name)){let s=Or.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(Or.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 kf.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(it.ControlCommand.ListFromInt());else {let s=new Nf.InkList;s.SetInitialOriginName(this.name),n.AddContent(new If.ListValue(s));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(it.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new Pf.Divert(new Vf.Path(e),t),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,n=t.runtimeDivert.variableDivertName!=null;if(n){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let i=t.targetContent;if(i===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${r.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Tr.FunctionCall=Pr;Pr.IsBuiltIn=r=>Or.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 lo=x(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.MultipleConditionExpression=void 0;var Lf=Le(),Bf=Ze(),oo=class extends Lf.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let n=true;for(let i of this.subExpressions)i.GenerateIntoContainer(t),n||t.AddContent(Bf.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Fr.MultipleConditionExpression=oo;});var ln=x(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.DivertTarget=void 0;var Wf=Na(),jf=sn(),qf=hr(),Mf=po(),Gf=ee(),uo=Le(),$f=tt(),uh=$n(),Jf=lo(),hh=cn(),ho=z(),co=class r extends uo.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new Gf.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, ho.asOrNull)(t,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(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof uo.Expression;){let i=false,a=false,s=t.parent;if(s instanceof Wf.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof r||o.leftExpression instanceof hh.VariableReference)&&(o.rightExpression instanceof r||o.rightExpression instanceof hh.VariableReference)||(i=true),a=true;}else if(s instanceof uh.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof uo.Expression||s instanceof Jf.MultipleConditionExpression||s instanceof jf.Choice&&s.condition===t||s instanceof qf.Conditional||s instanceof Mf.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;t=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, ho.asOrNull)(this.parent,uh.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, ho.asOrNull)(n,$f.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=co;});var un=x(Ir=>{Object.defineProperty(Ir,"__esModule",{value:true});Ir.Divert=void 0;var Hf=re(),Jn=me(),zf=et(),fo=ln(),mo=tt(),Uf=$n(),Kf=Z(),ch=Lt(),Xf=Oe(),ph=kt(),Yf=ee(),dh=cn(),Qf=Gn(),Hn=z(),go=class extends Kf.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return Jn.ControlCommand.End();if(this.isDone)return Jn.ControlCommand.Done();this.runtimeDivert=new zf.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 Hf.Container;if(n){this.isFunctionCall||i.AddContent(Jn.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, Hn.asOrNull)(o,dh.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let h=new ch.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 p=new Yf.VariablePointerValue(u.name);i.AddContent(p);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Jn.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Jn.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?ph.PushPopType.Function:ph.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, Hn.asOrNull)((0, Qf.ClosestFlowBase)(this),mo.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, Hn.asOrNull)(this.targetContent,mo.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 fo.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, Hn.asOrNull)(l,dh.VariableReference);if(!(l instanceof fo.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 ch.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},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, Hn.asOrNull)(this.targetContent,mo.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof fo.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let n=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=Uf.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new Xf.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,n=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,n):super.Error(`Divert ${e}`,t,n);}};Ir.Divert=go;});var fh=x(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.GatherPointToResolve=void 0;var Co=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};Vr.GatherPointToResolve=Co;});var mh=x(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.SequenceDivertToResolve=void 0;var yo=class{constructor(e,t){this.divert=e,this.targetContent=t;}};kr.SequenceDivertToResolve=yo;});var vo=x(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.SequenceType=void 0;var gh;(function(r){r[r.Stopping=1]="Stopping",r[r.Cycle=2]="Cycle",r[r.Shuffle=4]="Shuffle",r[r.Once=8]="Once";})(gh||(Rr.SequenceType=gh={}));});var Do=x(Wr=>{Object.defineProperty(Wr,"__esModule",{value:true});Wr.Sequence=void 0;var Ch=re(),Je=me(),So=et(),zn=ee(),Lr=Ze(),Zf=Z(),em=mh(),Br=vo(),tm=Bt(),Eo=class extends Zf.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new Ch.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(Je.ControlCommand.EvalStart()),n.AddContent(Je.ControlCommand.VisitIndex());let i=(this.sequenceType&Br.SequenceType.Once)>0,a=(this.sequenceType&Br.SequenceType.Cycle)>0,s=(this.sequenceType&Br.SequenceType.Stopping)>0,o=(this.sequenceType&Br.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(i&&(l+=1),s||i?(n.AddContent(new zn.IntValue(l-1)),n.AddContent(Lr.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new zn.IntValue(this.sequenceElements.length)),n.AddContent(Lr.NativeFunctionCall.CallWithName("%"))),o){let h=Je.ControlCommand.NoOp();if(i||s){let p=s?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(Je.ControlCommand.Duplicate()),n.AddContent(new zn.IntValue(p)),n.AddContent(Lr.NativeFunctionCall.CallWithName("=="));let d=new So.Divert;d.isConditional=true,n.AddContent(d),this.AddDivertToResolve(d,h);}let c=this.sequenceElements.length;s&&(c-=1),n.AddContent(new zn.IntValue(c)),n.AddContent(Je.ControlCommand.SequenceShuffleIndex()),(i||s)&&n.AddContent(h);}n.AddContent(Je.ControlCommand.EvalEnd());let u=Je.ControlCommand.NoOp();for(let h=0;h<l;h+=1){n.AddContent(Je.ControlCommand.EvalStart()),n.AddContent(Je.ControlCommand.Duplicate()),n.AddContent(new zn.IntValue(h)),n.AddContent(Lr.NativeFunctionCall.CallWithName("==")),n.AddContent(Je.ControlCommand.EvalEnd());let c=new So.Divert;c.isConditional=true,n.AddContent(c);let p;h<this.sequenceElements.length?p=this.sequenceElements[h].runtimeObject:p=new Ch.Container,p.name=`s${h}`,p.InsertContent(Je.ControlCommand.PopEvaluatedValue(),0);let d=new So.Divert;p.AddContent(d),n.AddToNamedContentOnly(p),this.AddDivertToResolve(c,p),this.AddDivertToResolve(d,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new em.SequenceDivertToResolve(n,i));},this.sequenceType=t,this.sequenceElements=[];for(let n of e){let i=n.content,a=null;i===null||i.length===0?a=n:a=new tm.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};Wr.Sequence=Eo;});var Ao=x(jr=>{Object.defineProperty(jr,"__esModule",{value:true});jr.TunnelOnwards=void 0;var nm=re(),Un=me(),im=et(),rm=ee(),sm=Z(),am=Vt(),om=z(),lm=hn(),bo=class extends sm.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new nm.Container;if(e.AddContent(Un.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(s==-1&&u.commandType===Un.ControlCommand.CommandType.EvalStart?s=l:u.commandType===Un.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=s+1;l<o;l+=1){let u=n.content[l];u.parent=null,e.AddContent(n.content[l]);}}}let i=(0, om.asOrNull)(t,im.Divert);if(i!=null&&i.hasVariableTarget){let a=new lm.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new rm.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new am.Void);return e.AddContent(Un.ControlCommand.EvalEnd()),e.AddContent(Un.ControlCommand.PopTunnel()),e},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};jr.TunnelOnwards=bo;});var _o=x(qr=>{Object.defineProperty(qr,"__esModule",{value:true});qr.ListDefinition=void 0;var wo=Fe(),xo=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let n=new wo.InkListItem(this.name,e);this._items.set(n.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?false:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[n,i]of this._itemNameToValues)if(i==e)return t=new wo.InkListItem(this.name,n),{result:t,exists:true};return t=wo.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(e.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};qr.ListDefinition=xo;});var Gr=x(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.ListDefinition=void 0;var um=Fe(),hm=Fe(),cm=_o(),pm=ee(),dm=Z(),fm=ct(),Oo=class extends dm.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let n of this.itemDefinitions)t.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):t.set(n.name,n.seriesValue);return new cm.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,i;let a=new um.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new hm.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 pm.ListValue(a)};let t=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(t=n.explicitValue),n.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,fm.SymbolType.List);}};Mr.ListDefinition=Oo;});var To=x($r=>{Object.defineProperty($r,"__esModule",{value:true});$r.VariableAssignment=void 0;var mm=re(),gm=Gn(),Cm=Gr(),ym=Z(),yh=ct(),vm=vt(),Sm=cn(),Em=z(),Po=class extends ym.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, gm.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new mm.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new vm.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!n,i instanceof Cm.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?yh.SymbolType.Var:yh.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, Em.asOrNull)(this.expression,Sm.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};$r.VariableAssignment=Po;});var Bt=x(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.Weave=void 0;var vh=Oi(),We=sn(),Jr=hr(),Dm=dr(),bm=re(),Hr=un(),Am=et(),wm=ln(),xm=tt(),rt=Mn(),_m=fh(),Om=Z(),Fo=Do(),Pm=Et(),Tm=Ao(),Fm=To(),je=z(),No=class r extends Om.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let n=this.content.length-1;n>=0;--n){e=this.content[n];let i=(0, je.asOrNull)(e,Pm.Text);if(!(i&&i.text===`
15
+ `)&&!this.IsGlobalDeclaration(e))break}let t=(0, je.asOrNull)(e,r);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-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(rt.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(We.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 rt.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 We.Choice||i instanceof rt.Gather){let s=i.indentationDepth-1;if(s>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let c=(0, je.asOrNull)(this.content[n],We.Choice)||(0, je.asOrNull)(this.content[n],rt.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 We.Choice||i instanceof rt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new bm.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof We.Choice||n instanceof rt.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 rt.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof Hr.Divert)l=o.runtimeObject;else {l=new Am.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new _m.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof rt.Gather)this.AddRuntimeForGather(n);else if(n instanceof We.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof rt.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, je.asOrNull)(n,We.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, je.asOrNull)(s,r);o&&(!a&&n===null&&(n=o),a&&i===null&&(i=o)),(s instanceof Fo.Sequence||s instanceof Jr.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 We.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof We.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, je.asOrNull)(n,Fm.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, je.asOrNull)(n,Dm.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, je.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 We.Choice||u instanceof rt.Gather||u instanceof r)break;i.push(u);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof vh.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 We.Choice||a instanceof Hr.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 Fo.Sequence||s instanceof Jr.Conditional){i=(0, je.asOrNull)(s,Jr.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(We.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(Hr.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof wm.DivertTarget))!==null&&(s=true),l.Find(Tm.TunnelOnwards)()!=null){s=true;break}o=l;}if(!s){if(o instanceof vh.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, je.asOrNull)(n.content[i],Hr.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, je.asOrNull)(i,xm.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);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof Fo.Sequence||n instanceof Jr.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};zr.Weave=No;});var po=x(Kr=>{Object.defineProperty(Kr,"__esModule",{value:true});Kr.ConditionalSingleBranch=void 0;var Sh=re(),Ur=me(),Eh=et(),Nm=Z(),Im=Ze(),Vm=ee(),km=Et(),Rm=Bt(),Lm=z(),Io=class extends Nm.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=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, Lm.asOrNull)(i,km.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new Sh.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(Ur.ControlCommand.Duplicate()),this._conditionalDivert=new Eh.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(Ur.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(Im.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(Ur.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new Vm.StringValue(`
16
+ `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Ur.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Eh.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new Sh.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new Rm.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};Kr.ConditionalSingleBranch=Io;});var bh=x(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.CustomFlags=void 0;var Dh;(function(r){r[r.ParsingString=1]="ParsingString",r[r.TagActive=2]="TagActive";})(Dh||(Xr.CustomFlags=Dh={}));});var Ah=x(Yr=>{Object.defineProperty(Yr,"__esModule",{value:true});Yr.DebugMetadata=void 0;var Vo=class r{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new r;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumber<e.startLineNumber?(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>e.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<e.endLineNumber?(t.endLineNumber=e.endLineNumber,t.endCharacterNumber=e.endCharacterNumber):(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=Math.max(this.endCharacterNumber,e.endCharacterNumber)),t}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};Yr.DebugMetadata=Vo;});var wh=x(Qr=>{Object.defineProperty(Qr,"__esModule",{value:true});Qr.ExternalDeclaration=void 0;var Bm=Z(),ko=class extends Bm.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};Qr.ExternalDeclaration=ko;});var xh=x(Zr=>{Object.defineProperty(Zr,"__esModule",{value:true});Zr.FlowDecl=void 0;var Ro=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};Zr.FlowDecl=Ro;});var Bo=x(es=>{Object.defineProperty(es,"__esModule",{value:true});es.Wrap=void 0;var Wm=Z(),Lo=class extends Wm.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};es.Wrap=Lo;});var _h=x(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.Glue=void 0;var jm=Bo(),Wo=class extends jm.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};ts.Glue=Wo;});var is=x(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.Glue=void 0;var qm=Pe(),jo=class extends qm.InkObject{toString(){return "Glue"}};ns.Glue=jo;});var Ph=x(rs=>{Object.defineProperty(rs,"__esModule",{value:true});rs.IncDecExpression=void 0;var Mm=Ar(),Oh=Le(),Gm=tt(),$m=Ze(),Jm=ee(),Hm=vt(),zm=hn(),Um=Bt(),qo=class extends Oh.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new zm.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new Jm.IntValue(1)),i.AddContent($m.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new Hm.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?"++":"--")},t instanceof Oh.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!n):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let n=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof Um.Weave)&&!(this.parent instanceof Gm.FlowBase)&&!(this.parent instanceof Mm.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};rs.IncDecExpression=qo;});var Go=x(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.IncludedFile=void 0;var Km=Z(),Mo=class extends Km.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};ss.IncludedFile=Mo;});var Th=x(as=>{Object.defineProperty(as,"__esModule",{value:true});as.InfixOperator=void 0;var $o=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};as.InfixOperator=$o;});var Ho=x(os=>{Object.defineProperty(os,"__esModule",{value:true});os.Knot=void 0;var Xm=tt(),Fh=an(),Jo=class extends Xm.FlowBase{get flowLevel(){return Fh.FlowLevel.Knot}constructor(e,t,n,i){super(e,t,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let n in this.subFlowsByName){let i=t.ContentWithNameAtLevel(n,Fh.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);}}}};os.Knot=Jo;});var Nh=x(ls=>{Object.defineProperty(ls,"__esModule",{value:true});ls.List=void 0;var Ym=Le(),Qm=Fe(),Zm=Fe(),eg=ee(),zo=class extends Ym.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,i;let a=new Qm.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 Zm.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(c,h.seriesValue);}}t.AddContent(new eg.ListValue(a));};}get typeName(){return "List"}};ls.List=zo;});var Ko=x(us=>{Object.defineProperty(us,"__esModule",{value:true});us.ListElementDefinition=void 0;var tg=Z(),ng=ct(),Uo=class extends tg.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,n=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=n,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,ng.SymbolType.ListItem);}};us.ListElementDefinition=Uo;});var Xo=x(hs=>{Object.defineProperty(hs,"__esModule",{value:true});hs.StatementLevel=void 0;var Ih;(function(r){r[r.InnerBlock=0]="InnerBlock",r[r.Stitch=1]="Stitch",r[r.Knot=2]="Knot",r[r.Top=3]="Top";})(Ih||(hs.StatementLevel=Ih={}));});var Qo=x(cs=>{Object.defineProperty(cs,"__esModule",{value:true});cs.Stitch=void 0;var ig=tt(),rg=an(),Yo=class extends ig.FlowBase{get flowLevel(){return rg.FlowLevel.Stitch}constructor(e,t,n,i){super(e,t,n,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};cs.Stitch=Yo;});var ds=x(ps=>{Object.defineProperty(ps,"__esModule",{value:true});ps.Tag=void 0;var sg=Pe(),Zo=class extends sg.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};ps.Tag=Zo;});var tl=x(fs=>{Object.defineProperty(fs,"__esModule",{value:true});fs.Choice=void 0;var ag=Oe(),og=fe(),lg=Pe(),el=class r extends lg.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, og.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new ag.Path(e);}Clone(){let e=new r;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};fs.Choice=el;});var il=x(ms=>{Object.defineProperty(ms,"__esModule",{value:true});ms.ListDefinitionsOrigin=void 0;var ug=Fe(),hg=ee(),cg=fe(),nl=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[n,i]of t.items){let a=ug.InkListItem.fromSerializedKey(n),s=new hg.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 e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let n=this._lists.get(e);return n?{result:n,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, cg.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};ms.ListDefinitionsOrigin=nl;});var dn=x(vs=>{Object.defineProperty(vs,"__esModule",{value:true});vs.JsonSerialisation=void 0;var gs=re(),Ie=ee(),Vh=is(),J=me(),pn=kt(),kh=et(),Rh=Xi(),rl=hn(),Lh=vt(),sl=Ze(),Bh=Vt(),Wh=ds(),pg=Oe(),jh=tl(),dg=_o(),fg=il(),Cs=Fe(),se=z(),Wt=fe(),ys=class r{static JArrayToRuntimeObjList(e,t=false){let n=e.length;t&&n--;let i=[];for(let a=0;a<n;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, Wt.throwNullException)("runtimeObj");i.push(o);}return i}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[n,i]of t)e.WritePropertyStart(n),this.WriteRuntimeObject(e,i),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let n of t)this.WriteRuntimeObject(e,n);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[n,i]of t)e.WriteIntProperty(n,i);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let n=(0, se.asOrNull)(t,gs.Container);if(n){this.WriteRuntimeContainer(e,n);return}let i=(0, se.asOrNull)(t,kh.Divert);if(i){let v="->";i.isExternal?v="x()":i.pushesToStack&&(i.stackPushType==pn.PushPopType.Function?v="f()":i.stackPushType==pn.PushPopType.Tunnel&&(v="->t->"));let E;i.hasVariableTarget?E=i.variableDivertName:E=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(v,E),i.hasVariableTarget&&e.WriteProperty("var",true),i.isConditional&&e.WriteProperty("c",true),i.externalArgs>0&&e.WriteIntProperty("exArgs",i.externalArgs),e.WriteObjectEnd();return}let a=(0, se.asOrNull)(t,Rh.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, se.asOrNull)(t,Ie.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, se.asOrNull)(t,Ie.IntValue);if(o){e.WriteInt(o.value);return}let l=(0, se.asOrNull)(t,Ie.FloatValue);if(l){e.WriteFloat(l.value);return}let u=(0, se.asOrNull)(t,Ie.StringValue);if(u){u.isNewline?e.Write(`
17
+ `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(u.value),e.WriteStringEnd());return}let h=(0, se.asOrNull)(t,Ie.ListValue);if(h){this.WriteInkList(e,h);return}let c=(0, se.asOrNull)(t,Ie.DivertTargetValue);if(c){if(e.WriteObjectStart(),c.value===null)return (0, Wt.throwNullException)("divTargetVal.value");e.WriteProperty("^->",c.value.componentsString),e.WriteObjectEnd();return}let p=(0, se.asOrNull)(t,Ie.VariablePointerValue);if(p){e.WriteObjectStart(),e.WriteProperty("^var",p.value),e.WriteIntProperty("ci",p.contextIndex),e.WriteObjectEnd();return}if((0, se.asOrNull)(t,Vh.Glue)){e.Write("<>");return}let f=(0, se.asOrNull)(t,J.ControlCommand);if(f){e.Write(r._controlCommandNames[f.commandType]);return}let g=(0, se.asOrNull)(t,sl.NativeFunctionCall);if(g){let v=g.name;v=="^"&&(v="L^"),e.Write(v);return}let b=(0, se.asOrNull)(t,rl.VariableReference);if(b){e.WriteObjectStart();let v=b.pathStringForCount;v!=null?e.WriteProperty("CNT?",v):e.WriteProperty("VAR?",b.name),e.WriteObjectEnd();return}let D=(0, se.asOrNull)(t,Lh.VariableAssignment);if(D){e.WriteObjectStart();let v=D.isGlobal?"VAR=":"temp=";e.WriteProperty(v,D.variableName),D.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, se.asOrNull)(t,Bh.Void)){e.Write("void");return}let m=(0, se.asOrNull)(t,Wh.Tag);if(m){e.WriteObjectStart(),e.WriteProperty("#",m.text),e.WriteObjectEnd();return}let C=(0, se.asOrNull)(t,jh.Choice);if(C){this.WriteChoice(e,C);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(e[n]);if(i===null)return (0, Wt.throwNullException)("inkObject");t.set(n,i);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let n in e)e.hasOwnProperty(n)&&t.set(n,parseInt(e[n]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return Ie.Value.Create(e);if(typeof e=="string"){let t=e.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(t);if(n)return new Ie.FloatValue(parseFloat(n[0]));let i=t[0];if(i=="^")return new Ie.StringValue(t.substring(1));if(i==`
18
+ `&&t.length==1)return new Ie.StringValue(`
19
+ `);if(t=="<>")return new Vh.Glue;for(let a=0;a<r._controlCommandNames.length;++a){let s=r._controlCommandNames[a];if(t==s)return new J.ControlCommand(a)}if(t=="L^"&&(t="^"),sl.NativeFunctionCall.CallExistsWithName(t))return sl.NativeFunctionCall.CallWithName(t);if(t=="->->")return J.ControlCommand.PopTunnel();if(t=="~ret")return J.ControlCommand.PopFunction();if(t=="void")return new Bh.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new Ie.DivertTargetValue(new pg.Path(n.toString()));if(t["^var"]){n=t["^var"];let h=new Ie.VariablePointerValue(n.toString());return "ci"in t&&(n=t.ci,h.contextIndex=parseInt(n)),h}let i=false,a=false,s=pn.PushPopType.Function,o=false;if((n=t["->"])?i=true:(n=t["f()"])?(i=true,a=true,s=pn.PushPopType.Function):(n=t["->t->"])?(i=true,a=true,s=pn.PushPopType.Tunnel):(n=t["x()"])&&(i=true,o=true,a=false,s=pn.PushPopType.Function),i){let h=new kh.Divert;h.pushesToStack=a,h.stackPushType=s,h.isExternal=o;let c=n.toString();return (n=t.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!t.c,o&&(n=t.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=t["*"]){let h=new Rh.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=t.flg)&&(h.flags=parseInt(n)),h}if(n=t["VAR?"])return new rl.VariableReference(n.toString());if(n=t["CNT?"]){let h=new rl.VariableReference;return h.pathStringForCount=n.toString(),h}let l=false,u=false;if((n=t["VAR="])?(l=true,u=true):(n=t["temp="])&&(l=true,u=false),l){let h=n.toString(),c=!t.re,p=new Lh.VariableAssignment(h,c);return p.isGlobal=u,p}if(t["#"]!==void 0)return n=t["#"],new Wh.Tag(n.toString());if(n=t.list){let h=n,c=new Cs.InkList;if(n=t.origins){let p=n;c.SetInitialOriginNames(p);}for(let p in h)if(h.hasOwnProperty(p)){let d=h[p],f=new Cs.InkListItem(p),g=parseInt(d);c.Add(f,g);}return new Ie.ListValue(c)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,n){return JSON.stringify(e,(i,a)=>t?.some(s=>s===i)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=false){if(e.WriteArrayStart(),t===null)return (0, Wt.throwNullException)("container");for(let l of t.content)this.WriteRuntimeObject(e,l);let i=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!n,o=i!=null||a>0||s;if(o&&e.WriteObjectStart(),i!=null)for(let[l,u]of i){let h=l,c=(0, se.asOrNull)(u,gs.Container);e.WritePropertyStart(h),this.WriteRuntimeContainer(e,c,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),s&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new gs.Container;t.content=this.JArrayToRuntimeObjList(e,true);let n=e[e.length-1];if(n!=null){let i=new Map;for(let a in n)if(a=="#f")t.countFlags=parseInt(n[a]);else if(a=="#n")t.name=n[a].toString();else {let s=this.JTokenToRuntimeObject(n[a]),o=(0, se.asOrNull)(s,gs.Container);o&&(o.name=a),i.set(a,s);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new jh.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t.isInvisibleDefault=!!e.isInvisibleDefault,t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),e.WriteProperty("isInvisibleDefault",t.isInvisibleDefault),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, Wt.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of n){let s=Cs.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, Wt.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(s.originName?s.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(s.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of n.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let i={};for(let[a,s]of n.items){let o=Cs.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Wt.throwNullException)("item.itemName");i[o.itemName]=s;}t[n.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),s=t[i],o=new Map;for(let u in s)if(t.hasOwnProperty(i)){let h=s[u];o.set(u,parseInt(h));}let l=new dg.ListDefinition(a,o);n.push(l);}return new fg.ListDefinitionsOrigin(n)}};vs.JsonSerialisation=ys;ys._controlCommandNames=(()=>{let r=[];r[J.ControlCommand.CommandType.EvalStart]="ev",r[J.ControlCommand.CommandType.EvalOutput]="out",r[J.ControlCommand.CommandType.EvalEnd]="/ev",r[J.ControlCommand.CommandType.Duplicate]="du",r[J.ControlCommand.CommandType.PopEvaluatedValue]="pop",r[J.ControlCommand.CommandType.PopFunction]="~ret",r[J.ControlCommand.CommandType.PopTunnel]="->->",r[J.ControlCommand.CommandType.BeginString]="str",r[J.ControlCommand.CommandType.EndString]="/str",r[J.ControlCommand.CommandType.NoOp]="nop",r[J.ControlCommand.CommandType.ChoiceCount]="choiceCnt",r[J.ControlCommand.CommandType.Turns]="turn",r[J.ControlCommand.CommandType.TurnsSince]="turns",r[J.ControlCommand.CommandType.ReadCount]="readc",r[J.ControlCommand.CommandType.Random]="rnd",r[J.ControlCommand.CommandType.SeedRandom]="srnd",r[J.ControlCommand.CommandType.VisitIndex]="visit",r[J.ControlCommand.CommandType.SequenceShuffleIndex]="seq",r[J.ControlCommand.CommandType.StartThread]="thread",r[J.ControlCommand.CommandType.Done]="done",r[J.ControlCommand.CommandType.End]="end",r[J.ControlCommand.CommandType.ListFromInt]="listInt",r[J.ControlCommand.CommandType.ListRange]="range",r[J.ControlCommand.CommandType.ListRandom]="lrnd",r[J.ControlCommand.CommandType.BeginTag]="#",r[J.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<J.ControlCommand.CommandType.TOTAL_VALUES;++e)if(r[e]==null)throw new Error("Control command not accounted for in serialisation");return r})();});var ll=x(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.CallStack=void 0;var al=kt(),qh=Oe(),mg=Qn(),Mh=dn(),gg=ee(),Cg=Nt(),Kn=jn(),yg=_n(),Gh=en(),ol=fe(),Xn=class r{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){yg.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=Kn.Pointer.Null,arguments[0]instanceof mg.Story){let e=arguments[0];this._startOfRoot=Kn.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new r.Thread),this._threads[0].callstack.push(new r.Element(al.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let i of n){let a=i,s=new r.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=Kn.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let n of this._threads)n.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==al.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let i=new r.Element(e,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=t,i.functionStartInOutputStream=n,this.callStack.push(i);}CanPop(e=null){return this.canPop?e==null?true:this.currentElement.type==e:false}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let n=this.callStack[t-1],i=(0, Gh.tryGetValueFromMap)(n.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, Gh.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&gg.ListValue.RetainListOriginsForAssignment(s.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new Cg.StringBuilder;for(let t=0;t<this._threads.length;t++){let n=this._threads[t],i=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
20
+ `,t+1,this._threads.length,i?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==al.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=n.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, ol.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Yn.CallStack=Xn;(function(r){class e{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 e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}r.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=Kn.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=Kn.Pointer.Null,p,d=u.cPath;if(typeof d<"u"){p=d.toString();let D=a.ContentAtPath(new qh.Path(p));if(c.container=D.container,c.index=parseInt(u.idx),D.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+p+". Has the story changed since this save data was created?");D.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+p+"', 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: '"+p+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let f=!!u.exp,g=new e(h,c,f),b=u.temp;typeof b<"u"?g.temporaryVariables=Mh.JsonSerialisation.JObjectToDictionaryRuntimeObjs(b):g.temporaryVariables.clear(),this.callstack.push(g);}let o=i.previousContentObject;if(typeof o<"u"){let l=new qh.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let i=new t;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, ol.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"),Mh.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, ol.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}r.Thread=t;})(Xn||(Yn.CallStack=Xn={}));});var Jh=x(Es=>{Object.defineProperty(Es,"__esModule",{value:true});Es.VariablesState=void 0;var de=ee(),vg=Pn(),$h=dn(),ge=z(),Zn=en(),Dt=fe();function Sg(){return class{}}var Ss=class r extends Sg(){variableChangedEvent(e,t){for(let n of this.variableChangedEventCallbacks)n(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let n=this._globalVariables.get(t);this.variableChangedEvent(t,n);}if(this.patch!=null)for(let t of this.patch.changedVariables){let n=this.patch.TryGetGlobal(t,null);n.exists&&e.set(t,n);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,n]of e)this.variableChangedEvent(t,n);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(e),typeof n>"u"&&(n=this._defaultGlobalVariables.get(e)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new vg.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=de.Value.Create(t);if(n==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,n);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,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, Dt.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,n]of this._defaultGlobalVariables){let i=e[t];if(typeof i<"u"){let a=$h.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Dt.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let i=t,a=n;if(r.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let s=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(i),$h.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Dt.throwNullException)("obj1");if(t===null)return (0, Dt.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let n=(0, ge.asOrNull)(e,de.BoolValue);if(n!==null)return n.value===(0, ge.asOrThrows)(t,de.BoolValue).value;let i=(0, ge.asOrNull)(e,de.IntValue);if(i!==null)return i.value===(0, ge.asOrThrows)(t,de.IntValue).value;let a=(0, ge.asOrNull)(e,de.FloatValue);if(a!==null)return a.value===(0, ge.asOrThrows)(t,de.FloatValue).value;let s=(0, ge.asOrNull)(e,de.Value),o=(0, ge.asOrNull)(t,de.Value);if(s!==null&&o!==null)return (0, ge.isEquatable)(s.valueObject)&&(0, ge.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let n=this.GetRawVariableWithName(e,t),i=(0, ge.asOrNull)(n,de.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(e){let t=(0, Zn.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let n=null;if(t==0||t==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(e,null),i.exists)||(i=(0, Zn.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Zn.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Dt.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(e,t),n}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let n=e.variableName;if(n===null)return (0, Dt.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let s=(0, ge.asOrNull)(t,de.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, ge.asOrNull)(this.GetRawVariableWithName(n,i),de.VariablePointerValue),s!=null&&(n=s.variableName,i=s.contextIndex,a=i==0);while(s!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, ge.asOrThrows)(e,de.ListValue),i=(0, ge.asOrThrows)(t,de.ListValue);n.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(e,t){let n=null;if(this.patch===null&&(n=(0, Zn.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, Zn.tryGetValueFromMap)(this._globalVariables,e,null))),de.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, Dt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&n!==null&&t!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Dt.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let n=this.GetRawVariableWithName(e.variableName,t),i=(0, ge.asOrNull)(n,de.VariablePointerValue);return i??new de.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Es.VariablesState=Ss;Ss.dontSaveDefaultValues=true;});var hl=x(Ds=>{Object.defineProperty(Ds,"__esModule",{value:true});Ds.PRNG=void 0;var ul=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};Ds.PRNG=ul;});var Hh=x(bs=>{Object.defineProperty(bs,"__esModule",{value:true});bs.StatePatch=void 0;var cl=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:true}:{result:t,exists:false}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:true}:{result:t,exists:false}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:true}:{result:t,exists:false}}};bs.StatePatch=cl;});var pl=x(ti=>{Object.defineProperty(ti,"__esModule",{value:true});ti.SimpleJson=void 0;var ei=class r{static TextToDictionary(e){return new r.Reader(e).ToDictionary()}static TextToArray(e){return new r.Reader(e).ToArray()}};ti.SimpleJson=ei;(function(r){class e{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=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(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=t,(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;})(t=r.Writer||(r.Writer={}));})(ei||(ti.SimpleJson=ei={}));});var Uh=x(ws=>{Object.defineProperty(ws,"__esModule",{value:true});ws.Flow=void 0;var zh=ll(),As=dn(),Eg=fe(),dl=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new zh.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=As.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=As.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let i=n.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),e.WriteProperty("outputStream",n=>As.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, Eg.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let i of this.currentChoices)As.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let a=e[`${n.originalThreadIndex}`];n.threadAtGeneration=new zh.CallStack.Thread(a,t);}}}};ws.Flow=dl;});var Yh=x(_s=>{Object.defineProperty(_s,"__esModule",{value:true});_s.StoryState=void 0;var Dg=ll(),bg=Jh(),he=ee(),bt=kt(),Ag=ds(),fl=is(),Kh=Oe(),be=me(),ml=Nt(),At=dn(),wg=hl(),xg=Vt(),fn=jn(),ni=en(),ae=z(),_g=_n(),qe=fe(),Og=Qn(),Pg=Hh(),Xh=pl(),xs=Uh(),Tg=Fe(),gl=class r{ToJson(e=false){let t=new Xh.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=Xh.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let n=this.story.ContentAtPath(new Kh.Path(e)).container;if(n===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(n,0),t.exists)return t.result}return t=(0, ni.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, qe.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(e,0);if(i.exists)return i.result}let t=e.path.toString(),n=(0, ni.tryGetValueFromMap)(this._visitCounts,t,null);return n.exists?n.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let i=this.VisitCountForContainer(e);i++,this._patch.SetVisitCount(e,i);return}let t=e.path.toString(),n=(0, ni.tryGetValueFromMap)(this._visitCounts,t,null);n.exists?this._visitCounts.set(t,n.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(e,0);if(i.exists)return this.currentTurnIndex-i.result}let t=e.path.toString(),n=(0, ni.tryGetValueFromMap)(this._turnIndices,t,0);return n.exists?this.currentTurnIndex-n.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, qe.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, qe.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new ml.StringBuilder,t=false;for(let n of this.outputStream){let i=(0, ae.asOrNull)(n,he.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, ae.asOrNull)(n,be.ControlCommand);a!==null&&(a.commandType==be.ControlCommand.CommandType.BeginTag?t=true:a.commandType==be.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new ml.StringBuilder,n=-1,i=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&n==-1&&(n=a),o||(s!=`
21
21
  `&&n>0&&n!=i&&t.Append(" "),n=-1),s==`
22
- `&&(i=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new gl.StringBuilder;for(let n of this.outputStream){let i=(0, ae.asOrNull)(n,De.ControlCommand);if(i!=null){if(i.commandType==De.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(i.commandType==De.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=false;}}else if(e){let a=(0, ae.asOrNull)(n,he.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, ae.asOrNull)(n,Dg.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let n=this.CleanOutputWhitespace(t.toString());this._currentTags.push(n),t.Clear();}this._outputStreamTagsDirty=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 e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=fn.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=e,this._currentFlow=new _s.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new Eg.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new bg.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=fn.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,n=(0, ni.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new _s.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=true),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, qe.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new r(this.story);if(t._patch=new _g.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new Sg.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let n of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(n.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[n,i]of this._namedFlows)t._namedFlows.set(n,i),t._aliveFlowNamesDirty=true;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,true);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,false);this._patch=null;}}ApplyCountChanges(e,t,n){(n?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,n]of this._namedFlows)e.WriteProperty(t,i=>n.WriteJson(i));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>bt.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, qe.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>bt.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>bt.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",wg.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,n=t.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<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=t.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[u,l]of o){let h=u,c=l,d=new _s.Flow(h,this.story,c);if(Object.keys(s).length===1)this._currentFlow=new _s.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, qe.throwNullException)("this._namedFlows");this._namedFlows.set(h,d);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let u=t.currentFlowName;this._currentFlow=this._namedFlows.get(u);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=bt.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=bt.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let s=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=bt.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new Uh.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=bt.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=bt.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, ae.asOrNull)(e,he.StringValue);if(t!==null){let n=this.TrySplittingHeadTailWhitespace(t);if(n!==null){for(let i of n)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, qe.throwNullException)("single.value");let n=-1,i=-1;for(let h=0;h<t.length;h++){let c=t[h];if(c==`
22
+ `&&(i=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new ml.StringBuilder;for(let n of this.outputStream){let i=(0, ae.asOrNull)(n,be.ControlCommand);if(i!=null){if(i.commandType==be.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(i.commandType==be.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=false;}}else if(e){let a=(0, ae.asOrNull)(n,he.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, ae.asOrNull)(n,Ag.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let n=this.CleanOutputWhitespace(t.toString());this._currentTags.push(n),t.Clear();}this._outputStreamTagsDirty=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 e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=fn.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=e,this._currentFlow=new xs.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new bg.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new wg.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=fn.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,n=(0, ni.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new xs.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=true),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, qe.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new r(this.story);if(t._patch=new Pg.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new Dg.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let n of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(n.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[n,i]of this._namedFlows)t._namedFlows.set(n,i),t._aliveFlowNamesDirty=true;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,true);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,false);this._patch=null;}}ApplyCountChanges(e,t,n){(n?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,n]of this._namedFlows)e.WriteProperty(t,i=>n.WriteJson(i));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>At.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, qe.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>At.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>At.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",Og.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,n=t.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<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=t.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,p=new xs.Flow(h,this.story,c);if(Object.keys(s).length===1)this._currentFlow=new xs.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, qe.throwNullException)("this._namedFlows");this._namedFlows.set(h,p);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let l=t.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=At.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=At.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let s=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=At.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new Kh.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=At.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=At.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, ae.asOrNull)(e,he.StringValue);if(t!==null){let n=this.TrySplittingHeadTailWhitespace(t);if(n!==null){for(let i of n)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, qe.throwNullException)("single.value");let n=-1,i=-1;for(let h=0;h<t.length;h++){let c=t[h];if(c==`
23
23
  `)n==-1&&(n=h),i=h;else {if(c==" "||c==" ")continue;break}}let a=-1,s=-1;for(let h=t.length-1;h>=0;h--){let c=t[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=[],u=0,l=t.length;if(n!=-1){if(n>0){let h=new he.StringValue(t.substring(0,n));o.push(h);}o.push(new he.StringValue(`
25
- `)),u=i+1;}if(a!=-1&&(l=s),l>u){let h=t.substring(u,l);o.push(new he.StringValue(h));}if(a!=-1&&s>i&&(o.push(new he.StringValue(`
26
- `)),a<t.length-1)){let h=t.length-a-1,c=new he.StringValue(t.substring(a+1,a+1+h));o.push(c);}return o}PushToOutputStreamIndividual(e){let t=(0, ae.asOrNull)(e,ml.Glue),n=(0, ae.asOrNull)(e,he.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let a=-1,s=this.callStack.currentElement;s.type==Dt.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let l=this.outputStream.length-1;l>=0;l--){let h=this.outputStream[l],c=h instanceof De.ControlCommand?h:null;if((h instanceof ml.Glue?h:null)!=null){o=l;break}else if(c!=null&&c.commandType==De.ControlCommand.CommandType.BeginString){l>=a&&(a=-1);break}}let u=-1;if(o!=-1&&a!=-1?u=Math.min(a,o):o!=-1?u=o:u=a,u!=-1){if(n.isNewline)i=false;else if(n.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let l=this.callStack.elements;for(let h=l.length-1;h>=0;h--){let c=l[h];if(c.type==Dt.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, qe.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let n=this.outputStream[t],i=(0, ae.asOrNull)(n,De.ControlCommand),a=(0, ae.asOrNull)(n,he.StringValue);if(i!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t<this.outputStream.length;)(0, ae.asOrNull)(this.outputStream[t],he.StringValue)?this.outputStream.splice(t,1):t++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let e=this.outputStream.length-1;e>=0;e--){let t=this.outputStream[e];if(t instanceof ml.Glue)this.outputStream.splice(e,1);else if(t instanceof De.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof De.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof he.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof he.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, ae.asOrNull)(this.outputStream[e],De.ControlCommand);if(t instanceof De.ControlCommand&&t.commandType==De.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, ae.asOrNull)(e,he.ListValue);if(t){let n=t.value;if(n===null)return (0, qe.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, qe.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, qe.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, qe.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, ae.nullIfUndefined)(t)}else {if(e>this.evaluationStack.length)throw new Error("trying to pop too many objects");let t=this.evaluationStack.splice(this.evaluationStack.length-e,e);return (0, ae.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=fn.Pointer.Null,this.previousPointer=fn.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){xg.Debug.Assert(this.callStack.currentElement.type==Dt.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let n=this.outputStream[t],i=(0, ae.asOrNull)(n,he.StringValue),a=(0, ae.asOrNull)(n,De.ControlCommand);if(i!=null){if(a)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==Dt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(e);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(Dt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=fn.Pointer.StartOf(e),this.PassArgumentsToEvaluationStack(t);}PassArgumentsToEvaluationStack(e){if(e!==null)for(let t=0;t<e.length;t++){if(!(typeof e[t]=="number"||typeof e[t]=="string"||typeof e[t]=="boolean"||e[t]instanceof Tg.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, ae.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(he.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Dt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=fn.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Dt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let e=this.callStack.currentElement.evaluationStackHeightWhenPushed,t=null;for(;this.evaluationStack.length>e;){let n=this.PopEvaluationStack();t===null&&(t=n);}if(this.PopCallStack(Dt.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof Ag.Void)return null;let n=(0, ae.asOrThrows)(t,he.Value);return n.valueType==he.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(e,t){t?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(e)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(e));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};Ts.StoryState=Cl;});var Yh=x(Os=>{Object.defineProperty(Os,"__esModule",{value:true});Os.Stopwatch=void 0;var yl=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;}};Os.Stopwatch=yl;});var Zh=x(Ps=>{Object.defineProperty(Ps,"__esModule",{value:true});Ps.ErrorType=void 0;var Qh;(function(r){r[r.Author=0]="Author",r[r.Warning=1]="Warning",r[r.Error=2]="Error";})(Qh||(Ps.ErrorType=Qh={}));});var Qn=x(qt=>{Object.defineProperty(qt,"__esModule",{value:true});qt.Story=qt.InkList=void 0;var Ce=ie(),vl=we(),Sl=pn(),Og=Xh(),k=me(),Me=Vt(),Pg=Yi(),Fg=nl(),ec=Ze(),F=ee(),El=xe(),ii=It(),Fs=fs(),Ng=yt(),Ig=hn(),Vg=Qe(),Wt=On(),Dl=cl(),jt=Ft(),kg=rl(),Rg=Yh(),At=jn(),ri=Te(),R=H(),J=fe(),tc=pl(),nc=Zh(),Lg=Te();Object.defineProperty(qt,"InkList",{enumerable:true,get:function(){return Lg.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var mn=class r extends vl.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, J.throwNullException)("this._state");for(let t of this._state.currentChoices)t.isInvisibleDefault||(t.index=e.length,e.push(t));return e}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=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 e,t=null,n=null;if(arguments[0]instanceof Ce.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let i=arguments[0];n=tc.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new kg.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let i=n,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let 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 u;(u=i.listDefs)&&(this._listDefinitions=Sl.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, R.asOrThrows)(Sl.JsonSerialisation.JTokenToRuntimeObject(o),Ce.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new tc.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",r.inkVersionCurrent),e.WriteProperty("root",n=>Sl.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[i,a]of n.items){let s=ri.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(s.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new Og.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, J.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, J.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new El.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=e;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(e){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+e);this.state.SwitchFlow_Internal(e);}RemoveFlow(e){this.state.RemoveFlow_Internal(e);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(e){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(e);}ContinueInternal(e=0){this._profiler!=null&&this._profiler.PreContinue();let t=e>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!t&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=t,!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 Rg.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof Wt.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(Me.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(Me.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,nc.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,nc.ErrorType.Warning);this.ResetErrors();}else {let s=new jt.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 Wt.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, J.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, J.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==r.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==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(e,t,n,i){if(e===null)return (0, J.throwNullException)("prevText");if(t===null)return (0, J.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
27
- `;if(n==i&&e.length==t.length&&a)return r.OutputStateChange.NoChange;if(!a)return r.OutputStateChange.NewlineRemoved;if(i>n)return r.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return r.OutputStateChange.ExtendedBeyondNewline}return r.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new jt.StringBuilder;for(;this.canContinue;)e.Append(this.Continue());return e.toString()}ContentAtPath(e){return this.mainContentContainer.ContentAtPath(e)}KnotContainerWithName(e){let t=this.mainContentContainer.namedContent.get(e);return t instanceof Ce.Container?t:null}PointerAtPath(e){if(e.length==0)return At.Pointer.Null;let t=new At.Pointer,n=e.length,i=null;return e.lastComponent===null?(0, J.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(n=e.length-1,i=this.mainContentContainer.ContentAtPath(e,void 0,n),t.container=i.container,t.index=e.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(e),t.container=i.container,t.index=-1),i.obj==null||i.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+i.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, J.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let e=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,e}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let e=true,t=this.state.currentPointer.copy();if(t.isNull)return;let n=(0, R.asOrNull)(t.Resolve(),Ce.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)t=At.Pointer.StartOf(n),n=(0, R.asOrNull)(t.Resolve(),Ce.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=t.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, R.asOrNull)(i,Pg.ChoicePoint);if(s){let u=this.ProcessChoice(s);u&&this.state.generatedChoices.push(u),i=null,e=false;}if(i instanceof Ce.Container&&(e=false),e){let u=(0, R.asOrNull)(i,F.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new F.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, R.asOrNull)(i,k.ControlCommand);o&&o.commandType==k.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let s=e.Resolve(),o=(0, R.asOrNull)(s,Ce.Container)||(0, R.asOrNull)(e.container,Ce.Container);for(;o;)this._prevContainers.push(o),o=(0, R.asOrNull)(o.parent,Ce.Container);}let n=t.Resolve();if(n==null)return;let i=(0, R.asOrNull)(n.parent,Ce.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, R.asOrNull)(i.parent,Ce.Container);}}PopChoiceStringAndTags(e){let t=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);for(;this.state.evaluationStack.length>0&&(0, R.asOrNull)(this.state.PeekEvaluationStack(),Fs.Tag)!=null;){let n=(0, R.asOrNull)(this.state.PopEvaluationStack(),Fs.Tag);n&&e.push(n.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let n="",i="",a=[];if(e.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new Fg.Choice;return s.targetPath=e.pathOnChoice,s.sourcePath=e.path.toString(),s.isInvisibleDefault=e.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof F.Value){let n=e;if(n instanceof F.DivertTargetValue){let i=n;return this.Error("Shouldn't use a divert target (to "+i.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof ec.Divert){let t=e;if(t.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(t.hasVariableTarget){let n=t.variableDivertName,i=this.state.variablesState.GetVariableWithName(n);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(i instanceof F.DivertTargetValue)){let s=(0, R.asOrNull)(i,F.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";s instanceof F.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, R.asOrThrows)(i,F.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),true;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),true}else if(e instanceof k.ControlCommand){let t=e;switch(t.commandType){case k.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case k.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case k.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let C=this.state.PopEvaluationStack();if(!(C instanceof ii.Void)){let E=new F.StringValue(C.toString());this.state.PushToOutputStream(E);}}break;case k.ControlCommand.CommandType.NoOp:break;case k.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case k.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case k.ControlCommand.CommandType.PopFunction:case k.ControlCommand.CommandType.PopTunnel:let n=t.commandType==k.ControlCommand.CommandType.PopFunction?Me.PushPopType.Function:Me.PushPopType.Tunnel,i=null;if(n==Me.PushPopType.Tunnel){let C=this.state.PopEvaluationStack();i=(0, R.asOrNull)(C,F.DivertTargetValue),i===null&&this.Assert(C instanceof ii.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let C=new Map;C.set(Me.PushPopType.Function,"function return statement (~ return)"),C.set(Me.PushPopType.Tunnel,"tunnel onwards statement (->->)");let E=C.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(E="end of flow (-> END or choice)");let w="Found "+C.get(n)+", when expected "+E;this.Error(w);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case k.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(t),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case k.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case k.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let C=[],E=0;for(let N=this.state.outputStream.length-1;N>=0;--N){let Z=this.state.outputStream[N];E++;let ve=(0, R.asOrNull)(Z,k.ControlCommand);if(ve!=null){if(ve.commandType==k.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}Z instanceof F.StringValue&&C.push(Z);}this.state.PopFromOutputStream(E);let w=new jt.StringBuilder;for(let N of C.reverse())w.Append(N.toString());let P=new Fs.Tag(this.state.CleanOutputWhitespace(w.toString()));this.state.PushEvaluationStack(P);}else this.state.PushToOutputStream(t);break}case k.ControlCommand.CommandType.EndString:{let C=[],E=[],w=0;for(let N=this.state.outputStream.length-1;N>=0;--N){let Z=this.state.outputStream[N];w++;let ve=(0, R.asOrNull)(Z,k.ControlCommand);if(ve&&ve.commandType==k.ControlCommand.CommandType.BeginString)break;Z instanceof Fs.Tag&&E.push(Z),Z instanceof F.StringValue&&C.push(Z);}this.state.PopFromOutputStream(w);for(let N of E)this.state.PushToOutputStream(N);C=C.reverse();let P=new jt.StringBuilder;for(let N of C)P.Append(N.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new F.StringValue(P.toString()));break}case k.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new F.IntValue(a));break;case k.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new F.IntValue(this.state.currentTurnIndex+1));break;case k.ControlCommand.CommandType.TurnsSince:case k.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof F.DivertTargetValue)){let C="";s instanceof F.IntValue&&(C=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+C);break}let o=(0, R.asOrThrows)(s,F.DivertTargetValue),u=(0, R.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,Ce.Container),l;u!=null?t.commandType==k.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(t.commandType==k.ControlCommand.CommandType.TurnsSince?l=-1:l=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new F.IntValue(l));break;case k.ControlCommand.CommandType.Random:{let C=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),E=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(E==null||!(E instanceof F.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(C==null||!(C instanceof F.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(C.value===null)return (0, J.throwNullException)("maxInt.value");if(E.value===null)return (0, J.throwNullException)("minInt.value");let w=C.value-E.value+1;(!isFinite(w)||w>Number.MAX_SAFE_INTEGER)&&(w=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),w<=0&&this.Error("RANDOM was called with minimum as "+E.value+" and maximum as "+C.value+". The maximum must be larger");let P=this.state.storySeed+this.state.previousRandom,Z=new Dl.PRNG(P).next(),ve=Z%w+E.value;this.state.PushEvaluationStack(new F.IntValue(ve)),this.state.previousRandom=Z;break}case k.ControlCommand.CommandType.SeedRandom:let h=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(h==null||!(h instanceof F.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, J.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new ii.Void);break;case k.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new F.IntValue(c));break;case k.ControlCommand.CommandType.SequenceShuffleIndex:let d=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new F.IntValue(d));break;case k.ControlCommand.CommandType.StartThread:break;case k.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=At.Pointer.Null);break;case k.ControlCommand.CommandType.End:this.state.ForceEnd();break;case k.ControlCommand.CommandType.ListFromInt:let f=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue),m=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.StringValue);if(f===null)throw new Wt.StoryException("Passed non-integer when creating a list element from a numerical value.");let g=null;if(this.listDefinitions===null)return (0, J.throwNullException)("this.listDefinitions");let b=this.listDefinitions.TryListGetDefinition(m.value,null);if(b.exists){if(f.value===null)return (0, J.throwNullException)("minInt.value");let C=b.result.TryGetItemWithValue(f.value,ri.InkListItem.Null);C.exists&&(g=new F.ListValue(C.result,f.value));}else throw new Wt.StoryException("Failed to find LIST called "+m.value);g==null&&(g=new F.ListValue),this.state.PushEvaluationStack(g);break;case k.ControlCommand.CommandType.ListRange:let S=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.Value),y=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.Value),p=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.ListValue);if(p===null||y===null||S===null)throw new Wt.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(p.value===null)return (0, J.throwNullException)("targetList.value");let D=p.value.ListWithSubRange(y.valueObject,S.valueObject);this.state.PushEvaluationStack(new F.ListValue(D));break;case k.ControlCommand.CommandType.ListRandom:{let C=this.state.PopEvaluationStack();if(C===null)throw new Wt.StoryException("Expected list for LIST_RANDOM");let E=C.value,w=null;if(E===null)throw (0, J.throwNullException)("list");if(E.Count==0)w=new ri.InkList;else {let P=this.state.storySeed+this.state.previousRandom,Z=new Dl.PRNG(P).next(),ve=Z%E.Count,Gt=E.entries();for(let Ll=0;Ll<=ve-1;Ll++)Gt.next();let Rl=Gt.next().value,ci={Key:ri.InkListItem.fromSerializedKey(Rl[0]),Value:Rl[1]};if(ci.Key.originName===null)return (0, J.throwNullException)("randomItem.Key.originName");w=new ri.InkList(ci.Key.originName,this),w.Add(ci.Key,ci.Value),this.state.previousRandom=Z;}this.state.PushEvaluationStack(new F.ListValue(w));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof Ng.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),true}else if(e instanceof Ig.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);n=new F.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(t.name),n==null&&(this.Warning("Variable not found: '"+t.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),n=new F.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(e instanceof Vg.NativeFunctionCall){let t=e,n=this.state.PopEvaluationStack(t.numberOfParameters),i=t.Call(n);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(e,t=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,n),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==Me.PushPopType.Function){let i="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(i="("+a.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace:
28
- `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new El.Path(e));}IfAsyncWeCant(e){if(this._asyncContinueActive)throw new Error("Can't "+e+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(e,t=true){this.state.SetChosenPath(e,t),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(e){e=e;let t=this.currentChoices;this.Assert(e>=0&&e<t.length,"choice out of range");let n=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, J.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, J.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(e,t),this.IfAsyncWeCant("evaluate a function"),e==null)throw new Error("Function is null");if(e==""||e.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(e);if(i==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,t);let s=new jt.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let u=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,u),n?{returned:u,output:o}:u}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(Me.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, J.throwNullException)("funcName");let n=this._externals.get(e),i=null,a=typeof n<"u";if(a&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+e+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+e+"()"),a&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(e),this.Assert(i!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(Me.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=At.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let l=0;l<t;++l){let c=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.Value).valueObject;s.push(c);}s.reverse();let o=n.function(s),u=null;o!=null?(u=F.Value.Create(o),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof o)):u=new ii.Void,this.state.PushEvaluationStack(u);}BindExternalFunctionGeneral(e,t,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(e),"Function '"+e+"' has already been bound."),this._externals.set(e,{function:t,lookAheadSafe:n});}TryCoerce(e){return e}BindExternalFunction(e,t,n=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,i=>{this.Assert(i.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=i.length;s<o;s++)a[s]=this.TryCoerce(i[s]);return t.apply(null,a)},n);}UnbindExternalFunction(e){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(e),"Function '"+e+"' has not been bound."),this._externals.delete(e);}ValidateExternalBindings(){let e=null,t=null,n=arguments[1]||new Set;if(arguments[0]instanceof Ce.Container&&(e=arguments[0]),arguments[0]instanceof vl.InkObject&&(t=arguments[0]),e===null&&t===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(e!=null){for(let i of e.content){let a=i;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(i,n);}for(let[,i]of e.namedContent)this.ValidateExternalBindings((0, R.asOrNull)(i,vl.InkObject),n);}else if(t!=null){let i=(0, R.asOrNull)(t,ec.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, J.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.add(a);}}}ObserveVariable(e,t){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(e))throw new Error("Cannot observe variable '"+e+"' because it wasn't declared in the ink story.");this._variableObservers.has(e)?this._variableObservers.get(e).push(t):this._variableObservers.set(e,[t]);}ObserveVariables(e,t){for(let n=0,i=e.length;n<i;n++)this.ObserveVariable(e[n],t[n]);}RemoveVariableObserver(e,t){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(t!=null){if(this._variableObservers.has(t))if(e!=null){let n=this._variableObservers.get(t);n!=null&&(n.splice(n.indexOf(e),1),n.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let n=this._variableObservers.keys();for(let i of n){let a=this._variableObservers.get(i);a!=null&&(a.splice(a.indexOf(e),1),a.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(e,t){if(this._variableObservers===null)return;let n=this._variableObservers.get(e);if(typeof n<"u"){if(!(t instanceof F.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, R.asOrThrows)(t,F.Value);for(let a of n)a(e,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new El.Path(e),n=this.ContentAtPath(t).container;if(n===null)return (0, J.throwNullException)("flowContainer");for(;;){let s=n.content[0];if(s instanceof Ce.Container)n=s;else break}let i=false,a=null;for(let s of n.content){let o=(0, R.asOrNull)(s,k.ControlCommand);if(o!=null)o.commandType==k.ControlCommand.CommandType.BeginTag?i=true:o.commandType==k.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, R.asOrNull)(s,F.StringValue);u!==null?(a===null&&(a=[]),u.value!==null&&a.push(u.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let e=new jt.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new jt.StringBuilder;return e.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=At.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(Me.PushPopType.Function)?(this.state.PopCallStack(Me.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new ii.Void),t=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),t=true):this.state.TryExitFunctionEvaluationFromGame(),t&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let e=true,t=this.state.callStack.currentElement.currentPointer.copy();if(t.index++,t.container===null)return (0, J.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let n=(0, R.asOrNull)(t.container.parent,Ce.Container);if(!(n instanceof Ce.Container))break;let i=n.content.indexOf(t.container);if(i==-1)break;if(t=new At.Pointer(n,i),t.index++,e=true,t.container===null)return (0, J.throwNullException)("pointer.container")}return e||(t=At.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(i=>i.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let n=t[0];return n.targetPath===null?(0, J.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, J.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 e=(0, R.asOrNull)(this.state.PopEvaluationStack(),F.IntValue);if(!(e instanceof F.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, J.throwNullException)("seqContainer");if(e.value===null)return (0, J.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, R.asOrThrows)(this.state.PopEvaluationStack(),F.IntValue).value;if(a===null)return (0, J.throwNullException)("seqCount");let s=a/n,o=a%n,u=t.path.toString(),l=0;for(let f=0,m=u.length;f<m;f++)l+=u.charCodeAt(f)||0;let h=l+s+this.state.storySeed,c=new Dl.PRNG(Math.floor(h)),d=[];for(let f=0;f<n;++f)d.push(f);for(let f=0;f<=o;++f){let m=c.next()%d.length,g=d[m];if(d.splice(m,1),f==o)return g}throw new Error("Should never reach here")}Error(e,t=false){let n=new Wt.StoryException(e);throw n.useEndLineNumber=t,n}Warning(e){this.AddError(e,true);}AddError(e,t=false,n=false){let i=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(i!=null){let s=n?i.endLineNumber:i.startLineNumber;e="RUNTIME "+a+": '"+i.fileName+"' line "+s+": "+e;}else this.state.currentPointer.isNull?e="RUNTIME "+a+": "+e:e="RUNTIME "+a+": ("+this.state.currentPointer+"): "+e;this.state.AddError(e,t),t||this.state.ForceEnd();}Assert(e,t=null){if(e==false)throw t==null&&(t="Story assert"),new Error(t+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let e,t=this.state.currentPointer;if(!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(t=this.state.callStack.elements[n].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.outputStream.length-1;n>=0;--n)if(e=this.state.outputStream[n].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};qt.Story=mn;mn.inkVersionCurrent=21;(function(r){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(r.OutputStateChange||(r.OutputStateChange={}));})(mn||(qt.Story=mn={}));});var rc=x(Rs=>{Object.defineProperty(Rs,"__esModule",{value:true});Rs.Story=void 0;var Bg=Oi(),Wg=fr(),Ns=ie(),Is=me(),si=Ut(),Vs=et(),ic=an(),jg=$o(),qg=$r(),Mg=Xo(),Gg=Qn(),gn=ht(),$g=St(),Jg=yt(),ai=H(),Hg=Gn(),zg=$n(),Ug=Rt(),ks=class r extends Vs.FlowBase{get flowLevel(){return ic.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(e,t=false){super(null,e,null,false,t),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(Wg.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let d=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(d,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(qg.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 Ns.Container;o.AddContent(Is.ControlCommand.EvalStart());let u=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),o.AddContent(c.listDefinition.runtimeObject),u.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(o);}let d=new Jg.VariableAssignment(h,true);d.isGlobal=true,o.AddContent(d);}o.AddContent(Is.ControlCommand.EvalEnd()),o.AddContent(Is.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(Is.ControlCommand.Done());let l=new Gg.Story(s,u);return this.runtimeObject=l,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(l.ResetState(),l)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,a=null)=>{let s=null;if(n)return (s=this._listDefs.get(n))?s.ItemNamed(i):null;{let o=null,u=null;for(let[,l]of this._listDefs.entries()){let h=l.ItemNamed(i);h&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${u.identifier} and ${l.identifier}`,a,false):(o=h,u=l));}return o}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let a of n.content){let s=(0, ai.asOrNull)(a,Ns.Container);s&&i.add(s);}if(n.namedContent)for(let[,a]of n.namedContent){let s=(0, ai.asOrNull)(a,Ns.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, ai.asOrNull)(n.parent,Ns.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?si.ErrorType.Warning:si.ErrorType.Error,o="";if(i instanceof Bg.AuthorWarning?(o+="TODO: ",s=si.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===si.ErrorType.Error,this._hadWarning=s===si.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 u=s||n.typeName;if(r.IsReservedKeyword(i?.name)){n.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a reserved keyword`);return}else if(zg.FunctionCall.IsBuiltIn(i?.name||"")){n.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a built in function`);return}let l=this.ContentWithNameAtLevel(i?.name||"",ic.FlowLevel.Knot),h=(0, ai.asOrNull)(l,Vs.FlowBase);if(h&&(h!==n||a===gn.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,u);return}if(a<gn.SymbolType.List)return;for(let[m,g]of this._listDefs)if(i?.name===m&&n!==g&&g.variableAssignment!==n&&this.NameConflictError(n,i?.name,g,u),!(n instanceof Mg.ListElementDefinition))for(let b of g.itemDefinitions)i?.name===b.name&&this.NameConflictError(n,i?.name||"",b,u);if(a<=gn.SymbolType.Var)return;let c=i?.name&&this.variableDeclarations.get(i?.name)||null;if(c&&c!==n&&c.isGlobalDeclaration&&c.listDefinition==null&&this.NameConflictError(n,i?.name||"",c,u),a<gn.SymbolType.SubFlowAndWeave)return;let f=new Ug.Path(i).ResolveFromContext(n);if(f&&f!==n){this.NameConflictError(n,i?.name||"",f,u);return}if(!(a<gn.SymbolType.Arg)&&a!==gn.SymbolType.Arg){let m=(0, ai.asOrNull)(n,Vs.FlowBase);if(m||(m=(0, Hg.ClosestFlowBase)(n)),m&&m.hasParameters&&m.args){for(let g of m.args)if(((o=g.identifier)===null||o===void 0?void 0:o.name)===i?.name){n.Error(`${u} '${i}': name has already been used for a argument to ${m.identifier} on ${m.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let n of e)if(n instanceof jg.IncludedFile){let i=n,a=e.indexOf(n);if(e.splice(a,1),i.includedStory){let s=[],o=i.includedStory;if(o.content!=null){for(let u of o.content)u instanceof Vs.FlowBase?t.push(u):s.push(u);s.push(new $g.Text(`
29
- `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};Rs.Story=ks;ks.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 ac=x(Ls=>{Object.defineProperty(Ls,"__esModule",{value:true});Ls.StringExpression=void 0;var sc=me(),Kg=Le(),Xg=St(),Yg=H(),bl=class r extends Kg.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof Xg.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(sc.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(sc.ControlCommand.EndString());},this.toString=()=>{let t="";for(let n of this.content)t+=n;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, Yg.asOrNull)(e,r);if(t===null||!this.isSingleString||!t.isSingleString)return false;let n=this.toString(),i=t.toString();return n===i}};Ls.StringExpression=bl;});var lc=x(Cn=>{Object.defineProperty(Cn,"__esModule",{value:true});Cn.LegacyTag=Cn.Tag=void 0;var Qg=Q(),oc=me(),Al=class extends Qg.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?oc.ControlCommand.BeginTag():oc.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};Cn.Tag=Al;var Zg=Wo(),xl=class extends Zg.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};Cn.LegacyTag=xl;});var uc=x(Bs=>{Object.defineProperty(Bs,"__esModule",{value:true});Bs.DefaultFileHandler=void 0;var wl=class{constructor(e){this.rootPath=e,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};Bs.DefaultFileHandler=wl;});var Pl=x(Ms=>{Object.defineProperty(Ms,"__esModule",{value:true});Ms.InkParser=void 0;var eC=Nu(),tC=Oi(),nC=Ia(),He=Ju(),de=Bn(),iC=sn(),rC=eh(),sC=cr(),oi=fo(),Fe=xr(),aC=fr(),Ws=Dh(),oC=bh(),Mt=un(),_l=ln(),lC=Le(),uC=Ah(),hc=xh(),js=$n(),hC=Mn(),cC=wh(),dC=rs(),qs=Th(),cc=$o(),pC=Oh(),fC=zo(),dc=Fh(),mC=$r(),gC=Xo(),CC=uo(),pc=Q(),yC=Rt(),fc=eo(),mc=bo(),ce=So(),be=Yo(),vC=Zo(),gc=rc(),li=ac(),ct=$a(),yn=lc(),dt=St(),Cc=xo(),Tl=Fo(),Ol=cn(),SC=Fa(),xt=H(),ui=Dr(),vn=Ji(),yc=Ut(),EC=uc(),U=class r extends ct.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,n=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel(be.StatementLevel.Top);return new gc.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let u=this.Parse(s);if(u===null)return null;let l=[];l.push(u);do{let h=this.BeginRule();if(o()===null){this.FailRule(h);break}let d=this.Parse(s);if(d===null){this.FailRule(h);break}this.SucceedRule(h),l.push(d);}while(true);return l},this.CreateDebugMetadata=(s,o)=>{let u=new oC.DebugMetadata;return u.startLineNumber=(s?.lineIndex||0)+1,u.endLineNumber=o.lineIndex+1,u.startCharacterNumber=(s?.characterInLineIndex||0)+1,u.endCharacterNumber=o.characterInLineIndex+1,u.fileName=this._filename,u},this.RuleDidSucceed=(s,o,u)=>{let l=(0, xt.asOrNull)(s,pc.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(o,u));let h=Array.isArray(s)?s:null;if(h!==null)for(let d of h)(0, xt.asOrNull)(d,pc.ParsedObject)&&(d.hasOwnDebugMetadata||(d.debugMetadata=this.CreateDebugMetadata(o,u)));let c=(0, xt.asOrNull)(s,ui.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(o,u));},this.OnStringParserError=(s,o,u=0,l=false)=>{let c=l?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${u+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,l?yc.ErrorType.Warning:yc.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 tC.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=r.ListAllCharacterRanges();for(let u of o)s.AddCharacters(u.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 u=this.Parse(this.BracketedName);this.Whitespace(),u!=null&&this.Newline();let l=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let h=null,c=this.Parse(this.MixedTextAndLogic);c&&(h=new Fe.ContentList(c));let d=null,f=null,m=this.ParseString("[")!==null;if(m){this.EndTagIfNecessary(h);let y=this.Parse(this.MixedTextAndLogic);y!==null&&(d=new Fe.ContentList(y)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(d);let p=this.Parse(this.MixedTextAndLogic);p!==null&&(f=new Fe.ContentList(p));}this.Whitespace(),this.EndTagIfNecessary(f??h);let g=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let b=!h&&!f&&!d;if(b&&g===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&m&&!d&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),f||(f=new Fe.ContentList),this.EndTagIfNecessary(f),g!==null)for(let y of g){let p=(0, xt.asOrNull)(y,Mt.Divert);p&&p.isEmpty||f.AddContent(y);}f.AddContent(new dt.Text(`
31
- `));let S=new iC.Choice(h,d,f);return u&&(S.identifier=u),S.indentationDepth=o.length,S.hasWeaveStyleInlineBrackets=m,S.condition=l,S.onceOnly=s,S.isInvisibleDefault=b,S},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new CC.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),ct.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),u=this.Parse(this.BracketedName),l=new hC.Gather(u,o);return this.Newline(),l},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),d=this.Parse(()=>this.InnerConditionalContent(c));return d===null?null:d}let o,u=s!==null,l=this.Parse(this.Newline)===null;if(l&&!u)return null;if(l)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let c=this.StatementsAtLevel(be.StatementLevel.InnerBlock);if(c!==null){o=[new oi.ConditionalSingleBranch(c)];let f=this.Parse(this.SingleMultilineCondition);f&&(f.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",f),f.isElse=true),o.push(f));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let c=new oi.ConditionalSingleBranch(null);c.isTrueBranch=true,o.unshift(c);}if(s){let c=false;for(let d=0;d<o.length;++d){let f=o[d],m=d===o.length-1;f.ownExpression?(f.matchingEquality=true,c=true):c&&m?(f.matchingEquality=true,f.isElse=true):!m&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",f):d===0?f.isTrueBranch=true:f.isElse=true;}}else {for(let c=0;c<o.length;++c){let d=o[c],f=c===o.length-1;if(d.ownExpression===null)if(f)d.isElse=true;else if(d.isElse){let m=o[o.length-1];m.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",m):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",d);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",d);}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=l;return new sC.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 u=new oi.ConditionalSingleBranch(s[0]);if(u.isTrueBranch=true,o.push(u),s.length>1){let l=new oi.ConditionalSingleBranch(s[1]);l.isElse=true,o.push(l);}}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 u=this.StatementsAtLevel(be.StatementLevel.InnerBlock);s===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new dt.Text("")]),this.MultilineWhitespace();let l=new oi.ConditionalSingleBranch(u);return l.ownExpression=s,l.isElse=o,l},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:ct.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let u=s.length-1,l=s[u];if(l instanceof dt.Text){let h=l;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),o?h.text+=" ":h.text.length===0&&(s.splice(u,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 Mt.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof yn.Tag&&s[0].isStart||s.push(new dt.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 u=this.Parse(this.MultiDivert);u!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...u));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),u=this.ParseString("\\")!==null;if(u||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),u){let l=this.ParseSingleCharacter();s+=l;}}else break}while(true);return s!==null?new dt.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new de.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new de.CharacterSet(`{}|
33
- \r\\#`),this._notTextEndCharactersChoice=new de.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new de.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 u=this.ParseUntil(s,this._nonTextPauseCharacters,o);return u!==null?u:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let u=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!u)return null;s=[],this.EndTagIfNecessary(s);for(let l=0;l<u.length;++l)if(l%2===0){if(u[l]==="->->"){l===0||l===u.length-1||l===u.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let d=new Cc.TunnelOnwards;if(l<u.length-1){let f=(0, xt.asOrNull)(u[l+1],Mt.Divert);d.divertAfter=f;}s.push(d);break}}else {let c=u[l];l<u.length-1&&(c.isTunnel=true),s.push(c);}if(s.length===0&&u.length===1){let l=new Mt.Divert(null);l.isEmpty=true,s.push(l),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 Mt.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 u=new yC.Path(s);return new Mt.Divert(u,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof Cc.TunnelOnwards)return null;let u=s[0];return u.isTunnel?null:u},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 u=this.ParseString("+")!==null,l=this.ParseString("-")!==null;if(u&&l&&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 u||l?new qs.IncDecExpression(o,h,u):new Tl.VariableAssignment({variableIdentifier:o,assignedExpression:h,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof qs.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 fc.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let u=this.BeginRule(),l=this.ParseInfixOperator();if(l!==null&&l.precedence>s){let h=`right side of '${l.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(o,l),h);if(c===null)return this.FailRule(u),null;o=this.SucceedRule(u,c);continue}this.FailRule(u);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 u=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(u===null&&o!==null&&(u=this.ExpressionUnary()),u===null)return null;o!==null&&(u=SC.UnaryExpression.WithInner(u,o)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let h=l==="++";if(!(u instanceof Ol.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let c=u;u=new qs.IncDecExpression(c.identifier,h);}}return u},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 _l.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new vn.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new vn.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 dt.Text("")]:o.find(u=>u instanceof Mt.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new li.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new vn.NumberExpression(true,"bool"):s==="false"?new vn.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 js.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||gc.Story.IsReservedKeyword(s[0].name)?null:new Ol.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 u=this.Parse(()=>this.Expression(o.precedence));return u?new nC.BinaryExpression(s,u,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 dc.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let u=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${u?.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,u=false)=>{let l=new pC.InfixOperator(s,o,u);this._binaryOperators.push(l),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(`
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=t.length;if(n!=-1){if(n>0){let h=new he.StringValue(t.substring(0,n));o.push(h);}o.push(new he.StringValue(`
25
+ `)),l=i+1;}if(a!=-1&&(u=s),u>l){let h=t.substring(l,u);o.push(new he.StringValue(h));}if(a!=-1&&s>i&&(o.push(new he.StringValue(`
26
+ `)),a<t.length-1)){let h=t.length-a-1,c=new he.StringValue(t.substring(a+1,a+1+h));o.push(c);}return o}PushToOutputStreamIndividual(e){let t=(0, ae.asOrNull)(e,fl.Glue),n=(0, ae.asOrNull)(e,he.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let a=-1,s=this.callStack.currentElement;s.type==bt.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 be.ControlCommand?h:null;if((h instanceof fl.Glue?h:null)!=null){o=u;break}else if(c!=null&&c.commandType==be.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==bt.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, qe.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let n=this.outputStream[t],i=(0, ae.asOrNull)(n,be.ControlCommand),a=(0, ae.asOrNull)(n,he.StringValue);if(i!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t<this.outputStream.length;)(0, ae.asOrNull)(this.outputStream[t],he.StringValue)?this.outputStream.splice(t,1):t++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let e=this.outputStream.length-1;e>=0;e--){let t=this.outputStream[e];if(t instanceof fl.Glue)this.outputStream.splice(e,1);else if(t instanceof be.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof be.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof he.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof he.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, ae.asOrNull)(this.outputStream[e],be.ControlCommand);if(t instanceof be.ControlCommand&&t.commandType==be.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, ae.asOrNull)(e,he.ListValue);if(t){let n=t.value;if(n===null)return (0, qe.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, qe.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, qe.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, qe.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, ae.nullIfUndefined)(t)}else {if(e>this.evaluationStack.length)throw new Error("trying to pop too many objects");let t=this.evaluationStack.splice(this.evaluationStack.length-e,e);return (0, ae.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=fn.Pointer.Null,this.previousPointer=fn.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){_g.Debug.Assert(this.callStack.currentElement.type==bt.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let n=this.outputStream[t],i=(0, ae.asOrNull)(n,he.StringValue),a=(0, ae.asOrNull)(n,be.ControlCommand);if(i!=null){if(a)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==bt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(e);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(bt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=fn.Pointer.StartOf(e),this.PassArgumentsToEvaluationStack(t);}PassArgumentsToEvaluationStack(e){if(e!==null)for(let t=0;t<e.length;t++){if(!(typeof e[t]=="number"||typeof e[t]=="string"||typeof e[t]=="boolean"||e[t]instanceof Tg.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, ae.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(he.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==bt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=fn.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=bt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let e=this.callStack.currentElement.evaluationStackHeightWhenPushed,t=null;for(;this.evaluationStack.length>e;){let n=this.PopEvaluationStack();t===null&&(t=n);}if(this.PopCallStack(bt.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof xg.Void)return null;let n=(0, ae.asOrThrows)(t,he.Value);return n.valueType==he.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.valueObject}return null}AddError(e,t){t?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(e)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(e));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};_s.StoryState=gl;});var Qh=x(Os=>{Object.defineProperty(Os,"__esModule",{value:true});Os.Stopwatch=void 0;var Cl=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;}};Os.Stopwatch=Cl;});var ec=x(Ps=>{Object.defineProperty(Ps,"__esModule",{value:true});Ps.ErrorType=void 0;var Zh;(function(r){r[r.Author=0]="Author",r[r.Warning=1]="Warning",r[r.Error=2]="Error";})(Zh||(Ps.ErrorType=Zh={}));});var Qn=x(Mt=>{Object.defineProperty(Mt,"__esModule",{value:true});Mt.Story=Mt.InkList=void 0;var Ce=re(),yl=Pe(),vl=dn(),Fg=Yh(),k=me(),Me=kt(),Ng=Xi(),Ig=tl(),tc=et(),N=ee(),Sl=Oe(),ii=Vt(),Ts=ds(),Vg=vt(),kg=hn(),Rg=Ze(),jt=Pn(),El=hl(),qt=Nt(),Lg=il(),Bg=Qh(),wt=jn(),ri=Fe(),R=z(),H=fe(),nc=pl(),ic=ec(),Wg=Fe();Object.defineProperty(Mt,"InkList",{enumerable:true,get:function(){return Wg.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var mn=class r extends yl.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, H.throwNullException)("this._state");for(let t of this._state.currentChoices)t.isInvisibleDefault||(t.index=e.length,e.push(t));return e}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=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 e,t=null,n=null;if(arguments[0]instanceof Ce.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let i=arguments[0];n=nc.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new Lg.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let i=n,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let 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=vl.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, R.asOrThrows)(vl.JsonSerialisation.JTokenToRuntimeObject(o),Ce.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new nc.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",r.inkVersionCurrent),e.WriteProperty("root",n=>vl.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[i,a]of n.items){let s=ri.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(s.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.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, H.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, H.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new Sl.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=e;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(e){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+e);this.state.SwitchFlow_Internal(e);}RemoveFlow(e){this.state.RemoveFlow_Internal(e);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(e){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(e);}ContinueInternal(e=0){this._profiler!=null&&this._profiler.PreContinue();let t=e>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!t&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=t,!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 Bg.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof jt.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(Me.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(Me.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,ic.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,ic.ErrorType.Warning);this.ResetErrors();}else {let s=new qt.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 jt.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, H.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, H.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==r.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==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(e,t,n,i){if(e===null)return (0, H.throwNullException)("prevText");if(t===null)return (0, H.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
27
+ `;if(n==i&&e.length==t.length&&a)return r.OutputStateChange.NoChange;if(!a)return r.OutputStateChange.NewlineRemoved;if(i>n)return r.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return r.OutputStateChange.ExtendedBeyondNewline}return r.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new qt.StringBuilder;for(;this.canContinue;)e.Append(this.Continue());return e.toString()}ContentAtPath(e){return this.mainContentContainer.ContentAtPath(e)}KnotContainerWithName(e){let t=this.mainContentContainer.namedContent.get(e);return t instanceof Ce.Container?t:null}PointerAtPath(e){if(e.length==0)return wt.Pointer.Null;let t=new wt.Pointer,n=e.length,i=null;return e.lastComponent===null?(0, H.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(n=e.length-1,i=this.mainContentContainer.ContentAtPath(e,void 0,n),t.container=i.container,t.index=e.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(e),t.container=i.container,t.index=-1),i.obj==null||i.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+i.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, H.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let e=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,e}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let e=true,t=this.state.currentPointer.copy();if(t.isNull)return;let n=(0, R.asOrNull)(t.Resolve(),Ce.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)t=wt.Pointer.StartOf(n),n=(0, R.asOrNull)(t.Resolve(),Ce.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=t.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, R.asOrNull)(i,Ng.ChoicePoint);if(s){let l=this.ProcessChoice(s);l&&this.state.generatedChoices.push(l),i=null,e=false;}if(i instanceof Ce.Container&&(e=false),e){let l=(0, R.asOrNull)(i,N.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);i=new N.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, R.asOrNull)(i,k.ControlCommand);o&&o.commandType==k.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let s=e.Resolve(),o=(0, R.asOrNull)(s,Ce.Container)||(0, R.asOrNull)(e.container,Ce.Container);for(;o;)this._prevContainers.push(o),o=(0, R.asOrNull)(o.parent,Ce.Container);}let n=t.Resolve();if(n==null)return;let i=(0, R.asOrNull)(n.parent,Ce.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, R.asOrNull)(i.parent,Ce.Container);}}PopChoiceStringAndTags(e){let t=(0, R.asOrThrows)(this.state.PopEvaluationStack(),N.StringValue);for(;this.state.evaluationStack.length>0&&(0, R.asOrNull)(this.state.PeekEvaluationStack(),Ts.Tag)!=null;){let n=(0, R.asOrNull)(this.state.PopEvaluationStack(),Ts.Tag);n&&e.push(n.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let n="",i="",a=[];if(e.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new Ig.Choice;return s.targetPath=e.pathOnChoice,s.sourcePath=e.path.toString(),s.isInvisibleDefault=e.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof N.Value){let n=e;if(n instanceof N.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 t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof tc.Divert){let t=e;if(t.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(t.hasVariableTarget){let n=t.variableDivertName,i=this.state.variablesState.GetVariableWithName(n);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(i instanceof N.DivertTargetValue)){let s=(0, R.asOrNull)(i,N.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";s instanceof N.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, R.asOrThrows)(i,N.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),true;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),true}else if(e instanceof k.ControlCommand){let t=e;switch(t.commandType){case k.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case k.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case k.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let v=this.state.PopEvaluationStack();if(!(v instanceof ii.Void)){let E=new N.StringValue(v.toString());this.state.PushToOutputStream(E);}}break;case k.ControlCommand.CommandType.NoOp:break;case k.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case k.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case k.ControlCommand.CommandType.PopFunction:case k.ControlCommand.CommandType.PopTunnel:let n=t.commandType==k.ControlCommand.CommandType.PopFunction?Me.PushPopType.Function:Me.PushPopType.Tunnel,i=null;if(n==Me.PushPopType.Tunnel){let v=this.state.PopEvaluationStack();i=(0, R.asOrNull)(v,N.DivertTargetValue),i===null&&this.Assert(v instanceof ii.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 v=new Map;v.set(Me.PushPopType.Function,"function return statement (~ return)"),v.set(Me.PushPopType.Tunnel,"tunnel onwards statement (->->)");let E=v.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(E="end of flow (-> END or choice)");let w="Found "+v.get(n)+", when expected "+E;this.Error(w);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case k.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(t),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case k.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case k.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let v=[],E=0;for(let P=this.state.outputStream.length-1;P>=0;--P){let L=this.state.outputStream[P];E++;let ve=(0, R.asOrNull)(L,k.ControlCommand);if(ve!=null){if(ve.commandType==k.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}L instanceof N.StringValue&&v.push(L);}this.state.PopFromOutputStream(E);let w=new qt.StringBuilder;for(let P of v.reverse())w.Append(P.toString());let T=new Ts.Tag(this.state.CleanOutputWhitespace(w.toString()));this.state.PushEvaluationStack(T);}else this.state.PushToOutputStream(t);break}case k.ControlCommand.CommandType.EndString:{let v=[],E=[],w=0;for(let P=this.state.outputStream.length-1;P>=0;--P){let L=this.state.outputStream[P];w++;let ve=(0, R.asOrNull)(L,k.ControlCommand);if(ve&&ve.commandType==k.ControlCommand.CommandType.BeginString)break;L instanceof Ts.Tag&&E.push(L),L instanceof N.StringValue&&v.push(L);}this.state.PopFromOutputStream(w);for(let P of E)this.state.PushToOutputStream(P);v=v.reverse();let T=new qt.StringBuilder;for(let P of v)T.Append(P.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new N.StringValue(T.toString()));break}case k.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new N.IntValue(a));break;case k.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new N.IntValue(this.state.currentTurnIndex+1));break;case k.ControlCommand.CommandType.TurnsSince:case k.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof N.DivertTargetValue)){let v="";s instanceof N.IntValue&&(v=". 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+v);break}let o=(0, R.asOrThrows)(s,N.DivertTargetValue),l=(0, R.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,Ce.Container),u;l!=null?t.commandType==k.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(t.commandType==k.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new N.IntValue(u));break;case k.ControlCommand.CommandType.Random:{let v=(0, R.asOrNull)(this.state.PopEvaluationStack(),N.IntValue),E=(0, R.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(E==null||!(E instanceof N.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(v==null||!(v instanceof N.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(v.value===null)return (0, H.throwNullException)("maxInt.value");if(E.value===null)return (0, H.throwNullException)("minInt.value");let w=v.value-E.value+1;(!isFinite(w)||w>Number.MAX_SAFE_INTEGER)&&(w=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),w<=0&&this.Error("RANDOM was called with minimum as "+E.value+" and maximum as "+v.value+". The maximum must be larger");let T=this.state.storySeed+this.state.previousRandom,L=new El.PRNG(T).next(),ve=L%w+E.value;this.state.PushEvaluationStack(new N.IntValue(ve)),this.state.previousRandom=L;break}case k.ControlCommand.CommandType.SeedRandom:let h=(0, R.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(h==null||!(h instanceof N.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, H.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new ii.Void);break;case k.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new N.IntValue(c));break;case k.ControlCommand.CommandType.SequenceShuffleIndex:let p=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new N.IntValue(p));break;case k.ControlCommand.CommandType.StartThread:break;case k.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=wt.Pointer.Null);break;case k.ControlCommand.CommandType.End:this.state.ForceEnd();break;case k.ControlCommand.CommandType.ListFromInt:let d=(0, R.asOrNull)(this.state.PopEvaluationStack(),N.IntValue),f=(0, R.asOrThrows)(this.state.PopEvaluationStack(),N.StringValue);if(d===null)throw new jt.StoryException("Passed non-integer when creating a list element from a numerical value.");let g=null;if(this.listDefinitions===null)return (0, H.throwNullException)("this.listDefinitions");let b=this.listDefinitions.TryListGetDefinition(f.value,null);if(b.exists){if(d.value===null)return (0, H.throwNullException)("minInt.value");let v=b.result.TryGetItemWithValue(d.value,ri.InkListItem.Null);v.exists&&(g=new N.ListValue(v.result,d.value));}else throw new jt.StoryException("Failed to find LIST called "+f.value);g==null&&(g=new N.ListValue),this.state.PushEvaluationStack(g);break;case k.ControlCommand.CommandType.ListRange:let D=(0, R.asOrNull)(this.state.PopEvaluationStack(),N.Value),y=(0, R.asOrNull)(this.state.PopEvaluationStack(),N.Value),m=(0, R.asOrNull)(this.state.PopEvaluationStack(),N.ListValue);if(m===null||y===null||D===null)throw new jt.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(m.value===null)return (0, H.throwNullException)("targetList.value");let C=m.value.ListWithSubRange(y.valueObject,D.valueObject);this.state.PushEvaluationStack(new N.ListValue(C));break;case k.ControlCommand.CommandType.ListRandom:{let v=this.state.PopEvaluationStack();if(v===null)throw new jt.StoryException("Expected list for LIST_RANDOM");let E=v.value,w=null;if(E===null)throw (0, H.throwNullException)("list");if(E.Count==0)w=new ri.InkList;else {let T=this.state.storySeed+this.state.previousRandom,L=new El.PRNG(T).next(),ve=L%E.Count,st=E.entries();for(let Rl=0;Rl<=ve-1;Rl++)st.next();let kl=st.next().value,ci={Key:ri.InkListItem.fromSerializedKey(kl[0]),Value:kl[1]};if(ci.Key.originName===null)return (0, H.throwNullException)("randomItem.Key.originName");w=new ri.InkList(ci.Key.originName,this),w.Add(ci.Key,ci.Value),this.state.previousRandom=L;}this.state.PushEvaluationStack(new N.ListValue(w));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof Vg.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),true}else if(e instanceof kg.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);n=new N.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(t.name),n==null&&(this.Warning("Variable not found: '"+t.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),n=new N.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(e instanceof Rg.NativeFunctionCall){let t=e,n=this.state.PopEvaluationStack(t.numberOfParameters),i=t.Call(n);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(e,t=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,n),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==Me.PushPopType.Function){let i="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(i="("+a.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace:
28
+ `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new Sl.Path(e));}IfAsyncWeCant(e){if(this._asyncContinueActive)throw new Error("Can't "+e+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(e,t=true){this.state.SetChosenPath(e,t),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(e){e=e;let t=this.currentChoices;this.Assert(e>=0&&e<t.length,"choice out of range");let n=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, H.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, H.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],n=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(e,t),this.IfAsyncWeCant("evaluate a function"),e==null)throw new Error("Function is null");if(e==""||e.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(e);if(i==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,t);let s=new qt.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(e,t,o,l),n?{returned:l,output:o}:l}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(Me.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, H.throwNullException)("funcName");let n=this._externals.get(e),i=null,a=typeof n<"u";if(a&&!n.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+e+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+e+"()"),a&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(e),this.Assert(i!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(Me.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=wt.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let u=0;u<t;++u){let c=(0, R.asOrThrows)(this.state.PopEvaluationStack(),N.Value).valueObject;s.push(c);}s.reverse();let o=n.function(s),l=null;o!=null?(l=N.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new ii.Void,this.state.PushEvaluationStack(l);}BindExternalFunctionGeneral(e,t,n=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(e),"Function '"+e+"' has already been bound."),this._externals.set(e,{function:t,lookAheadSafe:n});}TryCoerce(e){return e}BindExternalFunction(e,t,n=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,i=>{this.Assert(i.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=i.length;s<o;s++)a[s]=this.TryCoerce(i[s]);return t.apply(null,a)},n);}UnbindExternalFunction(e){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(e),"Function '"+e+"' has not been bound."),this._externals.delete(e);}ValidateExternalBindings(){let e=null,t=null,n=arguments[1]||new Set;if(arguments[0]instanceof Ce.Container&&(e=arguments[0]),arguments[0]instanceof yl.InkObject&&(t=arguments[0]),e===null&&t===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(e!=null){for(let i of e.content){let a=i;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(i,n);}for(let[,i]of e.namedContent)this.ValidateExternalBindings((0, R.asOrNull)(i,yl.InkObject),n);}else if(t!=null){let i=(0, R.asOrNull)(t,tc.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, H.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.add(a);}}}ObserveVariable(e,t){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(e))throw new Error("Cannot observe variable '"+e+"' because it wasn't declared in the ink story.");this._variableObservers.has(e)?this._variableObservers.get(e).push(t):this._variableObservers.set(e,[t]);}ObserveVariables(e,t){for(let n=0,i=e.length;n<i;n++)this.ObserveVariable(e[n],t[n]);}RemoveVariableObserver(e,t){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(t!=null){if(this._variableObservers.has(t))if(e!=null){let n=this._variableObservers.get(t);n!=null&&(n.splice(n.indexOf(e),1),n.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let n=this._variableObservers.keys();for(let i of n){let a=this._variableObservers.get(i);a!=null&&(a.splice(a.indexOf(e),1),a.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(e,t){if(this._variableObservers===null)return;let n=this._variableObservers.get(e);if(typeof n<"u"){if(!(t instanceof N.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, R.asOrThrows)(t,N.Value);for(let a of n)a(e,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new Sl.Path(e),n=this.ContentAtPath(t).container;if(n===null)return (0, H.throwNullException)("flowContainer");for(;;){let s=n.content[0];if(s instanceof Ce.Container)n=s;else break}let i=false,a=null;for(let s of n.content){let o=(0, R.asOrNull)(s,k.ControlCommand);if(o!=null)o.commandType==k.ControlCommand.CommandType.BeginTag?i=true:o.commandType==k.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let l=(0, R.asOrNull)(s,N.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 e=new qt.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new qt.StringBuilder;return e.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=wt.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(Me.PushPopType.Function)?(this.state.PopCallStack(Me.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new ii.Void),t=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),t=true):this.state.TryExitFunctionEvaluationFromGame(),t&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let e=true,t=this.state.callStack.currentElement.currentPointer.copy();if(t.index++,t.container===null)return (0, H.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let n=(0, R.asOrNull)(t.container.parent,Ce.Container);if(!(n instanceof Ce.Container))break;let i=n.content.indexOf(t.container);if(i==-1)break;if(t=new wt.Pointer(n,i),t.index++,e=true,t.container===null)return (0, H.throwNullException)("pointer.container")}return e||(t=wt.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(i=>i.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let n=t[0];return n.targetPath===null?(0, H.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, H.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 e=(0, R.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(!(e instanceof N.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, H.throwNullException)("seqContainer");if(e.value===null)return (0, H.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, R.asOrThrows)(this.state.PopEvaluationStack(),N.IntValue).value;if(a===null)return (0, H.throwNullException)("seqCount");let s=a/n,o=a%n,l=t.path.toString(),u=0;for(let d=0,f=l.length;d<f;d++)u+=l.charCodeAt(d)||0;let h=u+s+this.state.storySeed,c=new El.PRNG(Math.floor(h)),p=[];for(let d=0;d<n;++d)p.push(d);for(let d=0;d<=o;++d){let f=c.next()%p.length,g=p[f];if(p.splice(f,1),d==o)return g}throw new Error("Should never reach here")}Error(e,t=false){let n=new jt.StoryException(e);throw n.useEndLineNumber=t,n}Warning(e){this.AddError(e,true);}AddError(e,t=false,n=false){let i=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(i!=null){let s=n?i.endLineNumber:i.startLineNumber;e="RUNTIME "+a+": '"+i.fileName+"' line "+s+": "+e;}else this.state.currentPointer.isNull?e="RUNTIME "+a+": "+e:e="RUNTIME "+a+": ("+this.state.currentPointer+"): "+e;this.state.AddError(e,t),t||this.state.ForceEnd();}Assert(e,t=null){if(e==false)throw t==null&&(t="Story assert"),new Error(t+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let e,t=this.state.currentPointer;if(!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.callStack.elements.length-1;n>=0;--n)if(t=this.state.callStack.elements[n].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.outputStream.length-1;n>=0;--n)if(e=this.state.outputStream[n].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};Mt.Story=mn;mn.inkVersionCurrent=21;(function(r){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(r.OutputStateChange||(r.OutputStateChange={}));})(mn||(Mt.Story=mn={}));});var sc=x(ks=>{Object.defineProperty(ks,"__esModule",{value:true});ks.Story=void 0;var jg=Oi(),qg=dr(),Fs=re(),Ns=me(),si=Ut(),Is=tt(),rc=an(),Mg=Go(),Gg=Gr(),$g=Ko(),Jg=Qn(),gn=ct(),Hg=Et(),zg=vt(),ai=z(),Ug=Gn(),Kg=$n(),Xg=Lt(),Vs=class r extends Is.FlowBase{get flowLevel(){return rc.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(e,t=false){super(null,e,null,false,t),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(qg.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let p=`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(p,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(Gg.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 Fs.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 p=new zg.VariableAssignment(h,true);p.isGlobal=true,o.AddContent(p);}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 Jg.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, ai.asOrNull)(a,Fs.Container);s&&i.add(s);}if(n.namedContent)for(let[,a]of n.namedContent){let s=(0, ai.asOrNull)(a,Fs.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, ai.asOrNull)(n.parent,Fs.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?si.ErrorType.Warning:si.ErrorType.Error,o="";if(i instanceof jg.AuthorWarning?(o+="TODO: ",s=si.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===si.ErrorType.Error,this._hadWarning=s===si.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(Kg.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||"",rc.FlowLevel.Knot),h=(0, ai.asOrNull)(u,Is.FlowBase);if(h&&(h!==n||a===gn.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,l);return}if(a<gn.SymbolType.List)return;for(let[f,g]of this._listDefs)if(i?.name===f&&n!==g&&g.variableAssignment!==n&&this.NameConflictError(n,i?.name,g,l),!(n instanceof $g.ListElementDefinition))for(let b of g.itemDefinitions)i?.name===b.name&&this.NameConflictError(n,i?.name||"",b,l);if(a<=gn.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<gn.SymbolType.SubFlowAndWeave)return;let d=new Xg.Path(i).ResolveFromContext(n);if(d&&d!==n){this.NameConflictError(n,i?.name||"",d,l);return}if(!(a<gn.SymbolType.Arg)&&a!==gn.SymbolType.Arg){let f=(0, ai.asOrNull)(n,Is.FlowBase);if(f||(f=(0, Ug.ClosestFlowBase)(n)),f&&f.hasParameters&&f.args){for(let g of f.args)if(((o=g.identifier)===null||o===void 0?void 0:o.name)===i?.name){n.Error(`${l} '${i}': name has already been used for a argument to ${f.identifier} on ${f.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let n of e)if(n instanceof Mg.IncludedFile){let i=n,a=e.indexOf(n);if(e.splice(a,1),i.includedStory){let s=[],o=i.includedStory;if(o.content!=null){for(let l of o.content)l instanceof Is.FlowBase?t.push(l):s.push(l);s.push(new Hg.Text(`
29
+ `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};ks.Story=Vs;Vs.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 oc=x(Rs=>{Object.defineProperty(Rs,"__esModule",{value:true});Rs.StringExpression=void 0;var ac=me(),Yg=Le(),Qg=Et(),Zg=z(),Dl=class r extends Yg.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof Qg.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(ac.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(ac.ControlCommand.EndString());},this.toString=()=>{let t="";for(let n of this.content)t+=n;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, Zg.asOrNull)(e,r);if(t===null||!this.isSingleString||!t.isSingleString)return false;let n=this.toString(),i=t.toString();return n===i}};Rs.StringExpression=Dl;});var uc=x(Cn=>{Object.defineProperty(Cn,"__esModule",{value:true});Cn.LegacyTag=Cn.Tag=void 0;var eC=Z(),lc=me(),bl=class extends eC.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?lc.ControlCommand.BeginTag():lc.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};Cn.Tag=bl;var tC=Bo(),Al=class extends tC.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};Cn.LegacyTag=Al;});var hc=x(Ls=>{Object.defineProperty(Ls,"__esModule",{value:true});Ls.DefaultFileHandler=void 0;var wl=class{constructor(e){this.rootPath=e,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};Ls.DefaultFileHandler=wl;});var Pl=x(qs=>{Object.defineProperty(qs,"__esModule",{value:true});qs.InkParser=void 0;var nC=Iu(),iC=Oi(),rC=Na(),He=Hu(),pe=Bn(),sC=sn(),aC=th(),oC=hr(),oi=po(),Ve=Ar(),lC=dr(),Bs=bh(),uC=Ah(),Gt=un(),xl=ln(),hC=Le(),cC=wh(),cc=xh(),Ws=$n(),pC=Mn(),dC=_h(),fC=is(),js=Ph(),pc=Go(),mC=Th(),gC=Ho(),dc=Nh(),CC=Gr(),yC=Ko(),vC=lo(),fc=Z(),SC=Lt(),mc=Za(),gc=Do(),ce=vo(),Ae=Xo(),EC=Qo(),Cc=sc(),li=oc(),pt=Ga(),yn=uc(),dt=Et(),yc=Ao(),_l=To(),Ol=cn(),DC=Ta(),xt=z(),ui=Er(),vn=$i(),vc=Ut(),bC=hc(),K=class r extends pt.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,n=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel(Ae.StatementLevel.Top);return new Cc.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 p=this.Parse(s);if(p===null){this.FailRule(h);break}this.SucceedRule(h),u.push(p);}while(true);return u},this.CreateDebugMetadata=(s,o)=>{let l=new uC.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, xt.asOrNull)(s,fc.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let h=Array.isArray(s)?s:null;if(h!==null)for(let p of h)(0, xt.asOrNull)(p,fc.ParsedObject)&&(p.hasOwnDebugMetadata||(p.debugMetadata=this.CreateDebugMetadata(o,l)));let c=(0, xt.asOrNull)(s,ui.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?vc.ErrorType.Warning:vc.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 iC.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 Ve.ContentList(c));let p=null,d=null,f=this.ParseString("[")!==null;if(f){this.EndTagIfNecessary(h);let y=this.Parse(this.MixedTextAndLogic);y!==null&&(p=new Ve.ContentList(y)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(p);let m=this.Parse(this.MixedTextAndLogic);m!==null&&(d=new Ve.ContentList(m));}this.Whitespace(),this.EndTagIfNecessary(d??h);let g=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let b=!h&&!d&&!p;if(b&&g===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&f&&!p&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),d||(d=new Ve.ContentList),this.EndTagIfNecessary(d),g!==null)for(let y of g){let m=(0, xt.asOrNull)(y,Gt.Divert);m&&m.isEmpty||d.AddContent(y);}d.AddContent(new dt.Text(`
31
+ `));let D=new sC.Choice(h,p,d);return l&&(D.identifier=l),D.indentationDepth=o.length,D.hasWeaveStyleInlineBrackets=f,D.condition=u,D.onceOnly=s,D.isInvisibleDefault=b,D},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new vC.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),pt.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 pC.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),p=this.Parse(()=>this.InnerConditionalContent(c));return p===null?null:p}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(Ae.StatementLevel.InnerBlock);if(c!==null){o=[new oi.ConditionalSingleBranch(c)];let d=this.Parse(this.SingleMultilineCondition);d&&(d.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",d),d.isElse=true),o.push(d));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let c=new oi.ConditionalSingleBranch(null);c.isTrueBranch=true,o.unshift(c);}if(s){let c=false;for(let p=0;p<o.length;++p){let d=o[p],f=p===o.length-1;d.ownExpression?(d.matchingEquality=true,c=true):c&&f?(d.matchingEquality=true,d.isElse=true):!f&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",d):p===0?d.isTrueBranch=true:d.isElse=true;}}else {for(let c=0;c<o.length;++c){let p=o[c],d=c===o.length-1;if(p.ownExpression===null)if(d)p.isElse=true;else if(p.isElse){let f=o[o.length-1];f.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",f):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",p);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",p);}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 oC.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 oi.ConditionalSingleBranch(s[0]);if(l.isTrueBranch=true,o.push(l),s.length>1){let u=new oi.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(Ae.StatementLevel.InnerBlock);s===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new dt.Text("")]),this.MultilineWhitespace();let u=new oi.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:pt.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 dt.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 Gt.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof yn.Tag&&s[0].isStart||s.push(new dt.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 dt.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new pe.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new pe.CharacterSet(`{}|
33
+ \r\\#`),this._notTextEndCharactersChoice=new pe.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new pe.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 p=new yc.TunnelOnwards;if(u<l.length-1){let d=(0, xt.asOrNull)(l[u+1],Gt.Divert);p.divertAfter=d;}s.push(p);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 Gt.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 Gt.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 SC.Path(s);return new Gt.Divert(l,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof yc.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 js.IncDecExpression(o,h,l):new _l.VariableAssignment({variableIdentifier:o,assignedExpression:h,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof js.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 mc.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=DC.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof Ol.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new js.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 xl.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new vn.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new vn.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 dt.Text("")]:o.find(l=>l instanceof Gt.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new li.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new vn.NumberExpression(true,"bool"):s==="false"?new vn.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 Ws.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||Cc.Story.IsReservedKeyword(s[0].name)?null:new Ol.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 rC.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 dc.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 mC.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
34
  \r`),"filename for include statement");s=s.replace(new RegExp(/[ \t]+$/g),"");let o=this.fileHandler.ResolveInkFilename(s,this._filename);if(this.FilenameIsAlreadyOpen(o))return this.Error(`Recursive INCLUDE detected: '${o}' is already open.`),this.ParseUntilCharactersFromString(`\r
35
- `),new cc.IncludedFile(null);this.AddOpenFilename(o);let u=null,l="";try{l=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(h){this.Error(`Failed to load: '${s}'.
36
- Error:${h}`);}return l!=null&&(u=new r(l,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new cc.IncludedFile(u)},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(be.StatementLevel.Knot),u=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new fC.Knot(s.name,u,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,u=s?.name==="function";u?(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 ${u?"function":"knot"}`),o=new ui.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new hc.FlowDecl(o,l,u)},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(be.StatementLevel.Stitch),u=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new vC.Stitch(s.name,u,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 u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new hc.FlowDecl(o,u,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new de.CharacterSet("="),null),[new dt.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 u=this.Parse(this.IdentifierWithMetadata);if(s==null&&u===null)return null;let l=new eC.Argument;return o!==null&&(l.isDivertTarget=true),s!==null&&s.name==="ref"?(u===null&&this.Error("Expected an parameter name after 'ref'"),l.identifier=u,l.isByReference=true):(l.isDivertTarget?l.identifier=u:l.identifier=s,l.identifier===null&&this.Error("Expected an parameter name"),l.isByReference=false),l},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 ui.Identifier("");this.Whitespace();let u=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);u===null&&(u=[]);let l=u.map(h=>{var c;return (c=h.identifier)===null||c===void 0?void 0:c.name}).filter(xt.filterUndef);return new uC.ExternalDeclaration(o,l)},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 Fe.ContentList;o instanceof lC.Expression&&!(o instanceof js.FunctionCall||o instanceof qs.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
35
+ `),new pc.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}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 pc.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(Ae.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new gC.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 ui.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new cc.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(Ae.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new EC.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 cc.FlowDecl(o,l,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new pe.CharacterSet("="),null),[new dt.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 nC.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 ui.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(xt.filterUndef);return new cC.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 Ve.ContentList;o instanceof hC.Expression&&!(o instanceof Ws.FunctionCall||o instanceof js.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
37
37
  ~ return
38
38
  ~ var x = blah
39
39
  ~ x++
40
- ~ myFunction()`);let u=(0, xt.asOrNull)(o,js.FunctionCall);return u&&(u.shouldPopReturnedValue=true),o.Find(js.FunctionCall)()!==null&&(o=new Fe.ContentList(o,new dt.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 l=this.Expect(this.Expression,"initial value for ");return l?(l instanceof vn.NumberExpression||l instanceof li.StringExpression||l instanceof _l.DivertTarget||l instanceof Ol.VariableReference||l instanceof dc.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):l instanceof li.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new Tl.VariableAssignment({assignedExpression:l,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 u=this.Expect(this.ListDefinition,"list item names");return u?(u.identifier=new ui.Identifier(o.name),new Tl.VariableAssignment({variableIdentifier:o,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new mC.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(u===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let l=null;if(this.ParseString("=")!==null){this.Whitespace();let h=this.Expect(this.ExpressionInt,"value to be assigned to list item");h!==null&&(l=h.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new gC.ListElementDefinition(u,s,l)},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 u=this.Expect(this.Expression,"initial value for ");return u instanceof vn.NumberExpression||u instanceof _l.DivertTarget||u instanceof li.StringExpression?u instanceof li.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new aC.ConstantDeclaration(o,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new cC.Glue(new dC.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let u=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(u===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(u);let l=(0, xt.asOrNull)(u,Fe.ContentList);return l||(l=new Fe.ContentList(u)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(l),l},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let l=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return l===null?null:new mc.Sequence(l,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let u=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let l of u){let h=this.BeginRule(),c=this.ParseObject(l);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let s=this.Parse(this.Expression);return s&&(s.outputWhenComplete=true),s},this.IdentifierWithMetadata=()=>{let s=this.Identifier();return s===null?null:new ui.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let u of s)if(!(u>="0"&&u<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new de.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=ce.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let u=this.Parse(this.InnerSequenceObjects);return u===null||u.length<=1?null:new mc.Sequence(u,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case ce.SequenceType.Once:case ce.SequenceType.Cycle:case ce.SequenceType.Stopping:case ce.SequenceType.Shuffle:case ce.SequenceType.Shuffle|ce.SequenceType.Stopping:case ce.SequenceType.Shuffle|ce.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),ce.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new de.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let u of o)switch(u){case "!":s|=ce.SequenceType.Once;break;case "&":s|=ce.SequenceType.Cycle;break;case "~":s|=ce.SequenceType.Shuffle;break;case "$":s|=ce.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 u of s)o|=u;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=ce.SequenceType.Once;break;case "cycle":s=ce.SequenceType.Cycle;break;case "shuffle":s=ce.SequenceType.Shuffle;break;case "stopping":s=ce.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=[],u=false;for(let l of s)if(l==="|")u||o.push(new Fe.ContentList),u=false;else {let h=l;h===null?this.Error(`Expected content, but got ${l} (this is an ink compiler bug!)`):o.push(new Fe.ContentList(h)),u=true;}return u||o.push(new Fe.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(be.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new dt.Text(`
42
- `)),new Fe.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===be.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],u=this.OneOf(o);return s===be.StatementLevel.Top&&u instanceof fc.ReturnType&&this.Error("should not have return statement outside of a knot"),u},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],u=this.OneOf(o);return u===null?null:u},this.GenerateStatementLevelRules=()=>{let s=Object.values(be.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 u=[],l=[];u.push(this.Line(this.MultiDivert)),o>=be.StatementLevel.Top&&u.push(this.KnotDefinition),u.push(this.Line(this.Choice)),u.push(this.Line(this.AuthorWarning)),o>be.StatementLevel.InnerBlock&&u.push(this.Gather),o>=be.StatementLevel.Knot&&u.push(this.StitchDefinition),u.push(this.Line(this.ListDeclaration)),u.push(this.Line(this.VariableDeclaration)),u.push(this.Line(this.ConstDeclaration)),u.push(this.Line(this.ExternalDeclaration)),u.push(this.Line(this.IncludeStatement)),u.push(this.LogicLine),u.push(this.LineOfMixedTextAndLogic),o<=be.StatementLevel.Knot&&l.push(this.KnotDeclaration),o<=be.StatementLevel.Stitch&&l.push(this.StitchDeclaration),o<=be.StatementLevel.InnerBlock&&(l.push(this.ParseDashNotArrow),l.push(this.String("}"))),this._statementRulesAtLevel[o]=u,this._statementBreakRulesAtLevel[o]=l;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
43
- \r`),this.ParseNewline(),ct.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 Fe.ContentList;o.AddContent(new yn.Tag(false)),o.AddContent(new yn.Tag(true)),s=o;}else s=new yn.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new de.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?ct.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?ct.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?ct.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?ct.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?ct.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=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new EC.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(e){return new rC.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(Ws.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(Ws.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(Ws.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(Ws.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new de.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(e){this.tagActive&&(e!=null&&(e instanceof Fe.ContentList?e.AddContent(new yn.Tag(false)):e.push(new yn.Tag(false))),this.tagActive=false);}};Ms.InkParser=U;U.LatinBasic=He.CharacterRange.Define("A","z",new de.CharacterSet().AddRange("[","`"));U.LatinExtendedA=He.CharacterRange.Define("\u0100","\u017F");U.LatinExtendedB=He.CharacterRange.Define("\u0180","\u024F");U.Greek=He.CharacterRange.Define("\u0370","\u03FF",new de.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));U.Cyrillic=He.CharacterRange.Define("\u0400","\u04FF",new de.CharacterSet().AddRange("\u0482","\u0489"));U.Armenian=He.CharacterRange.Define("\u0530","\u058F",new de.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));U.Hebrew=He.CharacterRange.Define("\u0590","\u05FF",new de.CharacterSet);U.Arabic=He.CharacterRange.Define("\u0600","\u06FF",new de.CharacterSet);U.Korean=He.CharacterRange.Define("\uAC00","\uD7AF",new de.CharacterSet);U.Latin1Supplement=He.CharacterRange.Define("\x80","\xFF",new de.CharacterSet);U.Chinese=He.CharacterRange.Define("\u4E00","\u9FFF",new de.CharacterSet);U.ListAllCharacterRanges=()=>[U.LatinBasic,U.LatinExtendedA,U.LatinExtendedB,U.Arabic,U.Armenian,U.Cyrillic,U.Greek,U.Hebrew,U.Korean,U.Latin1Supplement,U.Chinese];});var vc=x(Gs=>{Object.defineProperty(Gs,"__esModule",{value:true});Gs.GenerateStoryStats=void 0;var DC=sn(),bC=un(),AC=Mn(),xC=zo(),wC=Zo(),_C=St();function TC(r){let e=r.FindAll(_C.Text)(),t=0;for(let u of e){let l=0,h=true;for(let c of u.text)c==" "||c==" "||c==`
44
- `||c=="\r"?h=true:h&&(l++,h=false);t+=l;}let n=r.FindAll(xC.Knot)(),i=r.FindAll(wC.Stitch)(),a=r.FindAll(DC.Choice)(),s=r.FindAll(AC.Gather)(u=>u.debugMetadata!=null),o=r.FindAll(bC.Divert)();return {words:t,knots:n.length,functions:n.filter(u=>u.isFunction).length,stitches:i.length,gathers:s.length,diverts:o.length-1,choices:a.length}}Gs.GenerateStoryStats=TC;});var Sc=x($s=>{Object.defineProperty($s,"__esModule",{value:true});$s.JsonFileHandler=void 0;var Fl=class{constructor(e){this.fileHierarchy=e,this.ResolveInkFilename=t=>{if(Object.keys(this.fileHierarchy).includes(t))return t;throw new Error(`Cannot locate ${t}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=t=>{if(Object.keys(this.fileHierarchy).includes(t))return this.fileHierarchy[t];throw new Error(`Cannot open ${t}.`)};}};$s.JsonFileHandler=Fl;});var Dc=x(ye=>{Object.defineProperty(ye,"__esModule",{value:true});ye.Compiler=ye.Story=ye.InkList=ye.JsonFileHandler=ye.StatementLevel=ye.InkParser=ye.CompilerOptions=void 0;var OC=fa(),PC=Pu(),Nl=Ut(),FC=Pl(),NC=ee(),IC=H(),VC=vc(),kC=fa();Object.defineProperty(ye,"CompilerOptions",{enumerable:true,get:function(){return kC.CompilerOptions}});var RC=Pl();Object.defineProperty(ye,"InkParser",{enumerable:true,get:function(){return RC.InkParser}});var LC=Yo();Object.defineProperty(ye,"StatementLevel",{enumerable:true,get:function(){return LC.StatementLevel}});var BC=Sc();Object.defineProperty(ye,"JsonFileHandler",{enumerable:true,get:function(){return BC.JsonFileHandler}});var Ec=Qn();Object.defineProperty(ye,"InkList",{enumerable:true,get:function(){return Ec.InkList}});Object.defineProperty(ye,"Story",{enumerable:true,get:function(){return Ec.Story}});var Il=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(e,t=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new FC.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, IC.asOrNull)(i,NC.StringValue);if(a!==null){let s=new PC.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, VC.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 Nl.ErrorType.Author:this._authorMessages.push(n);break;case Nl.ErrorType.Warning:this._warnings.push(n);break;case Nl.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=e,this._options=t||new OC.CompilerOptions;}};ye.Compiler=Il;});var Ae;(r=>(r.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),r.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),r.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),r.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Ae||={});var _=class M{static init(e){e.loadAssets&&(M._loadAssets=e.loadAssets),e.soundOperation&&(M._soundOperation=e.soundOperation),e.imageOperation&&(M._imageOperation=e.imageOperation),e.videoOperation&&(M._videoOperation=e.videoOperation),e.imageContainerOperation&&(M._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(M._textOperation=e.textOperation),e.canvasElementOperation&&(M._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(M._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(M._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(M._narrationOperation=e.narrationOperation),e.effectOperation&&(M._effectOperation=e.effectOperation),e.animateOperation&&(M._animateOperation=e.animateOperation),e.getLogichValue&&(M._getLogichValue=e.getLogichValue),e.getConditionalStep&&(M._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return M._loadAssets}static _soundOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return M._soundOperation}static _imageOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return M._imageOperation}static _videoOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return M._videoOperation}static _imageContainerOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return M._imageContainerOperation}static _textOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return M._textOperation}static _canvasElementOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return M._canvasElementOperation}static _setStorageValue=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return M._setStorageValue}static _setInitialStorageValue=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return M._setInitialStorageValue}static _narrationOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return M._narrationOperation}static _effectOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return M._effectOperation}static _animateOperation=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return M._animateOperation}static _getLogichValue=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return M._getLogichValue}static _getConditionalStep=()=>{throw Ae.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return M._getConditionalStep}};exports.TextReplaces=void 0;(r=>{r.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(l,h){e.unshift({fn:l,opts:h});}r.add=t;function n(l){let h=e.findIndex(c=>c.fn===l);h!==-1&&e.splice(h,1);}r.remove=n;function i(){return e.map(l=>l.opts)}r.info=i;function a(l,h){let c=e.filter(d=>(d.opts.type??"after-translation")===h.type);for(let d of c)l=u(l,d.fn,d.opts.validation);return l}r.replace=a;function s(l){let h=e.filter(c=>c.opts.i18nInterpolation);for(let c of h)l=o(l,c.fn,c.opts);return l}r.runI18nPreStep=s;function o(l,h,c){let{validation:d}=c,f=new RegExp(r.options.replaceRegex.source,"g"),m=[...l.matchAll(f)],g=new Set,b=[];for(let S of m)g.has(S[1])||(g.add(S[1]),b.push(S[1]));for(let S of b){if(d==="characterId"){if(!characters.RegisteredCharacters.has(S))continue}else if(d!=="all"){if(d instanceof RegExp){if(!d.test(S))continue}else if(d instanceof v.ZodType&&!d.safeParse(S).success)continue}h(S)!==void 0&&(l.includes(`{{[${S}]}}`)||(l=l.replaceAll(`[${S}]`,`{{[${S}]}}`)));}return l}function u(l,h,c){let d=new RegExp(r.options.replaceRegex.source,"g"),f=[...l.matchAll(d)],m=new Set,g=[];for(let b of f)m.has(b[1])||(m.add(b[1]),g.push(b[1]));for(let b of g){if(c==="characterId"){if(!characters.RegisteredCharacters.has(b))continue}else if(c!=="all"){if(c instanceof RegExp){if(!c.test(b))continue}else if(c instanceof v.ZodType&&!c.safeParse(b).success)continue}let S=h(b);S!==void 0&&(l=l.replaceAll(`[${b}]`,S));}return l}})(exports.TextReplaces||={});function Ic(r,e={}){let t="";return r.values.forEach(n=>{if(typeof n=="string")t+=n;else {let i=_.getLogichValue(n,e);t+=`${i}`;}}),t}var ql;(r=>{let e=u=>u;function t(u){return Array.isArray(u)?u.map(l=>n(`${l}`)):n(`${u}`)}r.t=t;function n(u){let l=u;return r.beforeToTranslate&&(l=(0, r.beforeToTranslate)(l)),l=exports.TextReplaces.replace(l,{type:"before-translation"}),l=e(l),r.afterToTranslate&&(l=(0, r.afterToTranslate)(l)),l=exports.TextReplaces.replace(l,{type:"after-translation"}),l}r.translate=n;function i(u){e=u;}r.setTranslate=i;function a(u,l,h){let{defaultValue:c="empty_string"}=h;typeof l=="string"&&(l=[l]),Array.isArray(l)&&l.forEach(d=>{let f=d;if(r.beforeToTranslate&&(f=(0, r.beforeToTranslate)(f)),c==="empty_string")u[f]===void 0&&(u[f]="");else if(c==="copy_key"){let m=d;r.beforeToTranslate&&(m=(0, r.beforeToTranslate)(m));let g=exports.TextReplaces.runI18nPreStep(m);g=exports.TextReplaces.replace(g,{type:"before-translation"}),u[f]=g;}});}function s(u,l=[]){if(typeof u=="object"&&u&&"type"in u)if(u.type==="ifelse")u.then&&s(u.then,l),u.else&&s(u.else,l);else if(u.type==="stepswitch"){if(u.elements)if(Array.isArray(u.elements))u.elements.forEach(h=>{s(h,l);});else if(u.elements.type==="ifelse"){let h=[];s(u.elements,h),h.forEach(c=>{l.push(...c);});}else if(u.elements.type==="stepswitch"){let h=[];s(u.elements,h),h.forEach(c=>{l.push(...c);});}else s(u.elements,l);}else u.type==="resulttocombine"?(u.firstItem&&s(u.firstItem,l),u.secondConditionalItem&&u.secondConditionalItem.forEach(h=>{s(h,l);})):l.push(u);else u&&l.push(u);return l}async function o(u,l={},h={}){let{defaultValue:c="copy_key",operationStringConvert:d}=h,f=u.map(async m=>{if(m.choices){let g=[];Array.isArray(m.choices)?g=[m.choices]:g=s(m.choices),g.forEach(b=>{b.forEach(S=>{if("type"in S){let y=[];S.type==="ifelse"||S.type==="stepswitch"?s(S,y):y=[S],y.map(p=>s(p.text)).forEach(p=>{Array.isArray(p)&&p.forEach(D=>{Array.isArray(D)?D.forEach(C=>{typeof C=="string"?a(l,C,{defaultValue:c}):s(C).forEach(E=>{Array.isArray(E)?E.forEach(w=>{typeof w=="string"&&a(l,w,{defaultValue:c});}):typeof E=="string"&&a(l,E,{defaultValue:c});});}):typeof D=="string"&&a(l,D,{defaultValue:c});});});}});});}if(m.dialogue){let g=[];Array.isArray(m.dialogue)?g=[m.dialogue]:g=s(m.dialogue),g.forEach(b=>{if(typeof b=="string")a(l,b,{defaultValue:c});else if("text"in b){let S=s(b.text);typeof S=="string"&&(S=[S]),S.forEach(y=>{typeof y=="string"?a(l,y,{defaultValue:c}):s(y).forEach(p=>{typeof p=="string"?a(l,p,{defaultValue:c}):Array.isArray(p)&&p.forEach(D=>{typeof D=="string"?a(l,D,{defaultValue:c}):s(D).forEach(C=>{typeof C=="string"&&a(l,C,{defaultValue:c});});});});});}});}if(m.operations)for(let g of m.operations){if(g.type==="operationtoconvert"&&d){let b=Ic(g),S=await d(b,m,{});if(!S)return;g=S;}g.type==="text"&&g.operationType==="show"&&a(l,g.text,{defaultValue:c});}m.conditionalStep&&s(m.conditionalStep).forEach(g=>{Array.isArray(g)?o(g,l,h):o([g],l,h);});});return await Promise.all(f),l}r.generateJsonTranslation=o;})(ql||={});var oe=ql;async function Ml(r){let e=_.getLogichValue(r,{});if(e)switch(e.type){case "assets":switch(e.operationType){case "load":await canvas.Assets.load(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoad(e.aliases);break}break;case "bundle":switch(e.operationType){case "load":await canvas.Assets.loadBundle(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoadBundle(e.aliases);break}break}}var q;(r=>(r.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),r.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),r.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),r.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(q||={});async function fi(r,e,t){switch(t.type){case "fade":await canvas.showWithFade(e.alias,r,t.props,t.priority);break;case "dissolve":await canvas.showWithDissolve(e.alias,r,t.props,t.priority);break;case "movein":case "moveout":await canvas.moveIn(e.alias,r,t.props,t.priority);break;case "zoomin":case "zoomout":await canvas.zoomIn(e.alias,r,t.props,t.priority);break;case "pushin":case "pushout":await canvas.pushIn(e.alias,r,t.props,t.priority);break}}function Sn(r){if(r.transition)switch(r.transition.type){case "fade":canvas.removeWithFade(r.alias,r.transition.props,r.transition.priority);break;case "dissolve":canvas.removeWithDissolve(r.alias,r.transition.props,r.transition.priority);break;case "movein":case "moveout":canvas.moveOut(r.alias,r.transition.props,r.transition.priority);break;case "zoomin":case "zoomout":canvas.zoomOut(r.alias,r.transition.props,r.transition.priority);break;case "pushin":case "pushout":canvas.pushOut(r.alias,r.transition.props,r.transition.priority);break}else canvas.canvas.remove(r.alias);}async function Gl(r){switch(r.operationType){case "show":if(r.transition){let e=new canvas.ImageSprite(r.props,r.url||r.alias);await fi(e,r,r.transition);}else await canvas.showImage(r.alias,r.url,r.props);break;case "edit":{let e=canvas.canvas.find(r.alias);e?r.props&&await e.setMemory({...e.memory,...r.props}):q.error(`Image with alias ${r.alias} not found.`);break}case "remove":Sn(r);break}}async function $l(r){switch(r.operationType){case "show":if(r.transition){let e=new canvas.VideoSprite(r.props,r.url||r.alias);await fi(e,r,r.transition);}else await canvas.showVideo(r.alias,r.url,r.props);break;case "edit":{let e=canvas.canvas.find(r.alias);e?r.props&&await e.setMemory({...e.memory,...r.props}):q.error(`Video with alias ${r.alias} not found.`);break}case "remove":Sn(r);break;case "pause":case "resume":{let e=canvas.canvas.find(r.alias);e?e.paused=r.operationType==="pause":q.error(`Video with alias ${r.alias} not found.`);break}}}async function Jl(r){switch(r.operationType){case "show":if(r.transition){let e=new canvas.ImageContainer(r.props,r.urls);await fi(e,r,r.transition);}else await canvas.showImageContainer(r.alias,r.urls,r.props);break;case "edit":{let e=canvas.canvas.find(r.alias);e?r.props&&await e.setMemory({...e.memory,...r.props}):q.error(`ImageContainer with alias ${r.alias} not found.`);break}case "remove":Sn(r);break}}async function Hl(r){switch(r.operationType){case "show":if(r.props=r.props||{},r.props.text=oe.t(r.text),r.transition){let e=new canvas.Text(r.props);await fi(e,r,r.transition);}else canvas.showText(r.alias,r.text,r.props);break;case "edit":{let e=canvas.canvas.find(r.alias);e?r.props&&await e.setMemory({...e.memory,...r.props}):q.error(`Text with alias ${r.alias} not found.`);break}case "remove":Sn(r);break}}async function zl(r){switch(r.operationType){case "edit":try{let e=canvas.canvas.find(r.alias);e?r.props&&e.setMemory({...e.memory,...r.props}):q.error(`Canvas Element with alias ${r.alias} not found.`);}catch(e){q.error(`There was an error while trying to edit the canvas element with alias ${r.alias}.`,e);}break;case "remove":Sn(r);break}}async function Ul(r){r.type==="shake"&&await canvas.shakeEffect(r.alias,r.props,r.priority);}function Kl(r){switch(r.type){case "animate":canvas.canvas.animate(r.alias,r.keyframes,r.options,r.priority);break;case "animate-sequence":canvas.canvas.animate(r.alias,r.sequence,r.options,r.priority);break}}function Xl(r){switch(r.type){case "input":narration.narration.requestInput({type:r.valueType},r.defaultValue);break;case "dialogue":narration.narration.dialogue=void 0;break}}function Yl(r){switch(r.operationType){case "play":r.url?sound.sound.play(r.alias,r.url,r.props):sound.sound.play(r.alias,r.props);break;case "stop":switch(r.type){case "sound":sound.sound.stop(r.alias);break;case "all":sound.sound.stopAll();break}break;case "pause":switch(r.type){case "sound":sound.sound.pause(r.alias);break;case "channel":sound.sound.findChannel(r.alias).pauseAll();break;case "all":sound.sound.pauseAll();break}break;case "resume":switch(r.type){case "sound":sound.sound.resume(r.alias);break;case "channel":sound.sound.findChannel(r.alias).resumeAll();break;case "all":sound.sound.resumeAll();break}break;case "edit":Object.entries(r.props).forEach(([e,t])=>{let n=sound.sound.find(r.alias);n&&(e==="volume"?n.volume.value=t:n.paused=t);});break}}var Us="___param___",ed=class G{static init(e){e.loadAssets&&(G._loadAssets=e.loadAssets),e.soundOperation&&(G._soundOperation=e.soundOperation),e.imageOperation&&(G._imageOperation=e.imageOperation),e.videoOperation&&(G._videoOperation=e.videoOperation),e.imageContainerOperation&&(G._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(G._textOperation=e.textOperation),e.canvasElementOperation&&(G._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(G._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(G._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(G._narrationOperation=e.narrationOperation),e.effectOperation&&(G._effectOperation=e.effectOperation),e.animateOperation&&(G._animateOperation=e.animateOperation),e.getLogichValue&&(G._getLogichValue=e.getLogichValue),e.getConditionalStep&&(G._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return G._loadAssets}static _soundOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return G._soundOperation}static _imageOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return G._imageOperation}static _videoOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return G._videoOperation}static _imageContainerOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return G._imageContainerOperation}static _textOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return G._textOperation}static _canvasElementOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return G._canvasElementOperation}static _setStorageValue=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return G._setStorageValue}static _setInitialStorageValue=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return G._setInitialStorageValue}static _narrationOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return G._narrationOperation}static _effectOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return G._effectOperation}static _animateOperation=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return G._animateOperation}static _getLogichValue=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return G._getLogichValue}static _getConditionalStep=()=>{throw q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return G._getConditionalStep}};function td(r,e){if(e&&typeof e=="object"&&typeof r.functionName=="string"&&r.functionName in e){let t=e[r.functionName];if(typeof t=="function"){let n=r.args.map(i=>ed.getLogichValue(i,e));return t(...n)}else q.warn(`getLogichValue function ${r.functionName} not found in props`);}}function Ql(r,e){let t=_.getLogichValue(r,e);return t&&typeof t=="object"&&"type"in t?_.getLogichValue(t,e):t}function Zl(r,e={}){let t=Ql(r.value,e);switch(r.storageType){case "flagStorage":storage.storage.setFlag(r.key,r.value);break;case "storage":storage.storage.set(r.key,t);break;case "tempstorage":storage.storage.setTempVariable(r.key,t);break;case "params":{let n=storage.storage.get(`${Us}${narration.narration.openedLabels.length-1}`)||[];n.length>r.key&&(n[r.key]=t),storage.storage.setTempVariable(`${Us}${narration.narration.openedLabels.length-1}`,n);break}}}function eu(r,e={}){let t=Ql(r.value,e);switch(r.storageType){case "storage":case "tempstorage":storage.storage.default={[r.key]:t};break}}function tu(r,e={}){let t=nu(r,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return id(t,e);case "arithmetic":case "arithmeticsingle":return nd(t,e);case "compare":case "union":return rd(t,e);case "function":return td(t,e)}return t}function nd(r,e){let t=_.getLogichValue(r.leftValue,e);switch(r.type){case "arithmetic":{let n=_.getLogichValue(r.rightValue,e);switch(r.operator){case "*":return t*n;case "/":return t/n;case "+":return typeof t=="string"||typeof n=="string"?`${t}${n}`:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:Array.isArray(t)?[...t,n]:Array.isArray(n)?[t,...n]:t+n;case "-":if(Array.isArray(t)&&Array.isArray(n))return t.filter(i=>!n.includes(i));if(Array.isArray(t))return t.filter(i=>i!==n);if(Array.isArray(n)){q.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-n;case "%":return t%n;case "POW":return t**n;case "RANDOM":return narration.narration.getRandomNumber(t,n);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(n))return t.filter(i=>n.includes(i));q.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:q.warn("getValueFromArithmeticOperations unknown operator",r);return}}case "arithmeticsingle":switch(r.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function id(r,e){if(r&&typeof r=="object"&&"type"in r&&r.type==="value"&&r.storageOperationType==="get")switch(r.storageType){case "storage":case "tempstorage":return r.key==="_input_value_"?narration.narration.inputValue:storage.storage.get(r.key);case "flagStorage":return storage.storage.getFlag(r.key);case "label":return narration.narration.getTimesLabelOpened(r.label);case "choice":return narration.narration.getTimesChoiceMade(r.index);case "logic":return _.getLogichValue(r.operation,e);case "params":{let t=storage.storage.get(`${Us}${narration.narration.openedLabels.length-1}`)||[];if(t&&t.length>r.key)return t[r.key];q.warn("getValue params not found");return}}return r}function rd(r,e){if(!r)return false;if(typeof r!="object"||!("type"in r))return !!r;switch(r.type){case "compare":{let t=_.getLogichValue(r.leftValue,e),n=_.getLogichValue(r.rightValue,e);switch(r.operator){case "==":return Array.isArray(t)&&Array.isArray(n)?t.length===n.length&&t.every(i=>n.includes(i)):t===n;case "!=":return Array.isArray(t)&&Array.isArray(n)?t.length!==n.length||!t.every(i=>n.includes(i)):t!==n;case "<":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<0:Array.isArray(t)&&Array.isArray(n)?t.length<n.length:t<n;case "<=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<=0:Array.isArray(t)&&Array.isArray(n)?t.length<=n.length:t<=n;case ">":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>0:Array.isArray(t)&&Array.isArray(n)?t.length>n.length:t>n;case ">=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>=0:Array.isArray(t)&&Array.isArray(n)?t.length>=n.length:t>=n;case "CONTAINS":return Array.isArray(t)&&Array.isArray(n)?n.every(i=>t.includes(i)):Array.isArray(t)?t.includes(n):t.toString().includes(n.toString())}break}case "value":{let t=_.getLogichValue(r,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return sd(r,e)}return !!r}function sd(r,e){if(r.unionType==="not"){let n=tu(r.condition,e);return Array.isArray(n)?n.length===0:n&&typeof n=="object"?Object.keys(n).length===0:!n}let t=n=>_.getLogichValue(n,e)||false;return r.unionType==="and"?r.conditions.every(t):r.conditions.some(t)}function ad(r,e){return Math.floor(Math.random()*(e-r+1)+r)}function nu(r,e={}){if(Array.isArray(r)||!r)return r;if(r&&typeof r=="object"&&"type"in r)switch(r.type){case "resulttocombine":return od(r,e);case "ifelse":return _.getLogichValue(r.condition,e)?_.getLogichValue(r.then,e):_.getLogichValue(r.else,e);case "stepswitch":{let t=_.getLogichValue(r.elements,e)||[];if(t.length===0){q.error("getValueFromConditionalStatements elements.length === 0");return}switch(r.choiceType){case "random":{let n=ad(0,t.length-1);return _.getLogichValue(t[n],e)}case "loop":{let n=narration.NarrationManagerStatic.getCurrentStepTimesCounter(r.nestedId)-1;return n>t.length-1?(n=n%t.length,_.getLogichValue(t[n],e)):_.getLogichValue(t[n],e)}case "sequential":{let n,i=narration.NarrationManagerStatic.getCurrentStepTimesCounter(r.nestedId)-1;return r.end==="lastItem"&&(n=_.getLogichValue(t[t.length-1],e)),i>t.length-1?n:_.getLogichValue(t[i],e)}case "sequentialrandom":{let n=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:r.nestedId,onceOnly:true});if(n===void 0&&r.end==="lastItem"){let i=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(r.nestedId);if(!i?.usedRandomNumbers){q.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=i.usedRandomNumbers[`0-${t.length-1}`];return _.getLogichValue(t[a[a.length-1]],e)}if(n===void 0){q.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return _.getLogichValue(t[n],e)}}}}return r}function mi(r,e={}){if(r.conditionalStep){let t=pixiVn.createExportableElement(_.getLogichValue(r.conditionalStep,e));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 n={...r,conditionalStep:void 0,...t};return mi(n,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return r}function od(r,e){let t=r.firstItem,n=(r.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>_.getLogichValue(s,e)):[_.getLogichValue(a,e)]),i=t?[t,...n]:n;if(i.length===0){q.warn("combinateResult toCheck.length === 0");return}if(typeof i[0]=="string")return oe.t(i);if(typeof i[0]=="object"){let a=i,s,o=false,u=a.map((y,p)=>{y=mi(y,e);let D=_.getLogichValue(y.dialogue,e)||"";return p===0?(s=_.getLogichValue(y.glueEnabled,e)||false,D):(typeof D=="object"&&"text"in D&&(D=`${D.character}: ${D.text}`),s===false&&o&&(D=`
45
-
46
- ${D}`),D&&(o=true),s=_.getLogichValue(y.glueEnabled,e)||false,D)}),l=_.getLogichValue(u[0],e),h=typeof l=="object"&&"character"in l?l.character:void 0,c=u.flatMap(y=>{let p;y&&typeof y=="object"&&"text"in y?p=y.text:p=y;let D;return Array.isArray(p)?D=p.map(C=>{let E=_.getLogichValue(C,e);return oe.t(`${E}`)}):D=_.getLogichValue(p,e)||"",oe.t(D)}),d=a.find(y=>y.end),f=a.find(y=>y.choices),m=false,g=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),m=a[a.length-1].glueEnabled,g=a.reverse().find(y=>!(y.operations&&(!y.dialogue||!y.choices)))?.goNextStep);let b=a.find(y=>y.labelToOpen),S=[];return a.forEach(y=>{y.operations&&(S=[...S,...y.operations]);}),{dialogue:h?{character:h,text:c}:c,end:d?.end,choices:f?.choices,glueEnabled:m,goNextStep:g,labelToOpen:b?.labelToOpen,operations:S}}}exports.VariableGetter=void 0;(r=>{let e=new Set;function t(a){e.add(a);}r.add=t;function n(){e.clear();}r.clear=n;function i(a,s={}){let o=h=>tu(h,s)??void 0,u=nu(a,s);if(e.size===0)return o(u);let l=o;for(let h of e){let c=l;l=d=>h(d,c)??void 0;}return l(u)}r.getLogichValue=i;})(exports.VariableGetter||={});var cd=Object.create,ou=Object.defineProperty,dd=Object.getOwnPropertyDescriptor,pd=Object.getOwnPropertyNames,fd=Object.getPrototypeOf,md=Object.prototype.hasOwnProperty,ru=(r=>typeof wt<"u"?wt:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof wt<"u"?wt:e)[t]}):r)(function(r){if(typeof wt<"u")return wt.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),lu=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),gd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pd(e))!md.call(r,i)&&i!==t&&ou(r,i,{get:()=>e[i],enumerable:!(n=dd(e,i))||n.enumerable});return r},Cd=(r,e,t)=>(t=r!=null?cd(fd(r)):{},gd(ou(t,"default",{value:r,enumerable:true}),r)),yd=lu((r,e)=>{(function(t,n){typeof r=="object"?e.exports=r=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(r,function(){var t=t||(function(n,i){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof ru=="function")try{a=ru("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 y(){}return function(p){var D;return y.prototype=p,D=new y,y.prototype=null,D}})(),u={},l=u.lib={},h=l.Base=(function(){return {extend:function(y){var p=o(this);return y&&p.mixIn(y),(!p.hasOwnProperty("init")||this.init===p.init)&&(p.init=function(){p.$super.init.apply(this,arguments);}),p.init.prototype=p,p.$super=this,p},create:function(){var y=this.extend();return y.init.apply(y,arguments),y},init:function(){},mixIn:function(y){for(var p in y)y.hasOwnProperty(p)&&(this[p]=y[p]);y.hasOwnProperty("toString")&&(this.toString=y.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),c=l.WordArray=h.extend({init:function(y,p){y=this.words=y||[],p!=i?this.sigBytes=p:this.sigBytes=y.length*4;},toString:function(y){return (y||f).stringify(this)},concat:function(y){var p=this.words,D=y.words,C=this.sigBytes,E=y.sigBytes;if(this.clamp(),C%4)for(var w=0;w<E;w++){var P=D[w>>>2]>>>24-w%4*8&255;p[C+w>>>2]|=P<<24-(C+w)%4*8;}else for(var N=0;N<E;N+=4)p[C+N>>>2]=D[N>>>2];return this.sigBytes+=E,this},clamp:function(){var y=this.words,p=this.sigBytes;y[p>>>2]&=4294967295<<32-p%4*8,y.length=n.ceil(p/4);},clone:function(){var y=h.clone.call(this);return y.words=this.words.slice(0),y},random:function(y){for(var p=[],D=0;D<y;D+=4)p.push(s());return new c.init(p,y)}}),d=u.enc={},f=d.Hex={stringify:function(y){for(var p=y.words,D=y.sigBytes,C=[],E=0;E<D;E++){var w=p[E>>>2]>>>24-E%4*8&255;C.push((w>>>4).toString(16)),C.push((w&15).toString(16));}return C.join("")},parse:function(y){for(var p=y.length,D=[],C=0;C<p;C+=2)D[C>>>3]|=parseInt(y.substr(C,2),16)<<24-C%8*4;return new c.init(D,p/2)}},m=d.Latin1={stringify:function(y){for(var p=y.words,D=y.sigBytes,C=[],E=0;E<D;E++){var w=p[E>>>2]>>>24-E%4*8&255;C.push(String.fromCharCode(w));}return C.join("")},parse:function(y){for(var p=y.length,D=[],C=0;C<p;C++)D[C>>>2]|=(y.charCodeAt(C)&255)<<24-C%4*8;return new c.init(D,p)}},g=d.Utf8={stringify:function(y){try{return decodeURIComponent(escape(m.stringify(y)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(y){return m.parse(unescape(encodeURIComponent(y)))}},b=l.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new c.init,this._nDataBytes=0;},_append:function(y){typeof y=="string"&&(y=g.parse(y)),this._data.concat(y),this._nDataBytes+=y.sigBytes;},_process:function(y){var p,D=this._data,C=D.words,E=D.sigBytes,w=this.blockSize,P=w*4,N=E/P;y?N=n.ceil(N):N=n.max((N|0)-this._minBufferSize,0);var Z=N*w,ve=n.min(Z*4,E);if(Z){for(var Gt=0;Gt<Z;Gt+=w)this._doProcessBlock(C,Gt);p=C.splice(0,Z),D.sigBytes-=ve;}return new c.init(p,ve)},clone:function(){var y=h.clone.call(this);return y._data=this._data.clone(),y},_minBufferSize:0});l.Hasher=b.extend({cfg:h.extend(),init:function(y){this.cfg=this.cfg.extend(y),this.reset();},reset:function(){b.reset.call(this),this._doReset();},update:function(y){return this._append(y),this._process(),this},finalize:function(y){y&&this._append(y);var p=this._doFinalize();return p},blockSize:16,_createHelper:function(y){return function(p,D){return new y.init(D).finalize(p)}},_createHmacHelper:function(y){return function(p,D){return new S.HMAC.init(y,D).finalize(p)}}});var S=u.algo={};return u})(Math);return t});}),vd=lu((r,e)=>{(function(t,n){typeof r=="object"?e.exports=r=n(yd()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(r,function(t){return (function(){var n=t,i=n.lib,a=i.WordArray,s=i.Hasher,o=n.algo,u=[],l=o.SHA1=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(h,c){for(var d=this._hash.words,f=d[0],m=d[1],g=d[2],b=d[3],S=d[4],y=0;y<80;y++){if(y<16)u[y]=h[c+y]|0;else {var p=u[y-3]^u[y-8]^u[y-14]^u[y-16];u[y]=p<<1|p>>>31;}var D=(f<<5|f>>>27)+S+u[y];y<20?D+=(m&g|~m&b)+1518500249:y<40?D+=(m^g^b)+1859775393:y<60?D+=(m&g|m&b|g&b)-1894007588:D+=(m^g^b)-899497514,S=b,b=g,g=m<<30|m>>>2,m=f,f=D;}d[0]=d[0]+f|0,d[1]=d[1]+m|0,d[2]=d[2]+g|0,d[3]=d[3]+b|0,d[4]=d[4]+S|0;},_doFinalize:function(){var h=this._data,c=h.words,d=this._nDataBytes*8,f=h.sigBytes*8;return c[f>>>5]|=128<<24-f%32,c[(f+64>>>9<<4)+14]=Math.floor(d/4294967296),c[(f+64>>>9<<4)+15]=d,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(l),n.HmacSHA1=s._createHmacHelper(l);})(),t.SHA1});}),su="___param___",se;(r=>(r.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),r.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),r.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),r.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(se||={});var Sd=class ${static init(e){e.loadAssets&&($._loadAssets=e.loadAssets),e.soundOperation&&($._soundOperation=e.soundOperation),e.imageOperation&&($._imageOperation=e.imageOperation),e.videoOperation&&($._videoOperation=e.videoOperation),e.imageContainerOperation&&($._imageContainerOperation=e.imageContainerOperation),e.textOperation&&($._textOperation=e.textOperation),e.canvasElementOperation&&($._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&($._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&($._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&($._narrationOperation=e.narrationOperation),e.effectOperation&&($._effectOperation=e.effectOperation),e.animateOperation&&($._animateOperation=e.animateOperation),e.getLogichValue&&($._getLogichValue=e.getLogichValue),e.getConditionalStep&&($._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return $._loadAssets}static _soundOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return $._soundOperation}static _imageOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return $._imageOperation}static _videoOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return $._videoOperation}static _imageContainerOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return $._imageContainerOperation}static _textOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return $._textOperation}static _canvasElementOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return $._canvasElementOperation}static _setStorageValue=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return $._setStorageValue}static _setInitialStorageValue=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return $._setInitialStorageValue}static _narrationOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return $._narrationOperation}static _effectOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return $._effectOperation}static _animateOperation=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return $._animateOperation}static _getLogichValue=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return $._getLogichValue}static _getConditionalStep=()=>{throw se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return $._getConditionalStep}};function Ed(r,e){if(e&&typeof e=="object"&&typeof r.functionName=="string"&&r.functionName in e){let t=e[r.functionName];if(typeof t=="function"){let n=r.args.map(i=>Sd.getLogichValue(i,e));return t(...n)}else se.warn(`getLogichValue function ${r.functionName} not found in props`);}}function Dd(r,e={}){let t="";return r.values.forEach(n=>{if(typeof n=="string")t+=n;else {let i=_.getLogichValue(n,e);t+=`${i}`;}}),t}async function uu(r,e,t){let n=_.getLogichValue(r,e);if(n)switch(n.type){case "sound":_.soundOperation(n);break;case "assets":case "bundle":await _.loadAssets(n);break;case "image":await _.imageOperation(n);break;case "video":await _.videoOperation(n);break;case "imagecontainer":await _.imageContainerOperation(n);break;case "text":await _.textOperation(n);break;case "canvaselement":await _.canvasElementOperation(n);break;case "value":_.setStorageValue(n,e);break;case "operationtoconvert":if(t){let i=Dd(n,e),a=await t(i);a&&await uu(a,e,t);}break;case "input":case "dialogue":_.narrationOperation(n);break;case "shake":await _.effectOperation(n);break;case "animate":case "animate-sequence":_.animateOperation(n);break;case "function":await Ed(n,e);break}}function au(r){let e=_.getLogichValue(r,{});e&&e.type==="value"&&e.storageOperationType==="set"&&(e.storageType==="storage"||e.storageType==="tempstorage")&&_.setInitialStorageValue(e);}var bd=Cd(vd()),Ad=class extends narration.LabelAbstract{constructor(r,e,t,n={}){t||(t={}),t.onLoadingLabel=async()=>{for(let i of e){let a;if(typeof i=="function"?a=i():a=i,a=_.getConditionalStep(a),a.operations)try{let s=a.operations.map(o=>_.loadAssets(o));await Promise.all(s);}catch(s){se.error("The operation in the onLoadingLabel function of the label has an error:",s);}}},super(r,t),this._steps=e,this.operationStringConvert=n.operationStringConvert,this.skipEmptyDialogs=n.skipEmptyDialogs||false;}_steps;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 e=this._steps[r];return this.stepConverter(e)}operationStringConvert;skipEmptyDialogs=false;getStepSha(r){if(r<0||r>=this.steps.length)return;let e=this._steps[r];return (0, bd.default)(e.toString().toLocaleLowerCase()).toString()}getDialogueText(r,e){let t="";if(Array.isArray(r)){let n=[];r.forEach(i=>{if(typeof i=="string")n.push(i);else if(i&&typeof i=="object"){let a=_.getLogichValue(i,e);a?(a&&!Array.isArray(a)&&typeof a=="object"&&(a=_.getLogichValue(a,e)||""),Array.isArray(a)?n=n.map(s=>`${s}`).concat(a):n.push(`${a}`)):n.push(`${i}`);}else n.push(`${i}`);}),t=n;}else {let n=_.getLogichValue(r,e);n&&!Array.isArray(n)&&typeof n=="object"&&(n=_.getLogichValue(n,e)),n&&Array.isArray(n)?t=n.map(i=>`${i}`):t=`${n}`;}return t}getDialogue(r,e){if(r==null)return;let t=_.getLogichValue(r,e);return t==null?`${t}`:typeof t=="object"&&"character"in t&&"text"in t?{character:t.character,text:oe.t(this.getDialogueText(t.text,e))}:oe.t(this.getDialogueText(t,e))}getChoices(r,e){return _.getLogichValue(r,e)?.map(t=>_.getLogichValue(t,e)).filter(t=>t!==void 0)}stepConverter(r){return async e=>{let t=typeof r=="function"?r():r;t=pixiVn.createExportableElement(t),t=_.getConditionalStep(t,e);let n=this.operationStringConvert?d=>this.operationStringConvert(d,t,e):void 0,{operations:i=[]}=t;for(let d of i)await uu(d,e,n);let{labelToOpen:a=[]}=t,s=this.getChoices(t.choices,e),o=_.getLogichValue(t.glueEnabled,e),u=this.getDialogue(t.dialogue,e),l=[];Array.isArray(a)||(a=[a]),a.forEach(d=>{let f=_.getLogichValue(d,e);f&&l.push(f);});let h=_.getLogichValue(t.goNextStep,e),c=_.getLogichValue(t.end,e);if(s){let d=s.map(f=>{let m="";if(Array.isArray(f.text)){let g=[];f.text.forEach(b=>{if(typeof b=="string")g.push(oe.t(b));else if(b&&typeof b=="object"){let S=_.getLogichValue(b,e);S&&!Array.isArray(S)&&typeof S=="object"&&(S=_.getLogichValue(S,e)||""),S&&(Array.isArray(S)?g=g.concat(oe.t(S)):g.push(oe.t(S)));}}),m=g;}else typeof f.text=="string"&&(m=oe.t(f.text));return {label:f.label,text:m,props:f.props,type:f.type,oneTime:f.oneTime,onlyHaveNoChoice:f.onlyHaveNoChoice,autoSelect:f.autoSelect}});narration.narration.choices=d;}else narration.narration.choices=void 0;u!==void 0&&(narration.narration.dialogue=u,this.skipEmptyDialogs&&typeof u=="string"&&(u===""||RegExp(/^\s+$/).test(u))&&(h=true)),o?narration.narration.dialogGlue=true:o===false&&(narration.narration.dialogGlue=false);for(let d of l){let f=d.label;typeof f=="object"&&(f=_.getLogichValue(f,e)||"");let m=d.params?.map(g=>_.getLogichValue(g,e));e={...e,...d.props},d.type==="jump"?(narration.narration.openedLabels.length>0&&narration.narration.closeCurrentLabel(),storage.storage.setTempVariable(`${su}${narration.narration.openedLabels.length}`,m),await narration.narration.call(f,e)):(storage.storage.setTempVariable(`${su}${narration.narration.openedLabels.length}`,m),await narration.narration.call(f,e));}c==="game_end"?(narration.narration.closeAllLabels(),await narration.narration.continue(e,{runNow:true})):c==="label_end"&&narration.narration.closeCurrentLabel(),h&&await narration.narration.continue(e,{runNow:true});}}};async function Ks(r,e={}){if(!Array.isArray(r))if(typeof r=="object"||typeof r=="string")r=[r];else {se.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let t=r.map(a=>{if(typeof a=="string")try{return JSON.parse(a)}catch(s){return se.error("Error parsing imported Pixi'VN JSON",s),{}}return a}),n=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)s.type==="value"&&(typeof s.value!="object"||!s.value||!("type"in s.value))&&au(s);return Promise.resolve()});await Promise.all(n);let i=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)(s.type!=="value"||s.type==="value"&&typeof s.value=="object"&&s.value&&"type"in s.value)&&au(s);if(a.labels){let s=a.labels;for(let o in s)try{let u=s[o],l=new Ad(o,u,void 0,e);narration.RegisteredLabels.add(l);}catch(u){se.error(`Error creating JSON label ${o}`,u);}}return Promise.resolve()});await Promise.all(i);}var xd={version:"1.13.12"};var hu=`https://pixi-vn.com/schemas/${xd.version}/schema.json`,cu=["==","!=","<","<=",">",">=","CONTAINS"];function Xs(){_.init({animateOperation:Kl,canvasElementOperation:zl,effectOperation:Ul,imageContainerOperation:Jl,imageOperation:Gl,textOperation:Hl,narrationOperation:Xl,loadAssets:Ml,soundOperation:Yl,videoOperation:$l,setStorageValue:Zl,setInitialStorageValue:eu,getLogichValue:exports.VariableGetter.getLogichValue,getConditionalStep:mi});}var gi="global decl",_t="___external_value___",Ci=/\[([^\]]+)\]/;function wd(r){oe.afterToTranslate=e=>du(e,r);}function _d(r){oe.beforeToTranslate=e=>du(e,r);}function du(r,e){let t=new RegExp(Ci.source,"g"),n=new Set,i=true;for(;i;){i=false;let a=[...r.matchAll(t)],s=new Set;for(let o of a){let u=o[1];if(s.has(u)||n.has(u))continue;s.add(u);let l=e(u);l!==void 0?(r=r.replaceAll(o[0],l),i=true):n.add(u);}}return r}var W;(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)))(W||={});var Td=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Od=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,Pd=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,Ys={Space_Separator:Td,ID_Start:Od,ID_Continue:Pd},ne={isSpaceSeparator(r){return typeof r=="string"&&Ys.Space_Separator.test(r)},isIdStartChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="$"||r==="_"||Ys.ID_Start.test(r))},isIdContinueChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="$"||r==="_"||r==="\u200C"||r==="\u200D"||Ys.ID_Continue.test(r))},isDigit(r){return typeof r=="string"&&/[0-9]/.test(r)},isHexDigit(r){return typeof r=="string"&&/[0-9A-Fa-f]/.test(r)}},Zs,Ee,ot,vi,pt,$e,le,na,bn,Fd=function(e,t){Zs=String(e),Ee="start",ot=[],vi=0,pt=1,$e=0,le=void 0,na=void 0,bn=void 0;do le=Nd(),kd[Ee]();while(le.type!=="eof");return typeof t=="function"?ea({"":bn},"",t):bn};function ea(r,e,t){let n=r[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let i=0;i<n.length;i++){let a=String(i),s=ea(n,a,t);s===void 0?delete n[a]:Object.defineProperty(n,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let i in n){let a=ea(n,i,t);a===void 0?delete n[i]:Object.defineProperty(n,i,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(r,e,n)}var V,I,Dn,at,L;function Nd(){for(V="default",I="",Dn=false,at=1;;){L=lt();let r=fu[V]();if(r)return r}}function lt(){if(Zs[vi])return String.fromCodePoint(Zs.codePointAt(vi))}function A(){let r=lt();return r===`
47
- `?(pt++,$e=0):r?$e+=r.length:$e++,r&&(vi+=r.length),r}var fu={default(){switch(L){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
48
- `:case "\r":case "\u2028":case "\u2029":A();return;case "/":A(),V="comment";return;case void 0:return A(),K("eof")}if(ne.isSpaceSeparator(L)){A();return}return fu[Ee]()},comment(){switch(L){case "*":A(),V="multiLineComment";return;case "/":A(),V="singleLineComment";return}throw X(A())},multiLineComment(){switch(L){case "*":A(),V="multiLineCommentAsterisk";return;case void 0:throw X(A())}A();},multiLineCommentAsterisk(){switch(L){case "*":A();return;case "/":A(),V="default";return;case void 0:throw X(A())}A(),V="multiLineComment";},singleLineComment(){switch(L){case `
49
- `:case "\r":case "\u2028":case "\u2029":A(),V="default";return;case void 0:return A(),K("eof")}A();},value(){switch(L){case "{":case "[":return K("punctuator",A());case "n":return A(),Tt("ull"),K("null",null);case "t":return A(),Tt("rue"),K("boolean",true);case "f":return A(),Tt("alse"),K("boolean",false);case "-":case "+":A()==="-"&&(at=-1),V="sign";return;case ".":I=A(),V="decimalPointLeading";return;case "0":I=A(),V="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=A(),V="decimalInteger";return;case "I":return A(),Tt("nfinity"),K("numeric",1/0);case "N":return A(),Tt("aN"),K("numeric",NaN);case '"':case "'":Dn=A()==='"',I="",V="string";return}throw X(A())},identifierNameStartEscape(){if(L!=="u")throw X(A());A();let r=ta();switch(r){case "$":case "_":break;default:if(!ne.isIdStartChar(r))throw pu();break}I+=r,V="identifierName";},identifierName(){switch(L){case "$":case "_":case "\u200C":case "\u200D":I+=A();return;case "\\":A(),V="identifierNameEscape";return}if(ne.isIdContinueChar(L)){I+=A();return}return K("identifier",I)},identifierNameEscape(){if(L!=="u")throw X(A());A();let r=ta();switch(r){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!ne.isIdContinueChar(r))throw pu();break}I+=r,V="identifierName";},sign(){switch(L){case ".":I=A(),V="decimalPointLeading";return;case "0":I=A(),V="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=A(),V="decimalInteger";return;case "I":return A(),Tt("nfinity"),K("numeric",at*(1/0));case "N":return A(),Tt("aN"),K("numeric",NaN)}throw X(A())},zero(){switch(L){case ".":I+=A(),V="decimalPoint";return;case "e":case "E":I+=A(),V="decimalExponent";return;case "x":case "X":I+=A(),V="hexadecimal";return}return K("numeric",at*0)},decimalInteger(){switch(L){case ".":I+=A(),V="decimalPoint";return;case "e":case "E":I+=A(),V="decimalExponent";return}if(ne.isDigit(L)){I+=A();return}return K("numeric",at*Number(I))},decimalPointLeading(){if(ne.isDigit(L)){I+=A(),V="decimalFraction";return}throw X(A())},decimalPoint(){switch(L){case "e":case "E":I+=A(),V="decimalExponent";return}if(ne.isDigit(L)){I+=A(),V="decimalFraction";return}return K("numeric",at*Number(I))},decimalFraction(){switch(L){case "e":case "E":I+=A(),V="decimalExponent";return}if(ne.isDigit(L)){I+=A();return}return K("numeric",at*Number(I))},decimalExponent(){switch(L){case "+":case "-":I+=A(),V="decimalExponentSign";return}if(ne.isDigit(L)){I+=A(),V="decimalExponentInteger";return}throw X(A())},decimalExponentSign(){if(ne.isDigit(L)){I+=A(),V="decimalExponentInteger";return}throw X(A())},decimalExponentInteger(){if(ne.isDigit(L)){I+=A();return}return K("numeric",at*Number(I))},hexadecimal(){if(ne.isHexDigit(L)){I+=A(),V="hexadecimalInteger";return}throw X(A())},hexadecimalInteger(){if(ne.isHexDigit(L)){I+=A();return}return K("numeric",at*Number(I))},string(){switch(L){case "\\":A(),I+=Id();return;case '"':if(Dn)return A(),K("string",I);I+=A();return;case "'":if(!Dn)return A(),K("string",I);I+=A();return;case `
50
- `:case "\r":throw X(A());case "\u2028":case "\u2029":Rd(L);break;case void 0:throw X(A())}I+=A();},start(){switch(L){case "{":case "[":return K("punctuator",A())}V="value";},beforePropertyName(){switch(L){case "$":case "_":I=A(),V="identifierName";return;case "\\":A(),V="identifierNameStartEscape";return;case "}":return K("punctuator",A());case '"':case "'":Dn=A()==='"',V="string";return}if(ne.isIdStartChar(L)){I+=A(),V="identifierName";return}throw X(A())},afterPropertyName(){if(L===":")return K("punctuator",A());throw X(A())},beforePropertyValue(){V="value";},afterPropertyValue(){switch(L){case ",":case "}":return K("punctuator",A())}throw X(A())},beforeArrayValue(){if(L==="]")return K("punctuator",A());V="value";},afterArrayValue(){switch(L){case ",":case "]":return K("punctuator",A())}throw X(A())},end(){throw X(A())}};function K(r,e){return {type:r,value:e,line:pt,column:$e}}function Tt(r){for(let e of r){if(lt()!==e)throw X(A());A();}}function Id(){switch(lt()){case "b":return A(),"\b";case "f":return A(),"\f";case "n":return A(),`
51
- `;case "r":return A(),"\r";case "t":return A()," ";case "v":return A(),"\v";case "0":if(A(),ne.isDigit(lt()))throw X(A());return "\0";case "x":return A(),Vd();case "u":return A(),ta();case `
52
- `:case "\u2028":case "\u2029":return A(),"";case "\r":return A(),lt()===`
53
- `&&A(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw X(A());case void 0:throw X(A())}return A()}function Vd(){let r="",e=lt();if(!ne.isHexDigit(e)||(r+=A(),e=lt(),!ne.isHexDigit(e)))throw X(A());return r+=A(),String.fromCodePoint(parseInt(r,16))}function ta(){let r="",e=4;for(;e-- >0;){let t=lt();if(!ne.isHexDigit(t))throw X(A());r+=A();}return String.fromCodePoint(parseInt(r,16))}var kd={start(){if(le.type==="eof")throw Ot();Qs();},beforePropertyName(){switch(le.type){case "identifier":case "string":na=le.value,Ee="afterPropertyName";return;case "punctuator":yi();return;case "eof":throw Ot()}},afterPropertyName(){if(le.type==="eof")throw Ot();Ee="beforePropertyValue";},beforePropertyValue(){if(le.type==="eof")throw Ot();Qs();},beforeArrayValue(){if(le.type==="eof")throw Ot();if(le.type==="punctuator"&&le.value==="]"){yi();return}Qs();},afterPropertyValue(){if(le.type==="eof")throw Ot();switch(le.value){case ",":Ee="beforePropertyName";return;case "}":yi();}},afterArrayValue(){if(le.type==="eof")throw Ot();switch(le.value){case ",":Ee="beforeArrayValue";return;case "]":yi();}},end(){}};function Qs(){let r;switch(le.type){case "punctuator":switch(le.value){case "{":r={};break;case "[":r=[];break}break;case "null":case "boolean":case "numeric":case "string":r=le.value;break}if(bn===void 0)bn=r;else {let e=ot[ot.length-1];Array.isArray(e)?e.push(r):Object.defineProperty(e,na,{value:r,writable:true,enumerable:true,configurable:true});}if(r!==null&&typeof r=="object")ot.push(r),Array.isArray(r)?Ee="beforeArrayValue":Ee="beforePropertyName";else {let e=ot[ot.length-1];e==null?Ee="end":Array.isArray(e)?Ee="afterArrayValue":Ee="afterPropertyValue";}}function yi(){ot.pop();let r=ot[ot.length-1];r==null?Ee="end":Array.isArray(r)?Ee="afterArrayValue":Ee="afterPropertyValue";}function X(r){return Si(r===void 0?`JSON5: invalid end of input at ${pt}:${$e}`:`JSON5: invalid character '${mu(r)}' at ${pt}:${$e}`)}function Ot(){return Si(`JSON5: invalid end of input at ${pt}:${$e}`)}function pu(){return $e-=5,Si(`JSON5: invalid identifier character at ${pt}:${$e}`)}function Rd(r){console.warn(`JSON5: '${mu(r)}' in strings is not valid ECMAScript; consider escaping`);}function mu(r){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[r])return e[r];if(r<" "){let t=r.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return r}function Si(r){let e=new SyntaxError(r);return e.lineNumber=pt,e.columnNumber=$e,e}var Ld=function(e,t,n){let i=[],a="",s,o,u="",l;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,l=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let g of t){let b;typeof g=="string"?b=g:(typeof g=="number"||g instanceof String||g instanceof Number)&&(b=String(g)),b!==void 0&&s.indexOf(b)<0&&s.push(b);}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),u=" ".substr(0,n)):typeof n=="string"&&(u=n.substr(0,10)),h("",{"":e});function h(g,b){let S=b[g];switch(S!=null&&(typeof S.toJSON5=="function"?S=S.toJSON5(g):typeof S.toJSON=="function"&&(S=S.toJSON(g))),o&&(S=o.call(b,g,S)),S instanceof Number?S=Number(S):S instanceof String?S=String(S):S instanceof Boolean&&(S=S.valueOf()),S){case null:return "null";case true:return "true";case false:return "false"}if(typeof S=="string")return c(S);if(typeof S=="number")return String(S);if(typeof S=="object")return Array.isArray(S)?m(S):d(S)}function c(g){let b={"'":.1,'"':.2},S={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},y="";for(let D=0;D<g.length;D++){let C=g[D];switch(C){case "'":case '"':b[C]++,y+=C;continue;case "\0":if(ne.isDigit(g[D+1])){y+="\\x00";continue}}if(S[C]){y+=S[C];continue}if(C<" "){let E=C.charCodeAt(0).toString(16);y+="\\x"+("00"+E).substring(E.length);continue}y+=C;}let p=l||Object.keys(b).reduce((D,C)=>b[D]<b[C]?D:C);return y=y.replace(new RegExp(p,"g"),S[p]),p+y+p}function d(g){if(i.indexOf(g)>=0)throw TypeError("Converting circular structure to JSON5");i.push(g);let b=a;a=a+u;let S=s||Object.keys(g),y=[];for(let D of S){let C=h(D,g);if(C!==void 0){let E=f(D)+":";u!==""&&(E+=" "),E+=C,y.push(E);}}let p;if(y.length===0)p="{}";else {let D;if(u==="")D=y.join(","),p="{"+D+"}";else {let C=`,
54
- `+a;D=y.join(C),p=`{
55
- `+a+D+`,
56
- `+b+"}";}}return i.pop(),a=b,p}function f(g){if(g.length===0)return c(g);let b=String.fromCodePoint(g.codePointAt(0));if(!ne.isIdStartChar(b))return c(g);for(let S=b.length;S<g.length;S++)if(!ne.isIdContinueChar(String.fromCodePoint(g.codePointAt(S))))return c(g);return g}function m(g){if(i.indexOf(g)>=0)throw TypeError("Converting circular structure to JSON5");i.push(g);let b=a;a=a+u;let S=[];for(let p=0;p<g.length;p++){let D=h(String(p),g);S.push(D!==void 0?D:"null");}let y;if(S.length===0)y="[]";else if(u==="")y="["+S.join(",")+"]";else {let p=`,
57
- `+a,D=S.join(p);y=`[
58
- `+a+D+`,
59
- `+b+"]";}return i.pop(),a=b,y}},Bd={parse:Fd,stringify:Ld},Wd=Bd,An=Wd;var Cu="\xA7SPACE\xA7",yu="\xA7DOUBLE_QUOTES\xA7",vu="\xA7QUOTES\xA7",Su="SPECIAL_\xA7QUOTES\xA7",Eu="\xA7CURLY_BRACKETS1\xA7",jd="\xA7INK_VAR\xA7",Du="\xA7CURLY_BRACKETS2\xA7";exports.HashtagCommands=void 0;(y=>{let r=[],e=[];async function t(p,D){for(let C=0;C<r.length;C++)try{let{validation:E}=r[C].opts;if(E instanceof RegExp){if(!E.test(p.join(" ")))continue}else if(E instanceof v.ZodType&&!E.safeParse(p).success)continue;let w=await r[C].fn(p,D,c);if(w===!0||typeof w=="string")return w}catch{}return false}function n(p,D={name:"custom-command",validation:/^/}){r.unshift({fn:p,opts:D});}y.add=n;function i(){return [...e.map(p=>p.opts),...r.map(p=>p.opts)]}y.info=i;function a(p,D){e.unshift({fn:p,opts:D});}y.addMapper=a;function s(){r.length=0;}y.clear=s;function o(){e.length=0;}y.clearMappers=o;async function u(p,D,C){try{let E=l(p),w=await t(E,C);return w===!0?void 0:typeof w=="string"?(w.startsWith("#")&&(w=w.substring(1)),await y.run(w,D,C)):h(E,D)}catch(E){throw W.error("Error parsing ink hashtag-command",p),E}}y.run=u;function l(p,D){if(p=p.replaceAll('\\"',yu),p=p.replaceAll("\\'",vu),p=p.replaceAll("\\`",Su),p=p.replaceAll("\\{",Eu),p=p.replaceAll("\\}",Du),D?.mergeInkVariables){let P;do P=p,p=p.replace(/\{[^{}:]*\}/g,jd);while(p!==P)}p=p.replaceAll("{"," { "),p=p.replaceAll("}"," } "),p=p.replaceAll(Eu,"{"),p=p.replaceAll(Du,"}");let C=[],E,w="";for(let P=0;P<p.length;P++){let N=p[P];N==='"'||N==="'"||N==="`"?E===void 0?(C.push(w),w="",E=N,w+=N):E===N?(E=void 0,w+=N,C.push(w),w=""):w+=N:w+=N;}return w!==""&&C.push(w),C.forEach((P,N)=>{N%2===1&&(C[N]=P.replaceAll(" ",Cu));}),p=C.join(""),C=p.split(" ").filter(P=>P!==""),C=C.map(P=>P.replaceAll(Cu," ").replaceAll(yu,'"').replaceAll(vu,"'").replaceAll(Su,"`")),C=g(C),C=C.map(P=>P.startsWith('"')&&P.endsWith('"')||P.startsWith("'")&&P.endsWith("'")||P.startsWith("`")&&P.endsWith("`")?P.slice(1,-1):P),C}y.convertTagTolist=l;function h(p,D,C){for(let E of e){let{validation:w}=E.opts,P=false;if(w instanceof RegExp?P=w.test(p.join(" ")):w instanceof v.ZodType&&(P=w.safeParse(p).success),P)return E.fn(p,D)}C?.silent||W.error("The operation is not valid",p);}y.convertOperation=h;function c(p){return d(p)}y.convertListStringToObj=c;function d(p){if(p.length===0)return {};if(p.length%2!==0)throw W.error("The props list must have a pair number of elements",p),new Error("The props list must have a pair number of elements");let D="{";p.forEach((C,E)=>{if(E%2===0)D+=`"${C}": `;else {switch(C){case "null":case "undefined":case "true":case "false":D+=`${C}`;break;default:m(C)?(C=f(C),D+=`"${C}"`):C.startsWith("{")&&C.endsWith("}")?D+=`${C}`:C.startsWith('"')&&C.endsWith('"')?D+=`${C}`:Number.isNaN(parseFloat(C))?D+=`"${C}"`:D+=`${C}`;}E<p.length-1&&(D+=", ");}}),D+="}";try{return An.parse(D)}catch(C){throw W.error("Error parsing ink json",D),C}}function f(p){return p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'")||p.startsWith("`")&&p.endsWith("`")?p.substring(1,p.length-1):p}function m(p){return !!(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'")||p.startsWith("`")&&p.endsWith("`"))}function g(p){return b(p).tokens}y.mergeJsonBlocks=g;function b(p){let D=[],C=false;for(let E=0;E<p.length;E++){let w=p[E];if(w!=="{"){D.push(w);continue}let P=S(p,E);if(P===-1){D.push(w);continue}let N=b(p.slice(E+1,P)),Z=["{",...N.tokens,"}"],ve=Z.join(" ");if(!N.hasInvalidMatchedBlock)try{An.parse(ve),D.push(ve),E=P;continue}catch{}C=true,D.push(...Z),E=P;}return {tokens:D,hasInvalidMatchedBlock:C}}function S(p,D){let C=0;for(let E=D;E<p.length;E++)if(p[E]==="{")C++;else if(p[E]==="}"&&(C--,C===0))return E;return -1}})(exports.HashtagCommands||={});function qd(r){exports.HashtagCommands.add(r);}function Md(r={}){function e(l){return l&&l.length>0?v__default.default.enum(Object.fromEntries(l.map(h=>[h,h]))):v__default.default.string()}exports.HashtagCommands.addMapper((l,h)=>{h.labelToOpen={label:l[1],type:"call"},h.goNextStep=void 0;},{name:"Call",description:"Calls the label specified by the second token, then returns to the current position.\n\n```ink\n# call label_name\n```",validation:v__default.default.tuple([v__default.default.literal("call"),v__default.default.string()])}),exports.HashtagCommands.addMapper((l,h)=>{h.labelToOpen={label:l[1],type:"jump"},h.goNextStep=void 0;},{name:"Jump",description:"Jumps to the label specified by the second token without returning.\n\n```ink\n# jump label_name\n```",validation:v__default.default.tuple([v__default.default.literal("jump"),v__default.default.string()])}),exports.HashtagCommands.addMapper((l,h)=>("dialogue"in h&&delete h.dialogue,"goNextStep"in h&&delete h.goNextStep,{type:"dialogue",operationType:"clean"}),{name:"Pause",description:"Clears the current dialogue and waits for user input before advancing.\n\n```ink\n# pause\n```",validation:v__default.default.tuple([v__default.default.literal("pause")])}),exports.HashtagCommands.addMapper((l,h)=>{h.goNextStep=true,h.glueEnabled=false;},{name:"Continue",description:"Forces the story to proceed to the next step automatically.\n\n```ink\n# continue\n```",validation:v__default.default.tuple([v__default.default.literal("continue")])}),exports.HashtagCommands.addMapper(l=>({type:"video",operationType:l[0],alias:l[2]}),{name:"Pause/Resume video",description:"Pauses or resumes a video canvas element identified by its alias.\n\n```ink\n# pause video <alias>\n# resume video <alias>\n```",validation:v__default.default.tuple([v__default.default.enum(["pause","resume"]),v__default.default.literal("video"),v__default.default.string()])}),exports.HashtagCommands.addMapper(l=>({type:l[1],operationType:l[0],aliases:l.slice(2)}),{name:"Load assets/bundle",description:`Loads (eagerly or lazily) a set of asset or bundle aliases.
40
+ ~ myFunction()`);let l=(0, xt.asOrNull)(o,Ws.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(Ws.FunctionCall)()!==null&&(o=new Ve.ContentList(o,new dt.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 vn.NumberExpression||u instanceof li.StringExpression||u instanceof xl.DivertTarget||u instanceof Ol.VariableReference||u instanceof dc.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 li.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new _l.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 ui.Identifier(o.name),new _l.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new CC.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 yC.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 vn.NumberExpression||l instanceof xl.DivertTarget||l instanceof li.StringExpression?l instanceof li.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 lC.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new dC.Glue(new fC.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, xt.asOrNull)(l,Ve.ContentList);return u||(u=new Ve.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 gc.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 ui.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 pe.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=ce.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 gc.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 ce.SequenceType.Once:case ce.SequenceType.Cycle:case ce.SequenceType.Stopping:case ce.SequenceType.Shuffle:case ce.SequenceType.Shuffle|ce.SequenceType.Stopping:case ce.SequenceType.Shuffle|ce.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),ce.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new pe.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":s|=ce.SequenceType.Once;break;case "&":s|=ce.SequenceType.Cycle;break;case "~":s|=ce.SequenceType.Shuffle;break;case "$":s|=ce.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=ce.SequenceType.Once;break;case "cycle":s=ce.SequenceType.Cycle;break;case "shuffle":s=ce.SequenceType.Shuffle;break;case "stopping":s=ce.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 Ve.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 Ve.ContentList(h)),l=true;}return l||o.push(new Ve.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(Ae.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new dt.Text(`
42
+ `)),new Ve.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===Ae.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===Ae.StatementLevel.Top&&l instanceof mc.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(Ae.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>=Ae.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>Ae.StatementLevel.InnerBlock&&l.push(this.Gather),o>=Ae.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<=Ae.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=Ae.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=Ae.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(),pt.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 Ve.ContentList;o.AddContent(new yn.Tag(false)),o.AddContent(new yn.Tag(true)),s=o;}else s=new yn.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new pe.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?pt.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?pt.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?pt.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?pt.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?pt.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=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new bC.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(e){return new aC.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(Bs.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(Bs.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(Bs.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(Bs.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new pe.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(e){this.tagActive&&(e!=null&&(e instanceof Ve.ContentList?e.AddContent(new yn.Tag(false)):e.push(new yn.Tag(false))),this.tagActive=false);}};qs.InkParser=K;K.LatinBasic=He.CharacterRange.Define("A","z",new pe.CharacterSet().AddRange("[","`"));K.LatinExtendedA=He.CharacterRange.Define("\u0100","\u017F");K.LatinExtendedB=He.CharacterRange.Define("\u0180","\u024F");K.Greek=He.CharacterRange.Define("\u0370","\u03FF",new pe.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));K.Cyrillic=He.CharacterRange.Define("\u0400","\u04FF",new pe.CharacterSet().AddRange("\u0482","\u0489"));K.Armenian=He.CharacterRange.Define("\u0530","\u058F",new pe.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));K.Hebrew=He.CharacterRange.Define("\u0590","\u05FF",new pe.CharacterSet);K.Arabic=He.CharacterRange.Define("\u0600","\u06FF",new pe.CharacterSet);K.Korean=He.CharacterRange.Define("\uAC00","\uD7AF",new pe.CharacterSet);K.Latin1Supplement=He.CharacterRange.Define("\x80","\xFF",new pe.CharacterSet);K.Chinese=He.CharacterRange.Define("\u4E00","\u9FFF",new pe.CharacterSet);K.ListAllCharacterRanges=()=>[K.LatinBasic,K.LatinExtendedA,K.LatinExtendedB,K.Arabic,K.Armenian,K.Cyrillic,K.Greek,K.Hebrew,K.Korean,K.Latin1Supplement,K.Chinese];});var Sc=x(Ms=>{Object.defineProperty(Ms,"__esModule",{value:true});Ms.GenerateStoryStats=void 0;var AC=sn(),wC=un(),xC=Mn(),_C=Ho(),OC=Qo(),PC=Et();function TC(r){let e=r.FindAll(PC.Text)(),t=0;for(let l of e){let u=0,h=true;for(let c of l.text)c==" "||c==" "||c==`
44
+ `||c=="\r"?h=true:h&&(u++,h=false);t+=u;}let n=r.FindAll(_C.Knot)(),i=r.FindAll(OC.Stitch)(),a=r.FindAll(AC.Choice)(),s=r.FindAll(xC.Gather)(l=>l.debugMetadata!=null),o=r.FindAll(wC.Divert)();return {words:t,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:i.length,gathers:s.length,diverts:o.length-1,choices:a.length}}Ms.GenerateStoryStats=TC;});var Ec=x(Gs=>{Object.defineProperty(Gs,"__esModule",{value:true});Gs.JsonFileHandler=void 0;var Tl=class{constructor(e){this.fileHierarchy=e,this.ResolveInkFilename=t=>{if(Object.keys(this.fileHierarchy).includes(t))return t;throw new Error(`Cannot locate ${t}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=t=>{if(Object.keys(this.fileHierarchy).includes(t))return this.fileHierarchy[t];throw new Error(`Cannot open ${t}.`)};}};Gs.JsonFileHandler=Tl;});var bc=x(ye=>{Object.defineProperty(ye,"__esModule",{value:true});ye.Compiler=ye.Story=ye.InkList=ye.JsonFileHandler=ye.StatementLevel=ye.InkParser=ye.CompilerOptions=void 0;var FC=da(),NC=Fu(),Fl=Ut(),IC=Pl(),VC=ee(),kC=z(),RC=Sc(),LC=da();Object.defineProperty(ye,"CompilerOptions",{enumerable:true,get:function(){return LC.CompilerOptions}});var BC=Pl();Object.defineProperty(ye,"InkParser",{enumerable:true,get:function(){return BC.InkParser}});var WC=Xo();Object.defineProperty(ye,"StatementLevel",{enumerable:true,get:function(){return WC.StatementLevel}});var jC=Ec();Object.defineProperty(ye,"JsonFileHandler",{enumerable:true,get:function(){return jC.JsonFileHandler}});var Dc=Qn();Object.defineProperty(ye,"InkList",{enumerable:true,get:function(){return Dc.InkList}});Object.defineProperty(ye,"Story",{enumerable:true,get:function(){return Dc.Story}});var Nl=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(e,t=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new IC.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, kC.asOrNull)(i,VC.StringValue);if(a!==null){let s=new NC.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, RC.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 Fl.ErrorType.Author:this._authorMessages.push(n);break;case Fl.ErrorType.Warning:this._warnings.push(n);break;case Fl.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=e,this._options=t||new FC.CompilerOptions;}};ye.Compiler=Nl;});var Se;(r=>(r.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),r.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),r.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),r.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Se||={});var _=class q{static init(e){e.loadAssets&&(q._loadAssets=e.loadAssets),e.soundOperation&&(q._soundOperation=e.soundOperation),e.imageOperation&&(q._imageOperation=e.imageOperation),e.videoOperation&&(q._videoOperation=e.videoOperation),e.imageContainerOperation&&(q._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(q._textOperation=e.textOperation),e.canvasElementOperation&&(q._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(q._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(q._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(q._narrationOperation=e.narrationOperation),e.effectOperation&&(q._effectOperation=e.effectOperation),e.animateOperation&&(q._animateOperation=e.animateOperation),e.canvasOperation&&(q._canvasOperation=e.canvasOperation),e.getLogichValue&&(q._getLogichValue=e.getLogichValue),e.getConditionalStep&&(q._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return q._loadAssets}static _soundOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return q._soundOperation}static _imageOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return q._imageOperation}static _videoOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return q._videoOperation}static _imageContainerOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return q._imageContainerOperation}static _textOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return q._textOperation}static _canvasElementOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return q._canvasElementOperation}static _setStorageValue=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return q._setStorageValue}static _setInitialStorageValue=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return q._setInitialStorageValue}static _narrationOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return q._narrationOperation}static _effectOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return q._effectOperation}static _animateOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return q._animateOperation}static _canvasOperation=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return q._canvasOperation}static _getLogichValue=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return q._getLogichValue}static _getConditionalStep=()=>{throw Se.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return q._getConditionalStep}};exports.TextReplaces=void 0;(r=>{r.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(u,h){e.unshift({fn:u,opts:h});}r.add=t;function n(u){let h=e.findIndex(c=>c.fn===u);h!==-1&&e.splice(h,1);}r.remove=n;function i(){return e.map(u=>u.opts)}r.info=i;function a(u,h){let c=e.filter(p=>(p.opts.type??"after-translation")===h.type);for(let p of c)u=l(u,p.fn,p.opts.validation);return u}r.replace=a;function s(u){let h=e.filter(c=>c.opts.i18nInterpolation);for(let c of h)u=o(u,c.fn,c.opts);return u}r.runI18nPreStep=s;function o(u,h,c){let{validation:p}=c,d=new RegExp(r.options.replaceRegex.source,"g"),f=[...u.matchAll(d)],g=new Set,b=[];for(let D of f)g.has(D[1])||(g.add(D[1]),b.push(D[1]));for(let D of b){if(p==="characterId"){if(!characters.RegisteredCharacters.has(D))continue}else if(p!=="all"){if(p instanceof RegExp){if(!p.test(D))continue}else if(p instanceof S.ZodType&&!p.safeParse(D).success)continue}h(D)!==void 0&&(u.includes(`{{[${D}]}}`)||(u=u.replaceAll(`[${D}]`,`{{[${D}]}}`)));}return u}function l(u,h,c){let p=new RegExp(r.options.replaceRegex.source,"g"),d=[...u.matchAll(p)],f=new Set,g=[];for(let b of d)f.has(b[1])||(f.add(b[1]),g.push(b[1]));for(let b of g){if(c==="characterId"){if(!characters.RegisteredCharacters.has(b))continue}else if(c!=="all"){if(c instanceof RegExp){if(!c.test(b))continue}else if(c instanceof S.ZodType&&!c.safeParse(b).success)continue}let D=h(b);D!==void 0&&(u=u.replaceAll(`[${b}]`,D));}return u}})(exports.TextReplaces||={});function kc(r,e={}){let t="";return r.values.forEach(n=>{if(typeof n=="string")t+=n;else {let i=_.getLogichValue(n,e);t+=`${i}`;}}),t}var jl;(r=>{let e=l=>l;function t(l){return Array.isArray(l)?l.map(u=>n(`${u}`)):n(`${l}`)}r.t=t;function n(l){let u=l;return r.beforeToTranslate&&(u=(0, r.beforeToTranslate)(u)),u=exports.TextReplaces.replace(u,{type:"before-translation"}),u=e(u),r.afterToTranslate&&(u=(0, r.afterToTranslate)(u)),u=exports.TextReplaces.replace(u,{type:"after-translation"}),u}r.translate=n;function i(l){e=l;}r.setTranslate=i;function a(l,u,h){let{defaultValue:c="empty_string"}=h;typeof u=="string"&&(u=[u]),Array.isArray(u)&&u.forEach(p=>{let d=p;if(r.beforeToTranslate&&(d=(0, r.beforeToTranslate)(d)),c==="empty_string")l[d]===void 0&&(l[d]="");else if(c==="copy_key"){let f=p;r.beforeToTranslate&&(f=(0, r.beforeToTranslate)(f));let g=exports.TextReplaces.runI18nPreStep(f);g=exports.TextReplaces.replace(g,{type:"before-translation"}),l[d]=g;}});}function s(l,u=[]){if(typeof l=="object"&&l&&"type"in l)if(l.type==="ifelse")l.then&&s(l.then,u),l.else&&s(l.else,u);else if(l.type==="stepswitch"){if(l.elements)if(Array.isArray(l.elements))l.elements.forEach(h=>{s(h,u);});else if(l.elements.type==="ifelse"){let h=[];s(l.elements,h),h.forEach(c=>{u.push(...c);});}else if(l.elements.type==="stepswitch"){let h=[];s(l.elements,h),h.forEach(c=>{u.push(...c);});}else s(l.elements,u);}else l.type==="resulttocombine"?(l.firstItem&&s(l.firstItem,u),l.secondConditionalItem&&l.secondConditionalItem.forEach(h=>{s(h,u);})):u.push(l);else l&&u.push(l);return u}async function o(l,u={},h={}){let{defaultValue:c="copy_key",operationStringConvert:p}=h,d=l.map(async f=>{if(f.choices){let g=[];Array.isArray(f.choices)?g=[f.choices]:g=s(f.choices),g.forEach(b=>{b.forEach(D=>{if("type"in D){let y=[];D.type==="ifelse"||D.type==="stepswitch"?s(D,y):y=[D],y.map(m=>s(m.text)).forEach(m=>{Array.isArray(m)&&m.forEach(C=>{Array.isArray(C)?C.forEach(v=>{typeof v=="string"?a(u,v,{defaultValue:c}):s(v).forEach(E=>{Array.isArray(E)?E.forEach(w=>{typeof w=="string"&&a(u,w,{defaultValue:c});}):typeof E=="string"&&a(u,E,{defaultValue:c});});}):typeof C=="string"&&a(u,C,{defaultValue:c});});});}});});}if(f.dialogue){let g=[];Array.isArray(f.dialogue)?g=[f.dialogue]:g=s(f.dialogue),g.forEach(b=>{if(typeof b=="string")a(u,b,{defaultValue:c});else if("text"in b){let D=s(b.text);typeof D=="string"&&(D=[D]),D.forEach(y=>{typeof y=="string"?a(u,y,{defaultValue:c}):s(y).forEach(m=>{typeof m=="string"?a(u,m,{defaultValue:c}):Array.isArray(m)&&m.forEach(C=>{typeof C=="string"?a(u,C,{defaultValue:c}):s(C).forEach(v=>{typeof v=="string"&&a(u,v,{defaultValue:c});});});});});}});}if(f.operations)for(let g of f.operations){if(g.type==="operationtoconvert"&&p){let b=kc(g),D=await p(b,f,{});if(!D)return;g=D;}g.type==="text"&&g.operationType==="show"&&a(u,g.text,{defaultValue:c});}f.conditionalStep&&s(f.conditionalStep).forEach(g=>{Array.isArray(g)?o(g,u,h):o([g],u,h);});});return await Promise.all(d),u}r.generateJsonTranslation=o;})(jl||={});var oe=jl;async function ql(r){let e=_.getLogichValue(r,{});if(e)switch(e.type){case "assets":switch(e.operationType){case "load":await canvas.Assets.load(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoad(e.aliases);break}break;case "bundle":switch(e.operationType){case "load":await canvas.Assets.loadBundle(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoadBundle(e.aliases);break}break}}var G;(r=>(r.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),r.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),r.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),r.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(G||={});async function fi(r,e,t){switch(t.type){case "fade":await canvas.showWithFade(e.alias,r,t.props,t.priority);break;case "dissolve":await canvas.showWithDissolve(e.alias,r,t.props,t.priority);break;case "movein":case "moveout":await canvas.moveIn(e.alias,r,t.props,t.priority);break;case "zoomin":case "zoomout":await canvas.zoomIn(e.alias,r,t.props,t.priority);break;case "pushin":case "pushout":await canvas.pushIn(e.alias,r,t.props,t.priority);break}}function Sn(r){if(r.transition)switch(r.transition.type){case "fade":canvas.removeWithFade(r.alias,r.transition.props,r.transition.priority);break;case "dissolve":canvas.removeWithDissolve(r.alias,r.transition.props,r.transition.priority);break;case "movein":case "moveout":canvas.moveOut(r.alias,r.transition.props,r.transition.priority);break;case "zoomin":case "zoomout":canvas.zoomOut(r.alias,r.transition.props,r.transition.priority);break;case "pushin":case "pushout":canvas.pushOut(r.alias,r.transition.props,r.transition.priority);break}else canvas.canvas.remove(r.alias);}async function Ml(r){switch(r.operationType){case "show":if(r.transition){let e=new canvas.ImageSprite(r.props,r.url||r.alias);await fi(e,r,r.transition);}else await canvas.showImage(r.alias,r.url,r.props);break;case "edit":{let e=canvas.canvas.find(r.alias);e?r.props&&await e.setMemory({...e.memory,...r.props}):G.error(`Image with alias ${r.alias} not found.`);break}case "remove":Sn(r);break}}async function Gl(r){switch(r.operationType){case "show":if(r.transition){let e=new canvas.VideoSprite(r.props,r.url||r.alias);await fi(e,r,r.transition);}else await canvas.showVideo(r.alias,r.url,r.props);break;case "edit":{let e=canvas.canvas.find(r.alias);e?r.props&&await e.setMemory({...e.memory,...r.props}):G.error(`Video with alias ${r.alias} not found.`);break}case "remove":Sn(r);break;case "pause":case "resume":{let e=canvas.canvas.find(r.alias);e?e.paused=r.operationType==="pause":G.error(`Video with alias ${r.alias} not found.`);break}}}async function $l(r){switch(r.operationType){case "show":if(r.transition){let e=new canvas.ImageContainer(r.props,r.urls);await fi(e,r,r.transition);}else await canvas.showImageContainer(r.alias,r.urls,r.props);break;case "edit":{let e=canvas.canvas.find(r.alias);e?r.props&&await e.setMemory({...e.memory,...r.props}):G.error(`ImageContainer with alias ${r.alias} not found.`);break}case "remove":Sn(r);break}}async function Jl(r){switch(r.operationType){case "show":if(r.props=r.props||{},r.props.text=oe.t(r.text),r.transition){let e=new canvas.Text(r.props);await fi(e,r,r.transition);}else canvas.showText(r.alias,r.text,r.props);break;case "edit":{let e=canvas.canvas.find(r.alias);e?r.props&&await e.setMemory({...e.memory,...r.props}):G.error(`Text with alias ${r.alias} not found.`);break}case "remove":Sn(r);break}}async function Hl(r){switch(r.operationType){case "edit":try{let e=canvas.canvas.find(r.alias);e?r.props&&e.setMemory({...e.memory,...r.props}):G.error(`Canvas Element with alias ${r.alias} not found.`);}catch(e){G.error(`There was an error while trying to edit the canvas element with alias ${r.alias}.`,e);}break;case "remove":Sn(r);break}}function zl(r){r.operationType==="clear"&&canvas.canvas.removeAll();}async function Ul(r){r.type==="shake"&&await canvas.shakeEffect(r.alias,r.props,r.priority);}function Kl(r){switch(r.type){case "animate":canvas.canvas.animate(r.alias,r.keyframes,r.options,r.priority);break;case "animate-sequence":canvas.canvas.animate(r.alias,r.sequence,r.options,r.priority);break}}function Xl(r){switch(r.type){case "input":narration.narration.requestInput({type:r.valueType},r.defaultValue);break;case "dialogue":narration.narration.dialogue=void 0;break}}function Yl(r){switch(r.operationType){case "play":r.url?sound.sound.play(r.alias,r.url,r.props):sound.sound.play(r.alias,r.props);break;case "stop":switch(r.type){case "sound":sound.sound.stop(r.alias);break;case "all":sound.sound.stopAll();break}break;case "pause":switch(r.type){case "sound":sound.sound.pause(r.alias);break;case "channel":sound.sound.findChannel(r.alias).pauseAll();break;case "all":sound.sound.pauseAll();break}break;case "resume":switch(r.type){case "sound":sound.sound.resume(r.alias);break;case "channel":sound.sound.findChannel(r.alias).resumeAll();break;case "all":sound.sound.resumeAll();break}break;case "edit":Object.entries(r.props).forEach(([e,t])=>{let n=sound.sound.find(r.alias);n&&(e==="volume"?n.volume.value=t:n.paused=t);});break}}var zs="___param___",np=class M{static init(e){e.loadAssets&&(M._loadAssets=e.loadAssets),e.soundOperation&&(M._soundOperation=e.soundOperation),e.imageOperation&&(M._imageOperation=e.imageOperation),e.videoOperation&&(M._videoOperation=e.videoOperation),e.imageContainerOperation&&(M._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(M._textOperation=e.textOperation),e.canvasElementOperation&&(M._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(M._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(M._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(M._narrationOperation=e.narrationOperation),e.effectOperation&&(M._effectOperation=e.effectOperation),e.animateOperation&&(M._animateOperation=e.animateOperation),e.canvasOperation&&(M._canvasOperation=e.canvasOperation),e.getLogichValue&&(M._getLogichValue=e.getLogichValue),e.getConditionalStep&&(M._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return M._loadAssets}static _soundOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return M._soundOperation}static _imageOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return M._imageOperation}static _videoOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return M._videoOperation}static _imageContainerOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return M._imageContainerOperation}static _textOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return M._textOperation}static _canvasElementOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return M._canvasElementOperation}static _setStorageValue=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return M._setStorageValue}static _setInitialStorageValue=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return M._setInitialStorageValue}static _narrationOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return M._narrationOperation}static _effectOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return M._effectOperation}static _animateOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return M._animateOperation}static _canvasOperation=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return M._canvasOperation}static _getLogichValue=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return M._getLogichValue}static _getConditionalStep=()=>{throw G.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return M._getConditionalStep}};function ip(r,e){if(e&&typeof e=="object"&&typeof r.functionName=="string"&&r.functionName in e){let t=e[r.functionName];if(typeof t=="function"){let n=r.args.map(i=>np.getLogichValue(i,e));return t(...n)}else G.warn(`getLogichValue function ${r.functionName} not found in props`);}}function Ql(r,e){let t=_.getLogichValue(r,e);return t&&typeof t=="object"&&"type"in t?_.getLogichValue(t,e):t}function Zl(r,e={}){let t=Ql(r.value,e);switch(r.storageType){case "flagStorage":storage.storage.setFlag(r.key,r.value);break;case "storage":storage.storage.set(r.key,t);break;case "tempstorage":storage.storage.setTempVariable(r.key,t);break;case "params":{let n=storage.storage.get(`${zs}${narration.narration.openedLabels.length-1}`)||[];n.length>r.key&&(n[r.key]=t),storage.storage.setTempVariable(`${zs}${narration.narration.openedLabels.length-1}`,n);break}}}function eu(r,e={}){let t=Ql(r.value,e);switch(r.storageType){case "storage":case "tempstorage":storage.storage.default={[r.key]:t};break}}function tu(r,e={}){let t=nu(r,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return sp(t,e);case "arithmetic":case "arithmeticsingle":return rp(t,e);case "compare":case "union":return ap(t,e);case "function":return ip(t,e)}return t}function rp(r,e){let t=_.getLogichValue(r.leftValue,e);switch(r.type){case "arithmetic":{let n=_.getLogichValue(r.rightValue,e);switch(r.operator){case "*":return t*n;case "/":return t/n;case "+":return typeof t=="string"||typeof n=="string"?`${t}${n}`:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:Array.isArray(t)?[...t,n]:Array.isArray(n)?[t,...n]:t+n;case "-":if(Array.isArray(t)&&Array.isArray(n))return t.filter(i=>!n.includes(i));if(Array.isArray(t))return t.filter(i=>i!==n);if(Array.isArray(n)){G.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-n;case "%":return t%n;case "POW":return t**n;case "RANDOM":return narration.narration.getRandomNumber(t,n);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(n))return t.filter(i=>n.includes(i));G.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:G.warn("getValueFromArithmeticOperations unknown operator",r);return}}case "arithmeticsingle":switch(r.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function sp(r,e){if(r&&typeof r=="object"&&"type"in r&&r.type==="value"&&r.storageOperationType==="get")switch(r.storageType){case "storage":case "tempstorage":return r.key==="_input_value_"?narration.narration.inputValue:storage.storage.get(r.key);case "flagStorage":return storage.storage.getFlag(r.key);case "label":return narration.narration.getTimesLabelOpened(r.label);case "choice":return narration.narration.getTimesChoiceMade(r.index);case "logic":return _.getLogichValue(r.operation,e);case "params":{let t=storage.storage.get(`${zs}${narration.narration.openedLabels.length-1}`)||[];if(t&&t.length>r.key)return t[r.key];G.warn("getValue params not found");return}}return r}function ap(r,e){if(!r)return false;if(typeof r!="object"||!("type"in r))return !!r;switch(r.type){case "compare":{let t=_.getLogichValue(r.leftValue,e),n=_.getLogichValue(r.rightValue,e);switch(r.operator){case "==":return Array.isArray(t)&&Array.isArray(n)?t.length===n.length&&t.every(i=>n.includes(i)):t===n;case "!=":return Array.isArray(t)&&Array.isArray(n)?t.length!==n.length||!t.every(i=>n.includes(i)):t!==n;case "<":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<0:Array.isArray(t)&&Array.isArray(n)?t.length<n.length:t<n;case "<=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<=0:Array.isArray(t)&&Array.isArray(n)?t.length<=n.length:t<=n;case ">":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>0:Array.isArray(t)&&Array.isArray(n)?t.length>n.length:t>n;case ">=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>=0:Array.isArray(t)&&Array.isArray(n)?t.length>=n.length:t>=n;case "CONTAINS":return Array.isArray(t)&&Array.isArray(n)?n.every(i=>t.includes(i)):Array.isArray(t)?t.includes(n):t.toString().includes(n.toString())}break}case "value":{let t=_.getLogichValue(r,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return op(r,e)}return !!r}function op(r,e){if(r.unionType==="not"){let n=tu(r.condition,e);return Array.isArray(n)?n.length===0:n&&typeof n=="object"?Object.keys(n).length===0:!n}let t=n=>_.getLogichValue(n,e)||false;return r.unionType==="and"?r.conditions.every(t):r.conditions.some(t)}function lp(r,e){return Math.floor(Math.random()*(e-r+1)+r)}function nu(r,e={}){if(Array.isArray(r)||!r)return r;if(r&&typeof r=="object"&&"type"in r)switch(r.type){case "resulttocombine":return up(r,e);case "ifelse":return _.getLogichValue(r.condition,e)?_.getLogichValue(r.then,e):_.getLogichValue(r.else,e);case "stepswitch":{let t=_.getLogichValue(r.elements,e)||[];if(t.length===0){G.error("getValueFromConditionalStatements elements.length === 0");return}switch(r.choiceType){case "random":{let n=lp(0,t.length-1);return _.getLogichValue(t[n],e)}case "loop":{let n=narration.NarrationManagerStatic.getCurrentStepTimesCounter(r.nestedId)-1;return n>t.length-1?(n=n%t.length,_.getLogichValue(t[n],e)):_.getLogichValue(t[n],e)}case "sequential":{let n,i=narration.NarrationManagerStatic.getCurrentStepTimesCounter(r.nestedId)-1;return r.end==="lastItem"&&(n=_.getLogichValue(t[t.length-1],e)),i>t.length-1?n:_.getLogichValue(t[i],e)}case "sequentialrandom":{let n=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:r.nestedId,onceOnly:true});if(n===void 0&&r.end==="lastItem"){let i=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(r.nestedId);if(!i?.usedRandomNumbers){G.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=i.usedRandomNumbers[`0-${t.length-1}`];return _.getLogichValue(t[a[a.length-1]],e)}if(n===void 0){G.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return _.getLogichValue(t[n],e)}}}}return r}function mi(r,e={}){if(r.conditionalStep){let t=pixiVn.createExportableElement(_.getLogichValue(r.conditionalStep,e));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 n={...r,conditionalStep:void 0,...t};return mi(n,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return r}function up(r,e){let t=r.firstItem,n=(r.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>_.getLogichValue(s,e)):[_.getLogichValue(a,e)]),i=t?[t,...n]:n;if(i.length===0){G.warn("combinateResult toCheck.length === 0");return}if(typeof i[0]=="string")return oe.t(i);if(typeof i[0]=="object"){let a=i,s,o=false,l=a.map((y,m)=>{y=mi(y,e);let C=_.getLogichValue(y.dialogue,e)||"";return m===0?(s=_.getLogichValue(y.glueEnabled,e)||false,C):(typeof C=="object"&&"text"in C&&(C=`${C.character}: ${C.text}`),s===false&&o&&(C=`
45
+
46
+ ${C}`),C&&(o=true),s=_.getLogichValue(y.glueEnabled,e)||false,C)}),u=_.getLogichValue(l[0],e),h=typeof u=="object"&&"character"in u?u.character:void 0,c=l.flatMap(y=>{let m;y&&typeof y=="object"&&"text"in y?m=y.text:m=y;let C;return Array.isArray(m)?C=m.map(v=>{let E=_.getLogichValue(v,e);return oe.t(`${E}`)}):C=_.getLogichValue(m,e)||"",oe.t(C)}),p=a.find(y=>y.end),d=a.find(y=>y.choices),f=false,g=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),f=a[a.length-1].glueEnabled,g=a.reverse().find(y=>!(y.operations&&(!y.dialogue||!y.choices)))?.goNextStep);let b=a.find(y=>y.labelToOpen),D=[];return a.forEach(y=>{y.operations&&(D=[...D,...y.operations]);}),{dialogue:h?{character:h,text:c}:c,end:p?.end,choices:d?.choices,glueEnabled:f,goNextStep:g,labelToOpen:b?.labelToOpen,operations:D}}}exports.VariableGetter=void 0;(r=>{let e=new Set;function t(a){e.add(a);}r.add=t;function n(){e.clear();}r.clear=n;function i(a,s={}){let o=h=>tu(h,s)??void 0,l=nu(a,s);if(e.size===0)return o(l);let u=o;for(let h of e){let c=u;u=p=>h(p,c)??void 0;}return u(l)}r.getLogichValue=i;})(exports.VariableGetter||={});var dp=Object.create,ou=Object.defineProperty,fp=Object.getOwnPropertyDescriptor,mp=Object.getOwnPropertyNames,gp=Object.getPrototypeOf,Cp=Object.prototype.hasOwnProperty,ru=(r=>typeof _t<"u"?_t:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof _t<"u"?_t:e)[t]}):r)(function(r){if(typeof _t<"u")return _t.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),lu=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),yp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of mp(e))!Cp.call(r,i)&&i!==t&&ou(r,i,{get:()=>e[i],enumerable:!(n=fp(e,i))||n.enumerable});return r},vp=(r,e,t)=>(t=r!=null?dp(gp(r)):{},yp(ou(t,"default",{value:r,enumerable:true}),r)),Sp=lu((r,e)=>{(function(t,n){typeof r=="object"?e.exports=r=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(r,function(){var t=t||(function(n,i){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof ru=="function")try{a=ru("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 y(){}return function(m){var C;return y.prototype=m,C=new y,y.prototype=null,C}})(),l={},u=l.lib={},h=u.Base=(function(){return {extend:function(y){var m=o(this);return y&&m.mixIn(y),(!m.hasOwnProperty("init")||this.init===m.init)&&(m.init=function(){m.$super.init.apply(this,arguments);}),m.init.prototype=m,m.$super=this,m},create:function(){var y=this.extend();return y.init.apply(y,arguments),y},init:function(){},mixIn:function(y){for(var m in y)y.hasOwnProperty(m)&&(this[m]=y[m]);y.hasOwnProperty("toString")&&(this.toString=y.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),c=u.WordArray=h.extend({init:function(y,m){y=this.words=y||[],m!=i?this.sigBytes=m:this.sigBytes=y.length*4;},toString:function(y){return (y||d).stringify(this)},concat:function(y){var m=this.words,C=y.words,v=this.sigBytes,E=y.sigBytes;if(this.clamp(),v%4)for(var w=0;w<E;w++){var T=C[w>>>2]>>>24-w%4*8&255;m[v+w>>>2]|=T<<24-(v+w)%4*8;}else for(var P=0;P<E;P+=4)m[v+P>>>2]=C[P>>>2];return this.sigBytes+=E,this},clamp:function(){var y=this.words,m=this.sigBytes;y[m>>>2]&=4294967295<<32-m%4*8,y.length=n.ceil(m/4);},clone:function(){var y=h.clone.call(this);return y.words=this.words.slice(0),y},random:function(y){for(var m=[],C=0;C<y;C+=4)m.push(s());return new c.init(m,y)}}),p=l.enc={},d=p.Hex={stringify:function(y){for(var m=y.words,C=y.sigBytes,v=[],E=0;E<C;E++){var w=m[E>>>2]>>>24-E%4*8&255;v.push((w>>>4).toString(16)),v.push((w&15).toString(16));}return v.join("")},parse:function(y){for(var m=y.length,C=[],v=0;v<m;v+=2)C[v>>>3]|=parseInt(y.substr(v,2),16)<<24-v%8*4;return new c.init(C,m/2)}},f=p.Latin1={stringify:function(y){for(var m=y.words,C=y.sigBytes,v=[],E=0;E<C;E++){var w=m[E>>>2]>>>24-E%4*8&255;v.push(String.fromCharCode(w));}return v.join("")},parse:function(y){for(var m=y.length,C=[],v=0;v<m;v++)C[v>>>2]|=(y.charCodeAt(v)&255)<<24-v%4*8;return new c.init(C,m)}},g=p.Utf8={stringify:function(y){try{return decodeURIComponent(escape(f.stringify(y)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(y){return f.parse(unescape(encodeURIComponent(y)))}},b=u.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new c.init,this._nDataBytes=0;},_append:function(y){typeof y=="string"&&(y=g.parse(y)),this._data.concat(y),this._nDataBytes+=y.sigBytes;},_process:function(y){var m,C=this._data,v=C.words,E=C.sigBytes,w=this.blockSize,T=w*4,P=E/T;y?P=n.ceil(P):P=n.max((P|0)-this._minBufferSize,0);var L=P*w,ve=n.min(L*4,E);if(L){for(var st=0;st<L;st+=w)this._doProcessBlock(v,st);m=v.splice(0,L),C.sigBytes-=ve;}return new c.init(m,ve)},clone:function(){var y=h.clone.call(this);return y._data=this._data.clone(),y},_minBufferSize:0});u.Hasher=b.extend({cfg:h.extend(),init:function(y){this.cfg=this.cfg.extend(y),this.reset();},reset:function(){b.reset.call(this),this._doReset();},update:function(y){return this._append(y),this._process(),this},finalize:function(y){y&&this._append(y);var m=this._doFinalize();return m},blockSize:16,_createHelper:function(y){return function(m,C){return new y.init(C).finalize(m)}},_createHmacHelper:function(y){return function(m,C){return new D.HMAC.init(y,C).finalize(m)}}});var D=l.algo={};return l})(Math);return t});}),Ep=lu((r,e)=>{(function(t,n){typeof r=="object"?e.exports=r=n(Sp()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(r,function(t){return (function(){var n=t,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 p=this._hash.words,d=p[0],f=p[1],g=p[2],b=p[3],D=p[4],y=0;y<80;y++){if(y<16)l[y]=h[c+y]|0;else {var m=l[y-3]^l[y-8]^l[y-14]^l[y-16];l[y]=m<<1|m>>>31;}var C=(d<<5|d>>>27)+D+l[y];y<20?C+=(f&g|~f&b)+1518500249:y<40?C+=(f^g^b)+1859775393:y<60?C+=(f&g|f&b|g&b)-1894007588:C+=(f^g^b)-899497514,D=b,b=g,g=f<<30|f>>>2,f=d,d=C;}p[0]=p[0]+d|0,p[1]=p[1]+f|0,p[2]=p[2]+g|0,p[3]=p[3]+b|0,p[4]=p[4]+D|0;},_doFinalize:function(){var h=this._data,c=h.words,p=this._nDataBytes*8,d=h.sigBytes*8;return c[d>>>5]|=128<<24-d%32,c[(d+64>>>9<<4)+14]=Math.floor(p/4294967296),c[(d+64>>>9<<4)+15]=p,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);})(),t.SHA1});}),su="___param___",ie;(r=>(r.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),r.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),r.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),r.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(ie||={});var Dp=class ${static init(e){e.loadAssets&&($._loadAssets=e.loadAssets),e.soundOperation&&($._soundOperation=e.soundOperation),e.imageOperation&&($._imageOperation=e.imageOperation),e.videoOperation&&($._videoOperation=e.videoOperation),e.imageContainerOperation&&($._imageContainerOperation=e.imageContainerOperation),e.textOperation&&($._textOperation=e.textOperation),e.canvasElementOperation&&($._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&($._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&($._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&($._narrationOperation=e.narrationOperation),e.effectOperation&&($._effectOperation=e.effectOperation),e.animateOperation&&($._animateOperation=e.animateOperation),e.canvasOperation&&($._canvasOperation=e.canvasOperation),e.getLogichValue&&($._getLogichValue=e.getLogichValue),e.getConditionalStep&&($._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return $._loadAssets}static _soundOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return $._soundOperation}static _imageOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return $._imageOperation}static _videoOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return $._videoOperation}static _imageContainerOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return $._imageContainerOperation}static _textOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return $._textOperation}static _canvasElementOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return $._canvasElementOperation}static _setStorageValue=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return $._setStorageValue}static _setInitialStorageValue=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return $._setInitialStorageValue}static _narrationOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return $._narrationOperation}static _effectOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return $._effectOperation}static _animateOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return $._animateOperation}static _canvasOperation=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return $._canvasOperation}static _getLogichValue=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return $._getLogichValue}static _getConditionalStep=()=>{throw ie.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return $._getConditionalStep}};function bp(r,e){if(e&&typeof e=="object"&&typeof r.functionName=="string"&&r.functionName in e){let t=e[r.functionName];if(typeof t=="function"){let n=r.args.map(i=>Dp.getLogichValue(i,e));return t(...n)}else ie.warn(`getLogichValue function ${r.functionName} not found in props`);}}function Ap(r,e={}){let t="";return r.values.forEach(n=>{if(typeof n=="string")t+=n;else {let i=_.getLogichValue(n,e);t+=`${i}`;}}),t}async function uu(r,e,t){let n=_.getLogichValue(r,e);if(n)switch(n.type){case "sound":_.soundOperation(n);break;case "assets":case "bundle":await _.loadAssets(n);break;case "image":await _.imageOperation(n);break;case "video":await _.videoOperation(n);break;case "imagecontainer":await _.imageContainerOperation(n);break;case "text":await _.textOperation(n);break;case "canvaselement":await _.canvasElementOperation(n);break;case "canvas":_.canvasOperation(n);break;case "value":_.setStorageValue(n,e);break;case "operationtoconvert":if(t){let i=Ap(n,e),a=await t(i);a&&await uu(a,e,t);}break;case "input":case "dialogue":_.narrationOperation(n);break;case "shake":await _.effectOperation(n);break;case "animate":case "animate-sequence":_.animateOperation(n);break;case "function":await bp(n,e);break}}function au(r){let e=_.getLogichValue(r,{});e&&e.type==="value"&&e.storageOperationType==="set"&&(e.storageType==="storage"||e.storageType==="tempstorage")&&_.setInitialStorageValue(e);}var wp=vp(Ep()),xp=class extends narration.LabelAbstract{constructor(r,e,t,n={}){t||(t={}),t.onLoadingLabel=async()=>{for(let i of e){let a;if(typeof i=="function"?a=i():a=i,a=_.getConditionalStep(a),a.operations)try{let s=a.operations.map(o=>_.loadAssets(o));await Promise.all(s);}catch(s){ie.error("The operation in the onLoadingLabel function of the label has an error:",s);}}},super(r,t),this._steps=e,this.operationStringConvert=n.operationStringConvert,this.skipEmptyDialogs=n.skipEmptyDialogs||false;}_steps;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 e=this._steps[r];return this.stepConverter(e)}operationStringConvert;skipEmptyDialogs=false;getStepSha(r){if(r<0||r>=this.steps.length)return;let e=this._steps[r];return (0, wp.default)(e.toString().toLocaleLowerCase()).toString()}getDialogueText(r,e){let t="";if(Array.isArray(r)){let n=[];r.forEach(i=>{if(typeof i=="string")n.push(i);else if(i&&typeof i=="object"){let a=_.getLogichValue(i,e);a?(a&&!Array.isArray(a)&&typeof a=="object"&&(a=_.getLogichValue(a,e)||""),Array.isArray(a)?n=n.map(s=>`${s}`).concat(a):n.push(`${a}`)):n.push(`${i}`);}else n.push(`${i}`);}),t=n;}else {let n=_.getLogichValue(r,e);n&&!Array.isArray(n)&&typeof n=="object"&&(n=_.getLogichValue(n,e)),n&&Array.isArray(n)?t=n.map(i=>`${i}`):t=`${n}`;}return t}getDialogue(r,e){if(r==null)return;let t=_.getLogichValue(r,e);return t==null?`${t}`:typeof t=="object"&&"character"in t&&"text"in t?{character:t.character,text:oe.t(this.getDialogueText(t.text,e))}:oe.t(this.getDialogueText(t,e))}getChoices(r,e){return _.getLogichValue(r,e)?.map(t=>_.getLogichValue(t,e)).filter(t=>t!==void 0)}stepConverter(r){return async e=>{let t=typeof r=="function"?r():r;t=pixiVn.createExportableElement(t),t=_.getConditionalStep(t,e);let n=this.operationStringConvert?p=>this.operationStringConvert(p,t,e):void 0,{operations:i=[]}=t;for(let p of i)await uu(p,e,n);let{labelToOpen:a=[]}=t,s=this.getChoices(t.choices,e),o=_.getLogichValue(t.glueEnabled,e),l=this.getDialogue(t.dialogue,e),u=[];Array.isArray(a)||(a=[a]),a.forEach(p=>{let d=_.getLogichValue(p,e);d&&u.push(d);});let h=_.getLogichValue(t.goNextStep,e),c=_.getLogichValue(t.end,e);if(s){let p=s.map(d=>{let f="";if(Array.isArray(d.text)){let g=[];d.text.forEach(b=>{if(typeof b=="string")g.push(oe.t(b));else if(b&&typeof b=="object"){let D=_.getLogichValue(b,e);D&&!Array.isArray(D)&&typeof D=="object"&&(D=_.getLogichValue(D,e)||""),D&&(Array.isArray(D)?g=g.concat(oe.t(D)):g.push(oe.t(D)));}}),f=g;}else typeof d.text=="string"&&(f=oe.t(d.text));return {label:d.label,text:f,props:d.props,type:d.type,oneTime:d.oneTime,onlyHaveNoChoice:d.onlyHaveNoChoice,autoSelect:d.autoSelect}});narration.narration.choices=p;}else narration.narration.choices=void 0;l!==void 0&&(narration.narration.dialogue=l,this.skipEmptyDialogs&&typeof l=="string"&&(l===""||RegExp(/^\s+$/).test(l))&&(h=true)),o?narration.narration.dialogGlue=true:o===false&&(narration.narration.dialogGlue=false);for(let p of u){let d=p.label;typeof d=="object"&&(d=_.getLogichValue(d,e)||"");let f=p.params?.map(g=>_.getLogichValue(g,e));e={...e,...p.props},p.type==="jump"?(narration.narration.openedLabels.length>0&&narration.narration.closeCurrentLabel(),storage.storage.setTempVariable(`${su}${narration.narration.openedLabels.length}`,f),await narration.narration.call(d,e)):(storage.storage.setTempVariable(`${su}${narration.narration.openedLabels.length}`,f),await narration.narration.call(d,e));}c==="game_end"?(narration.narration.closeAllLabels(),await narration.narration.continue(e,{runNow:true})):c==="label_end"&&narration.narration.closeCurrentLabel(),h&&await narration.narration.continue(e,{runNow:true});}}};async function Us(r,e={}){if(!Array.isArray(r))if(typeof r=="object"||typeof r=="string")r=[r];else {ie.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let t=r.map(a=>{if(typeof a=="string")try{return JSON.parse(a)}catch(s){return ie.error("Error parsing imported Pixi'VN JSON",s),{}}return a}),n=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)s.type==="value"&&(typeof s.value!="object"||!s.value||!("type"in s.value))&&au(s);return Promise.resolve()});await Promise.all(n);let i=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)(s.type!=="value"||s.type==="value"&&typeof s.value=="object"&&s.value&&"type"in s.value)&&au(s);if(a.labels){let s=a.labels;for(let o in s)try{let l=s[o],u=new xp(o,l,void 0,e);narration.RegisteredLabels.add(u);}catch(l){ie.error(`Error creating JSON label ${o}`,l);}}return Promise.resolve()});await Promise.all(i);}var _p={version:"1.13.14"};var hu=`https://pixi-vn.com/schemas/${_p.version}/schema.json`,cu=["==","!=","<","<=",">",">=","CONTAINS"];function Ks(){_.init({animateOperation:Kl,canvasElementOperation:Hl,canvasOperation:zl,effectOperation:Ul,imageContainerOperation:$l,imageOperation:Ml,textOperation:Jl,narrationOperation:Xl,loadAssets:ql,soundOperation:Yl,videoOperation:Gl,setStorageValue:Zl,setInitialStorageValue:eu,getLogichValue:exports.VariableGetter.getLogichValue,getConditionalStep:mi});}var gi="global decl",Ot="___external_value___",pu=/\[([^\]]+)\]/;function Op(r){oe.afterToTranslate=e=>du(e,r);}function Pp(r){oe.beforeToTranslate=e=>du(e,r);}function du(r,e){let t=new RegExp(pu.source,"g"),n=new Set,i=true;for(;i;){i=false;let a=[...r.matchAll(t)],s=new Set;for(let o of a){let l=o[1];if(s.has(l)||n.has(l))continue;s.add(l);let u=e(l);u!==void 0?(r=r.replaceAll(o[0],u),i=true):n.add(l);}}return r}var j;(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)))(j||={});var Tp=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Fp=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,Np=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,Xs={Space_Separator:Tp,ID_Start:Fp,ID_Continue:Np},ne={isSpaceSeparator(r){return typeof r=="string"&&Xs.Space_Separator.test(r)},isIdStartChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="$"||r==="_"||Xs.ID_Start.test(r))},isIdContinueChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="$"||r==="_"||r==="\u200C"||r==="\u200D"||Xs.ID_Continue.test(r))},isDigit(r){return typeof r=="string"&&/[0-9]/.test(r)},isHexDigit(r){return typeof r=="string"&&/[0-9A-Fa-f]/.test(r)}},Qs,De,lt,yi,ft,$e,le,ta,bn,Ip=function(e,t){Qs=String(e),De="start",lt=[],yi=0,ft=1,$e=0,le=void 0,ta=void 0,bn=void 0;do le=Vp(),Lp[De]();while(le.type!=="eof");return typeof t=="function"?Zs({"":bn},"",t):bn};function Zs(r,e,t){let n=r[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let i=0;i<n.length;i++){let a=String(i),s=Zs(n,a,t);s===void 0?delete n[a]:Object.defineProperty(n,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let i in n){let a=Zs(n,i,t);a===void 0?delete n[i]:Object.defineProperty(n,i,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(r,e,n)}var V,I,Dn,ot,B;function Vp(){for(V="default",I="",Dn=false,ot=1;;){B=ut();let r=mu[V]();if(r)return r}}function ut(){if(Qs[yi])return String.fromCodePoint(Qs.codePointAt(yi))}function A(){let r=ut();return r===`
47
+ `?(ft++,$e=0):r?$e+=r.length:$e++,r&&(yi+=r.length),r}var mu={default(){switch(B){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
48
+ `:case "\r":case "\u2028":case "\u2029":A();return;case "/":A(),V="comment";return;case void 0:return A(),X("eof")}if(ne.isSpaceSeparator(B)){A();return}return mu[De]()},comment(){switch(B){case "*":A(),V="multiLineComment";return;case "/":A(),V="singleLineComment";return}throw Y(A())},multiLineComment(){switch(B){case "*":A(),V="multiLineCommentAsterisk";return;case void 0:throw Y(A())}A();},multiLineCommentAsterisk(){switch(B){case "*":A();return;case "/":A(),V="default";return;case void 0:throw Y(A())}A(),V="multiLineComment";},singleLineComment(){switch(B){case `
49
+ `:case "\r":case "\u2028":case "\u2029":A(),V="default";return;case void 0:return A(),X("eof")}A();},value(){switch(B){case "{":case "[":return X("punctuator",A());case "n":return A(),Pt("ull"),X("null",null);case "t":return A(),Pt("rue"),X("boolean",true);case "f":return A(),Pt("alse"),X("boolean",false);case "-":case "+":A()==="-"&&(ot=-1),V="sign";return;case ".":I=A(),V="decimalPointLeading";return;case "0":I=A(),V="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=A(),V="decimalInteger";return;case "I":return A(),Pt("nfinity"),X("numeric",1/0);case "N":return A(),Pt("aN"),X("numeric",NaN);case '"':case "'":Dn=A()==='"',I="",V="string";return}throw Y(A())},identifierNameStartEscape(){if(B!=="u")throw Y(A());A();let r=ea();switch(r){case "$":case "_":break;default:if(!ne.isIdStartChar(r))throw fu();break}I+=r,V="identifierName";},identifierName(){switch(B){case "$":case "_":case "\u200C":case "\u200D":I+=A();return;case "\\":A(),V="identifierNameEscape";return}if(ne.isIdContinueChar(B)){I+=A();return}return X("identifier",I)},identifierNameEscape(){if(B!=="u")throw Y(A());A();let r=ea();switch(r){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!ne.isIdContinueChar(r))throw fu();break}I+=r,V="identifierName";},sign(){switch(B){case ".":I=A(),V="decimalPointLeading";return;case "0":I=A(),V="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=A(),V="decimalInteger";return;case "I":return A(),Pt("nfinity"),X("numeric",ot*(1/0));case "N":return A(),Pt("aN"),X("numeric",NaN)}throw Y(A())},zero(){switch(B){case ".":I+=A(),V="decimalPoint";return;case "e":case "E":I+=A(),V="decimalExponent";return;case "x":case "X":I+=A(),V="hexadecimal";return}return X("numeric",ot*0)},decimalInteger(){switch(B){case ".":I+=A(),V="decimalPoint";return;case "e":case "E":I+=A(),V="decimalExponent";return}if(ne.isDigit(B)){I+=A();return}return X("numeric",ot*Number(I))},decimalPointLeading(){if(ne.isDigit(B)){I+=A(),V="decimalFraction";return}throw Y(A())},decimalPoint(){switch(B){case "e":case "E":I+=A(),V="decimalExponent";return}if(ne.isDigit(B)){I+=A(),V="decimalFraction";return}return X("numeric",ot*Number(I))},decimalFraction(){switch(B){case "e":case "E":I+=A(),V="decimalExponent";return}if(ne.isDigit(B)){I+=A();return}return X("numeric",ot*Number(I))},decimalExponent(){switch(B){case "+":case "-":I+=A(),V="decimalExponentSign";return}if(ne.isDigit(B)){I+=A(),V="decimalExponentInteger";return}throw Y(A())},decimalExponentSign(){if(ne.isDigit(B)){I+=A(),V="decimalExponentInteger";return}throw Y(A())},decimalExponentInteger(){if(ne.isDigit(B)){I+=A();return}return X("numeric",ot*Number(I))},hexadecimal(){if(ne.isHexDigit(B)){I+=A(),V="hexadecimalInteger";return}throw Y(A())},hexadecimalInteger(){if(ne.isHexDigit(B)){I+=A();return}return X("numeric",ot*Number(I))},string(){switch(B){case "\\":A(),I+=kp();return;case '"':if(Dn)return A(),X("string",I);I+=A();return;case "'":if(!Dn)return A(),X("string",I);I+=A();return;case `
50
+ `:case "\r":throw Y(A());case "\u2028":case "\u2029":Bp(B);break;case void 0:throw Y(A())}I+=A();},start(){switch(B){case "{":case "[":return X("punctuator",A())}V="value";},beforePropertyName(){switch(B){case "$":case "_":I=A(),V="identifierName";return;case "\\":A(),V="identifierNameStartEscape";return;case "}":return X("punctuator",A());case '"':case "'":Dn=A()==='"',V="string";return}if(ne.isIdStartChar(B)){I+=A(),V="identifierName";return}throw Y(A())},afterPropertyName(){if(B===":")return X("punctuator",A());throw Y(A())},beforePropertyValue(){V="value";},afterPropertyValue(){switch(B){case ",":case "}":return X("punctuator",A())}throw Y(A())},beforeArrayValue(){if(B==="]")return X("punctuator",A());V="value";},afterArrayValue(){switch(B){case ",":case "]":return X("punctuator",A())}throw Y(A())},end(){throw Y(A())}};function X(r,e){return {type:r,value:e,line:ft,column:$e}}function Pt(r){for(let e of r){if(ut()!==e)throw Y(A());A();}}function kp(){switch(ut()){case "b":return A(),"\b";case "f":return A(),"\f";case "n":return A(),`
51
+ `;case "r":return A(),"\r";case "t":return A()," ";case "v":return A(),"\v";case "0":if(A(),ne.isDigit(ut()))throw Y(A());return "\0";case "x":return A(),Rp();case "u":return A(),ea();case `
52
+ `:case "\u2028":case "\u2029":return A(),"";case "\r":return A(),ut()===`
53
+ `&&A(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw Y(A());case void 0:throw Y(A())}return A()}function Rp(){let r="",e=ut();if(!ne.isHexDigit(e)||(r+=A(),e=ut(),!ne.isHexDigit(e)))throw Y(A());return r+=A(),String.fromCodePoint(parseInt(r,16))}function ea(){let r="",e=4;for(;e-- >0;){let t=ut();if(!ne.isHexDigit(t))throw Y(A());r+=A();}return String.fromCodePoint(parseInt(r,16))}var Lp={start(){if(le.type==="eof")throw Tt();Ys();},beforePropertyName(){switch(le.type){case "identifier":case "string":ta=le.value,De="afterPropertyName";return;case "punctuator":Ci();return;case "eof":throw Tt()}},afterPropertyName(){if(le.type==="eof")throw Tt();De="beforePropertyValue";},beforePropertyValue(){if(le.type==="eof")throw Tt();Ys();},beforeArrayValue(){if(le.type==="eof")throw Tt();if(le.type==="punctuator"&&le.value==="]"){Ci();return}Ys();},afterPropertyValue(){if(le.type==="eof")throw Tt();switch(le.value){case ",":De="beforePropertyName";return;case "}":Ci();}},afterArrayValue(){if(le.type==="eof")throw Tt();switch(le.value){case ",":De="beforeArrayValue";return;case "]":Ci();}},end(){}};function Ys(){let r;switch(le.type){case "punctuator":switch(le.value){case "{":r={};break;case "[":r=[];break}break;case "null":case "boolean":case "numeric":case "string":r=le.value;break}if(bn===void 0)bn=r;else {let e=lt[lt.length-1];Array.isArray(e)?e.push(r):Object.defineProperty(e,ta,{value:r,writable:true,enumerable:true,configurable:true});}if(r!==null&&typeof r=="object")lt.push(r),Array.isArray(r)?De="beforeArrayValue":De="beforePropertyName";else {let e=lt[lt.length-1];e==null?De="end":Array.isArray(e)?De="afterArrayValue":De="afterPropertyValue";}}function Ci(){lt.pop();let r=lt[lt.length-1];r==null?De="end":Array.isArray(r)?De="afterArrayValue":De="afterPropertyValue";}function Y(r){return vi(r===void 0?`JSON5: invalid end of input at ${ft}:${$e}`:`JSON5: invalid character '${gu(r)}' at ${ft}:${$e}`)}function Tt(){return vi(`JSON5: invalid end of input at ${ft}:${$e}`)}function fu(){return $e-=5,vi(`JSON5: invalid identifier character at ${ft}:${$e}`)}function Bp(r){console.warn(`JSON5: '${gu(r)}' in strings is not valid ECMAScript; consider escaping`);}function gu(r){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[r])return e[r];if(r<" "){let t=r.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return r}function vi(r){let e=new SyntaxError(r);return e.lineNumber=ft,e.columnNumber=$e,e}var Wp=function(e,t,n){let i=[],a="",s,o,l="",u;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,u=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let g of t){let b;typeof g=="string"?b=g:(typeof g=="number"||g instanceof String||g instanceof Number)&&(b=String(g)),b!==void 0&&s.indexOf(b)<0&&s.push(b);}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),h("",{"":e});function h(g,b){let D=b[g];switch(D!=null&&(typeof D.toJSON5=="function"?D=D.toJSON5(g):typeof D.toJSON=="function"&&(D=D.toJSON(g))),o&&(D=o.call(b,g,D)),D instanceof Number?D=Number(D):D instanceof String?D=String(D):D instanceof Boolean&&(D=D.valueOf()),D){case null:return "null";case true:return "true";case false:return "false"}if(typeof D=="string")return c(D);if(typeof D=="number")return String(D);if(typeof D=="object")return Array.isArray(D)?f(D):p(D)}function c(g){let b={"'":.1,'"':.2},D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},y="";for(let C=0;C<g.length;C++){let v=g[C];switch(v){case "'":case '"':b[v]++,y+=v;continue;case "\0":if(ne.isDigit(g[C+1])){y+="\\x00";continue}}if(D[v]){y+=D[v];continue}if(v<" "){let E=v.charCodeAt(0).toString(16);y+="\\x"+("00"+E).substring(E.length);continue}y+=v;}let m=u||Object.keys(b).reduce((C,v)=>b[C]<b[v]?C:v);return y=y.replace(new RegExp(m,"g"),D[m]),m+y+m}function p(g){if(i.indexOf(g)>=0)throw TypeError("Converting circular structure to JSON5");i.push(g);let b=a;a=a+l;let D=s||Object.keys(g),y=[];for(let C of D){let v=h(C,g);if(v!==void 0){let E=d(C)+":";l!==""&&(E+=" "),E+=v,y.push(E);}}let m;if(y.length===0)m="{}";else {let C;if(l==="")C=y.join(","),m="{"+C+"}";else {let v=`,
54
+ `+a;C=y.join(v),m=`{
55
+ `+a+C+`,
56
+ `+b+"}";}}return i.pop(),a=b,m}function d(g){if(g.length===0)return c(g);let b=String.fromCodePoint(g.codePointAt(0));if(!ne.isIdStartChar(b))return c(g);for(let D=b.length;D<g.length;D++)if(!ne.isIdContinueChar(String.fromCodePoint(g.codePointAt(D))))return c(g);return g}function f(g){if(i.indexOf(g)>=0)throw TypeError("Converting circular structure to JSON5");i.push(g);let b=a;a=a+l;let D=[];for(let m=0;m<g.length;m++){let C=h(String(m),g);D.push(C!==void 0?C:"null");}let y;if(D.length===0)y="[]";else if(l==="")y="["+D.join(",")+"]";else {let m=`,
57
+ `+a,C=D.join(m);y=`[
58
+ `+a+C+`,
59
+ `+b+"]";}return i.pop(),a=b,y}},jp={parse:Ip,stringify:Wp},qp=jp,An=qp;var yu="\xA7SPACE\xA7",vu="\xA7DOUBLE_QUOTES\xA7",Su="\xA7QUOTES\xA7",Eu="SPECIAL_\xA7QUOTES\xA7",Du="\xA7CURLY_BRACKETS1\xA7",Mp="\xA7INK_VAR\xA7",bu="\xA7CURLY_BRACKETS2\xA7";exports.HashtagCommands=void 0;(m=>{let r=[],e=[];async function t(C,v){for(let E=0;E<r.length;E++)try{let{validation:w}=r[E].opts;if(w instanceof RegExp){if(!w.test(C.join(" ")))continue}else if(w instanceof S.ZodType&&!w.safeParse(C).success)continue;let T=await r[E].fn(C,v,c);if(T===!0||typeof T=="string")return T}catch{}return false}function n(C,v={name:"custom-command",validation:/^/}){r.unshift({fn:C,opts:v});}m.add=n;function i(){return [...e.map(C=>C.opts),...r.map(C=>C.opts)]}m.info=i;function a(C,v){e.unshift({fn:C,opts:v});}m.addMapper=a;function s(){r.length=0;}m.clear=s;function o(){e.length=0;}m.clearMappers=o;async function l(C,v,E){try{let w=u(C),T=await t(w,E);return T===!0?void 0:typeof T=="string"?(T.startsWith("#")&&(T=T.substring(1)),await m.run(T,v,E)):h(w,v)}catch(w){throw j.error("Error parsing ink hashtag-command",C),w}}m.run=l;function u(C,v){if(C=C.replaceAll('\\"',vu),C=C.replaceAll("\\'",Su),C=C.replaceAll("\\`",Eu),C=C.replaceAll("\\{",Du),C=C.replaceAll("\\}",bu),v?.mergeInkVariables){let P;do P=C,C=C.replace(/\{[^{}:]*\}/g,Mp);while(C!==P)}C=C.replaceAll("{"," { "),C=C.replaceAll("}"," } "),C=C.replaceAll(Du,"{"),C=C.replaceAll(bu,"}");let E=[],w,T="";for(let P=0;P<C.length;P++){let L=C[P];L==='"'||L==="'"||L==="`"?w===void 0?(E.push(T),T="",w=L,T+=L):w===L?(w=void 0,T+=L,E.push(T),T=""):T+=L:T+=L;}return T!==""&&E.push(T),E.forEach((P,L)=>{L%2===1&&(E[L]=P.replaceAll(" ",yu));}),C=E.join(""),E=C.split(" ").filter(P=>P!==""),E=E.map(P=>P.replaceAll(yu," ").replaceAll(vu,'"').replaceAll(Su,"'").replaceAll(Eu,"`")),E=g(E),E=E.flatMap(P=>y(P)),E=E.map(P=>P.startsWith('"')&&P.endsWith('"')||P.startsWith("'")&&P.endsWith("'")||P.startsWith("`")&&P.endsWith("`")?P.slice(1,-1):P),E}m.convertTagTolist=u;function h(C,v,E){for(let w of e){let{validation:T}=w.opts,P=false;if(T instanceof RegExp?P=T.test(C.join(" ")):T instanceof S.ZodType&&(P=T.safeParse(C).success),P)return w.fn(C,v)}E?.silent||j.error("The operation is not valid",C);}m.convertOperation=h;function c(C){return p(C)}m.convertListStringToObj=c;function p(C){if(C.length===0)return {};if(C.length%2!==0)throw j.error("The props list must have a pair number of elements",C),new Error("The props list must have a pair number of elements");let v="{";C.forEach((E,w)=>{if(w%2===0)v+=`"${E}": `;else {switch(E){case "null":case "undefined":case "true":case "false":v+=`${E}`;break;default:f(E)?(E=d(E),v+=`"${E}"`):E.startsWith("{")&&E.endsWith("}")?v+=`${E}`:E.startsWith('"')&&E.endsWith('"')?v+=`${E}`:Number.isNaN(parseFloat(E))?v+=`"${E}"`:v+=`${E}`;}w<C.length-1&&(v+=", ");}}),v+="}";try{return An.parse(v)}catch(E){throw j.error("Error parsing ink json",v),E}}function d(C){return C.startsWith('"')&&C.endsWith('"')||C.startsWith("'")&&C.endsWith("'")||C.startsWith("`")&&C.endsWith("`")?C.substring(1,C.length-1):C}function f(C){return !!(C.startsWith('"')&&C.endsWith('"')||C.startsWith("'")&&C.endsWith("'")||C.startsWith("`")&&C.endsWith("`"))}function g(C){return b(C).tokens}m.mergeJsonBlocks=g;function b(C){let v=[],E=false;for(let w=0;w<C.length;w++){let T=C[w];if(T!=="{"){v.push(T);continue}let P=D(C,w);if(P===-1){v.push(T);continue}let L=b(C.slice(w+1,P)),ve=["{",...L.tokens,"}"],st=ve.join(" ");if(!L.hasInvalidMatchedBlock)try{An.parse(st),v.push(st),w=P;continue}catch{}E=true,v.push(...ve),w=P;}return {tokens:v,hasInvalidMatchedBlock:E}}function D(C,v){let E=0;for(let w=v;w<C.length;w++)if(C[w]==="{")E++;else if(C[w]==="}"&&(E--,E===0))return w;return -1}function y(C){if(C==="["||C==="]")return [C];let v=0,E=C.length,w=[];for(;v<E&&C[v]==="[";)w.push("["),v++;let T=[];for(;E>v&&C[E-1]==="]";)T.unshift("]"),E--;let P=C.slice(v,E);return P===""?[...w,...T]:[...w,P,...T]}})(exports.HashtagCommands||={});function Gp(r){exports.HashtagCommands.add(r);}function $p(r={}){function e(h){return h&&h.length>0?S__default.default.enum(Object.fromEntries(h.map(c=>[c,c]))):S__default.default.string()}exports.HashtagCommands.addMapper((h,c)=>{c.labelToOpen={label:h[1],type:"call"},c.goNextStep=void 0;},{name:"Call",deprecated:true,description:"Calls the label specified by the second token, then returns to the current position.\n\n```ink\n# call label_name\n```",validation:S__default.default.tuple([S__default.default.literal("call"),S__default.default.string()])}),exports.HashtagCommands.addMapper((h,c)=>{c.labelToOpen={label:h[1],type:"jump"},c.goNextStep=void 0;},{name:"Jump",deprecated:true,description:"Jumps to the label specified by the second token without returning.\n\n```ink\n# jump label_name\n```",validation:S__default.default.tuple([S__default.default.literal("jump"),S__default.default.string()])}),exports.HashtagCommands.addMapper((h,c)=>("dialogue"in c&&delete c.dialogue,"goNextStep"in c&&delete c.goNextStep,{type:"dialogue",operationType:"clean"}),{name:"Pause",description:"Clears the current dialogue and waits for user input before advancing.\n\n```ink\n# pause\n```",validation:S__default.default.tuple([S__default.default.literal("pause")])}),exports.HashtagCommands.addMapper((h,c)=>{c.goNextStep=true,c.glueEnabled=false;},{name:"Continue",description:"Forces the story to proceed to the next step automatically.\n\n```ink\n# continue\n```",validation:S__default.default.tuple([S__default.default.literal("continue")])}),exports.HashtagCommands.addMapper(h=>({type:"video",operationType:h[0],alias:h[2]}),{name:"Pause/Resume video",description:"Pauses or resumes a video canvas element identified by its alias.\n\n```ink\n# pause video <alias>\n# resume video <alias>\n```",validation:S__default.default.tuple([S__default.default.enum(["pause","resume"]),S__default.default.literal("video"),S__default.default.string()])}),exports.HashtagCommands.addMapper(h=>({type:h[1],operationType:h[0],aliases:h.slice(2)}),{name:"Load assets/bundle",description:`Loads (eagerly or lazily) a set of asset or bundle aliases.
60
60
 
61
61
  \`\`\`ink
62
62
  # load assets <alias...>
63
63
  # lazyload assets <alias...>
64
64
  # load bundle <alias...>
65
65
  # lazyload bundle <alias...>
66
- \`\`\``,validation:v__default.default.union([v__default.default.tuple([v__default.default.enum(["load","lazyload"]),v__default.default.literal("assets")]).rest(e(r.assetAliasIds)),v__default.default.tuple([v__default.default.enum(["load","lazyload"]),v__default.default.literal("bundle")]).rest(e(r.bundleIds))])}),exports.HashtagCommands.addMapper(l=>({type:"all",operationType:l[0]}),{name:"Pause/Resume/Stop all sounds",description:"Pauses, resumes, or stops all active sounds at once.\n\n```ink\n# pause all sounds\n# resume all sounds\n# stop all sounds\n```",validation:v__default.default.tuple([v__default.default.enum(["pause","resume","stop"]),v__default.default.literal("all"),v__default.default.enum(["sounds","sound"])])}),exports.HashtagCommands.addMapper(l=>({type:"sound",operationType:"pause",alias:l[2]}),{name:"Pause sound",description:"Pauses the sound identified by its alias.\n\n```ink\n# pause sound <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("pause"),v__default.default.literal("sound"),v__default.default.string()])}),exports.HashtagCommands.addMapper(l=>({type:"channel",operationType:"pause",alias:l[2]}),{name:"Pause channel",description:"Pauses the audio channel identified by its alias.\n\n```ink\n# pause channel <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("pause"),v__default.default.literal("channel"),v__default.default.string()])}),exports.HashtagCommands.addMapper(l=>({type:"sound",operationType:"resume",alias:l[2]}),{name:"Resume sound",description:"Resumes the sound identified by its alias.\n\n```ink\n# resume sound <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("resume"),v__default.default.literal("sound"),v__default.default.string()])}),exports.HashtagCommands.addMapper(l=>({type:"channel",operationType:"resume",alias:l[2]}),{name:"Resume channel",description:"Resumes the audio channel identified by its alias.\n\n```ink\n# resume channel <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("resume"),v__default.default.literal("channel"),v__default.default.string()])}),exports.HashtagCommands.addMapper(l=>({type:"sound",operationType:"stop",alias:l[2]}),{name:"Stop sound",description:"Stops the sound identified by its alias.\n\n```ink\n# stop sound <alias>\n```",validation:v__default.default.tuple([v__default.default.literal("stop"),v__default.default.literal("sound"),v__default.default.string()])}),exports.HashtagCommands.addMapper(l=>({type:"sound",operationType:"stop",alias:l[2]}),{name:"Remove sound",description:"Removes (stops) the sound identified by its alias.\n\n```ink\n# remove sound <alias>\n```",deprecated:true,validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("sound"),v__default.default.string()])}),exports.HashtagCommands.addMapper(l=>({type:"sound",operationType:"edit",alias:l[2],props:exports.HashtagCommands.convertListStringToObj(l.slice(3))}),{name:"Edit sound",description:"Edits the properties of a sound identified by its alias.\n\n```ink\n# edit sound <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("sound"),v__default.default.string()]).rest(v__default.default.string()).refine(l=>(l.length-3)%2===0)}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c={type:"sound",operationType:"play",alias:h,url:h};return l.length>3&&(c.props=exports.HashtagCommands.convertListStringToObj(l.slice(3))),c},{name:"Play sound",description:"Plays a sound using its alias as the URL, with optional key/value properties.\n\n```ink\n# play sound <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("play"),v__default.default.literal("sound"),v__default.default.string()]).rest(v__default.default.string()).refine(l=>(l.length-3)%2===0)}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c=l[3],d={type:"sound",operationType:"play",alias:h,url:c};return l.length>4&&(d.props=exports.HashtagCommands.convertListStringToObj(l.slice(4))),d},{name:"Play sound with source",description:"Plays a sound with an explicit source URL and optional key/value properties.\n \n```ink\n# play sound <alias> <source> [<key> <value> \u2026]\n```\n",validation:v__default.default.tuple([v__default.default.literal("play"),v__default.default.literal("sound"),v__default.default.string()]).rest(v__default.default.string()).refine(l=>l.length>3&&(l.length-3)%2!==0)});function t(l){let h=[],c=0,d="";for(let f of l)f.startsWith("{")?(c++,d+=f):f.endsWith("}")&&c>0?(c--,d+=f,c===0&&(h.push(d),d="")):c>0?d+=f:h.push(f);return h}function n(l,h){switch(l){case "dissolve":case "fade":case "movein":case "moveout":case "zoomin":case "zoomout":case "pushin":case "pushout":break;default:return}let c={type:l};if(h.length>0)try{c.props=exports.HashtagCommands.convertListStringToObj(h);}catch{}return c}function i(l,h,c){let d,f;c.length%2===0?(d=h,f=c):(d=c[0],f=c.slice(1));let m={type:l,operationType:"show",alias:h,url:d};if(f.length>0){if(f.includes("with")&&f.length>f.indexOf("with")+1){let g=f[f.indexOf("with")+1],b=f.slice(f.indexOf("with")+2);f=f.slice(0,f.indexOf("with"));let S=n(g,b);S!==void 0&&(m.transition=S);}f.length>0&&(m.props=exports.HashtagCommands.convertListStringToObj(f));}return m}function a(l,h){let c,d;h.length%2===0?(c=l,d=h):(c=h[0],d=h.slice(1));let f={type:"text",operationType:"show",alias:l,text:c};if(d.length>0){if(d.includes("with")&&d.length>d.indexOf("with")+1){let m=d[d.indexOf("with")+1],g=d.slice(d.indexOf("with")+2);d=d.slice(0,d.indexOf("with"));let b=n(m,g);b!==void 0&&(f.transition=b);}d.length>0&&(f.props=exports.HashtagCommands.convertListStringToObj(d));}return f}function s(l,h,c){let d={type:l,operationType:"remove",alias:h};if(c.includes("with")&&c.length>c.indexOf("with")+1){let f=c[c.indexOf("with")+1],m=c.slice(c.indexOf("with")+2),g=n(f,m);g!==void 0&&(d.transition=g);}return d}function o(l,h){let c=S=>S.startsWith('"')&&S.endsWith('"')||S.startsWith("'")&&S.endsWith("'")||S.startsWith("`")&&S.endsWith("`")?S.substring(1,S.length-1):S,d=[],f=h.findIndex(S=>S.startsWith("[")),m=h.findIndex(S=>S.endsWith("]"));if(f===-1||m===-1){W.error("Show imagecontainer must have a list of image ulrs",h);return}if(d=h.slice(f,m+1),d.length<2){W.error("Show imagecontainer must have a list of image ulrs",h);return}d[0]==="["?d.shift():d[0]=d[0].substring(1),d[d.length-1]==="]"?d.pop():d[d.length-1]=d[d.length-1].substring(0,d[d.length-1].length-1);let g={type:"imagecontainer",operationType:"show",alias:l,urls:d.map(S=>c(S))},b=h.slice(m+1);if(b.length>0){if(b.includes("with")&&b.length>b.indexOf("with")+1){let S=b[b.indexOf("with")+1],y=b.slice(b.indexOf("with")+2);b=b.slice(0,b.indexOf("with"));let p=n(S,y);p!==void 0&&(g.transition=p);}b.length>0&&(g.props=exports.HashtagCommands.convertListStringToObj(b));}return g}function u(l){let h=l.slice(3),c=h.findIndex(g=>g.startsWith("[")),d=h.findIndex(g=>g.endsWith("]"));if(c===-1||d===-1||d<c)return;let f=h.slice(d+1),m=f.indexOf("with");return m===-1?{beforeWith:f,afterWith:[]}:{beforeWith:f.slice(0,m),afterWith:f.slice(m+1)}}exports.HashtagCommands.addMapper(l=>({alias:l[1],type:"shake",props:exports.HashtagCommands.convertListStringToObj(l.slice(2))}),{name:"Shake",description:"Applies shake effect to a canvas alias with optional key/value parameters.\n\n```ink\n# shake <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("shake"),v__default.default.string()]).rest(v__default.default.string()).refine(l=>(l.length-2)%2===0)}),exports.HashtagCommands.addMapper(l=>{let h=l.slice(2),c=h,d=[];if(h.includes("options")){let m=h.indexOf("options");c=h.slice(0,m),d=h.slice(m+1);}return {alias:l[1],type:"animate",keyframes:exports.HashtagCommands.convertListStringToObj(c),options:exports.HashtagCommands.convertListStringToObj(d)}},{name:"Animate",description:"Animates a canvas alias with keyframes and optional options section, both in key/value pairs.\n\n```ink\n# animate <alias> [<key> <value> \u2026] [options <key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("animate"),v__default.default.string()]).rest(v__default.default.string()).refine(l=>{let h=l.slice(2),c=h.indexOf("options");if(c===-1)return h.length%2===0;if(h.lastIndexOf("options")!==c)return false;let d=h.slice(0,c),f=h.slice(c+1);return d.length%2===0&&f.length%2===0})}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c=t(l.slice(3));return i("image",h,c)},{name:"Show image",description:"Shows an image canvas element with optional source URL, key/value properties, and transition effect.\n\n```ink\n# show image <alias> [<source>] [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("image"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>o(l[2],t(l.slice(3))),{name:"Show imagecontainer",description:"Shows an image-container canvas element with a list of image URLs and optional key/value properties.\n\n```ink\n# show imagecontainer <alias> [ <url1> <url2> \u2026 ] [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string()).refine(l=>{let h=u(l);return h===void 0?false:h.afterWith.length===0&&h.beforeWith.length%2===0})}),exports.HashtagCommands.addMapper(l=>o(l[2],t(l.slice(3))),{name:"Show imagecontainer with transition",description:"Shows an image-container canvas element with a list of image URLs, optional properties, and a transition effect.\n\n```ink\n# show imagecontainer <alias> [ <url1> <url2> \u2026 ] [<key> <value> \u2026] with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string()).refine(l=>{let h=u(l);return h===void 0?false:h.afterWith.length===1&&h.beforeWith.length%2===0})}),exports.HashtagCommands.addMapper(l=>o(l[2],t(l.slice(3))),{name:"Show imagecontainer with transition and props",description:"Shows an image-container canvas element with a list of image URLs, optional properties, a transition effect, and transition key/value properties.\n\n```ink\n# show imagecontainer <alias> [ <url1> <url2> \u2026 ] [<key> <value> \u2026] with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout <key> <value> \u2026\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string()).refine(l=>{let h=u(l);return h===void 0?false:h.afterWith.length>1&&(h.afterWith.length-1)%2===0&&h.beforeWith.length%2===0})}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c=t(l.slice(3));return i("video",h,c)},{name:"Show video",description:"Shows a video canvas element with optional source URL, key/value properties, and transition effect.\n\n```ink\n# show video <alias> [<source>] [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("video"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>{let h=l[2];return a(h,l.slice(3))},{name:"Show text",description:"Shows a text canvas element with optional text content, key/value properties, and transition effect.\n\n```ink\n# show text <alias> [<text>] [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("show"),v__default.default.literal("text"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c=t(l.slice(3));return s("image",h,c)},{name:"Remove image",description:"Removes an image canvas element with an optional transition effect.\n\n```ink\n# remove image <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("image"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c=t(l.slice(3));return s("video",h,c)},{name:"Remove video",description:"Removes a video canvas element with an optional transition effect.\n\n```ink\n# remove video <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("video"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c=t(l.slice(3));return s("canvaselement",h,c)},{name:"Remove canvas element",description:"Removes a canvas element with an optional transition effect.\n\n```ink\n# remove canvaselement <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("canvaselement"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c=t(l.slice(3));return s("text",h,c)},{name:"Remove text",description:"Removes a text canvas element with an optional transition effect.\n\n```ink\n# remove text <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("text"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>{let h=l[2],c=t(l.slice(3));return s("imagecontainer",h,c)},{name:"Remove imagecontainer",description:"Removes an image-container canvas element with an optional transition effect.\n\n```ink\n# remove imagecontainer <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:v__default.default.tuple([v__default.default.literal("remove"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>({type:"image",operationType:"edit",alias:l[2],props:exports.HashtagCommands.convertListStringToObj(l.slice(3))}),{name:"Edit image",description:"Edits the properties of an image canvas element identified by its alias.\n\n```ink\n# edit image <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("image"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>({type:"imagecontainer",operationType:"edit",alias:l[2],props:exports.HashtagCommands.convertListStringToObj(l.slice(3))}),{name:"Edit imagecontainer",description:"Edits the properties of an image-container canvas element identified by its alias.\n\n```ink\n# edit imagecontainer <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("imagecontainer"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>({type:"canvaselement",operationType:"edit",alias:l[2],props:exports.HashtagCommands.convertListStringToObj(l.slice(3))}),{name:"Edit canvas element",description:"Edits the properties of a canvas element identified by its alias.\n\n```ink\n# edit canvaselement <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("canvaselement"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>({type:"video",operationType:"edit",alias:l[2],props:exports.HashtagCommands.convertListStringToObj(l.slice(3))}),{name:"Edit video",description:"Edits the properties of a video canvas element identified by its alias.\n\n```ink\n# edit video <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("video"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>({type:"text",operationType:"edit",alias:l[2],props:exports.HashtagCommands.convertListStringToObj(l.slice(3))}),{name:"Edit text",description:"Edits the properties of a text canvas element identified by its alias.\n\n```ink\n# edit text <alias> [<key> <value> \u2026]\n```",validation:v__default.default.tuple([v__default.default.literal("edit"),v__default.default.literal("text"),v__default.default.string()]).rest(v__default.default.string())}),exports.HashtagCommands.addMapper(l=>({type:"input",operationType:"request"}),{name:"Request input",description:"Requests player input without any additional constraints.\n\n```ink\n# request input\n```",validation:v__default.default.tuple([v__default.default.literal("request"),v__default.default.literal("input")])}),exports.HashtagCommands.addMapper(l=>{let h={type:"input",operationType:"request"};try{let c=exports.HashtagCommands.convertListStringToObj(l.slice(2));"type"in c&&typeof c.type=="string"&&(h.valueType=c.type),"default"in c&&(h.defaultValue=c.default);}catch{}return h},{name:"Request input with params",description:"Requests player input with optional key/value parameters (e.g. type, default).\n\n```ink\n# request input <key> <value> [<key> <value> \u2026]\n# request input type number default 18\n```",validation:v__default.default.tuple([v__default.default.literal("request"),v__default.default.literal("input")]).rest(v__default.default.string()).refine(l=>l.length>2&&(l.length-2)%2===0)});}function Gd(r){oe.translate=r;}async function $d(r,e={},t={}){let n=[];return r.labels&&Object.values(r.labels).forEach(i=>{n=n.concat(i);}),await oe.generateJsonTranslation(n,e,{...t,operationStringConvert:exports.HashtagCommands.run})}var bu=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],Au=["+","-","/","*","%","POW","RANDOM","L^"],xu=["INT","FLOOR","FLOAT"];function Jt(r,e){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 ia(e)+"_|_"+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(r);)t++,r=r.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(r)&&e){let n=r.substring(1);return ia(e,t)+"_|_"+n.replaceAll(".","_|_")}return r.replaceAll(".","_|_")||ia(e,t).replaceAll(".","_|_")}function ia(r,e=0){let t=r.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var wu="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function ze(r){return r.startsWith("^")&&(r=r.substring(1)),r=r.replaceAll("\\\\",wu),r=r.replaceAll("\\n",`
67
- `),r=r.replaceAll("\\t"," "),r=r.replaceAll(" "," "),r=r.replaceAll(wu,"\\\\"),r}function ft(r,e,t,n){let{functions:i}=n;r=r.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return r.forEach(s=>{if(typeof s=="string")switch(s){case "&&":case "||":if(a.length>=2){let o={type:"union",unionType:s==="&&"?"and":"or",conditions:[a[a.length-2],a[a.length-1]]};a.pop(),a.pop(),a.push(o);}break;case "!":if(a.length===0)W.error("Error parsing ink file: Conditional statement is not valid",r);else {let o={type:"union",unionType:"not",condition:a[a.length-1]};a[a.length-1]=o;}break;case "!?":if(a.length>1){let o={type:"union",unionType:"not",condition:{type:"compare",operator:"CONTAINS",leftValue:a[a.length-2],rightValue:a[a.length-1]}};a.pop(),a.pop(),a.push(o);}else W.error("Error parsing ink file: Conditional statement is not valid",r);break;default:if(cu.includes(s))if(a.length<2)W.error("Error parsing ink file: Conditional statement is not valid",r);else {let o={type:"compare",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(Au.includes(s))if(a.length<2)W.error("Error parsing ink file: Conditional statement is not valid",r);else {s==="L^"&&(s="INTERSECTION");let o={type:"arithmetic",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(xu.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(ze(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),u=o.pop(),l=o.pop();if(l===void 0||u===void 0){W.error("Error parsing ink file: Conditional statement is not valid",r);return}let h=Number(l),c=o.join(".");if(c.includes("^.")){let f=c.split("."),m=f[f.length-1].replaceAll(".","_|_");f.pop(),c=`${f.join(".")}.${m}`,u.includes("c-")&&(c=c+"_|_"+u);}else c=c.replaceAll(".","_|_");let d=Jt(c,e);if(!d)return;a.push({type:"compare",leftValue:ra(d),operator:">=",rightValue:{type:"value",value:h}});}else {let o=Jt(s["CNT?"],e);if(!o)return;a.push(ra(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(Pt({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],u=i.find(h=>h.name===o);if(!u){W.error(`Error parsing ink file: Function ${o} is not defined`,r);return}let l=[];for(let h=0;h<u.args;h++)a.length!==0&&l.push(a.pop());a.push({type:"function",functionName:o,args:l.reverse()});}else if(typeof s=="object"&&"^->"in s)s["^->"].includes("$r")||a.push(s["^->"]);else if(typeof s=="object"&&"list"in s){let o=Object.values(s.list).map(u=>u);a.push(o);}else a.push(s);}),a}function sa(r,e,t,n){return ft(r,e,t,n)}function Pt(r,e,t){let{key:n,defaultType:i}=r,a=e.indexOf(n);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:i,key:n}}function xn(r,e,t){let{key:n,value:i,defaultType:a,artmeticValue:s}=r,o=e.indexOf(n);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:i}];if(s){if(typeof i=="object"&&"list"in i){let u=Object.values(i.list).map(l=>l);return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:u}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:i}]}else if(typeof i=="object"){if("list"in i&&typeof i.list=="object"){if("origins"in i&&Array.isArray(i.origins)&&i.origins.length>0)return i.origins.reduce(u=>(u.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(t.enums[n])}),Object.entries(t.enums[n]).forEach(([l,h])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${l}`,value:h});}),u),[]);{let u=new Set,l=Object.entries(i.list).reduce((h,[c,d])=>{let[f,m]=c.split(".");return h.push({type:"value",storageOperationType:"set",storageType:a,key:m,value:d}),u.add(f),h},[]);return u.forEach(h=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:h,value:Object.values(t.enums[h])});}),n in t.enums?Object.entries(t.enums[n]).forEach(([h,c])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${h}`,value:c});}):l.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(i.list)}),l}}else if(typeof i=="object"&&"VAR?"in i){if(typeof i["VAR?"]=="string"&&i["VAR?"].includes(".")){let[u,l]=i["VAR?"].split(".");if(u in t.enums&&l in t.enums[u])return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:t.enums[u][l]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:Pt({key:i["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:i}]}function ra(r){return {type:"value",storageType:"label",storageOperationType:"get",label:r}}function aa(r,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(r)?"call":"jump"}function Ei(r,e){if(e){if(typeof e=="string")e.startsWith("^")&&r.push(ze(e));else if(typeof e=="object"&&"type"in e)switch(e.type){case "value":case "function":console.warn("Warning: trying to add a value or function operation as text. This is likely a mistake, so it will be ignored.");break;default:r.push(e);}}}function oa(r,e,t,n,i,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:u=false}=a;return Hd(r,e,t,n,i,{isNewLine:s,isHashtagScript:o,isThreads:u})}function Hd(r,e,t,n,i,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:u}=a;if(o){if(Array.isArray(e)&&e.length>0){let l={goNextStep:true},h=[];try{if(e.length===1&&typeof e[0]=="string"&&!e[0].match(Ci)){let c=e[0],d=exports.HashtagCommands.convertTagTolist(c),f=exports.HashtagCommands.convertOperation(d,l,{silent:!0});f&&(f.$origin=c,h.push(f));}}catch{}h.length===0&&h.push({type:"operationtoconvert",values:e}),r.push({...l,operations:h});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&r.length>0){let l=r[r.length-1];!l.glueEnabled&&!l.operations&&!l.labelToOpen&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),r[r.length-1]=l;}typeof e=="string"?r.push(zd(ze(e),n.characterIds)):r.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")r.push({end:"game_end"});else if(e==="done")r.push({end:"label_end",goNextStep:true});else if(e==="<>")if(r.length>0){let l=r[r.length-1];l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true),r[r.length-1]=l;}else r.push({glueEnabled:true,goNextStep:false});}else if(typeof e=="object"){if("type"in e)switch(e.type){case "value":e.storageOperationType==="set"?(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=ze(e.value)),r.push({goNextStep:true,operations:[e]})):console.warn("Warning: trying to add a value get operation as step. This is likely a mistake, so it will be ignored.");break;case "function":r.push({goNextStep:true,operations:[e]});break;default:if(!s&&r.length>0){let l=r[r.length-1];!l.glueEnabled&&!l.operations&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),r[r.length-1]=l;}r.push({conditionalStep:e});}else if("->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&r.length>0&&r[r.length-1]?.dialogue===void 0&&(l=void 0),!s&&r.length>0){let h=r[r.length-1];h.labelToOpen||(h.goNextStep=true),r[r.length-1]=h;}if(e.params&&e.params.length===0&&delete e.params,e.var)r.push({labelToOpen:{label:Pt({key:e["->"],defaultType:"storage"},i),type:u?"call":"jump",params:e.params},glueEnabled:l});else {let h=Jt(e["->"],t);if(!h)return;r.push({labelToOpen:{label:h,type:aa(h,u),params:e.params},glueEnabled:l});}}else if("->t->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&r.length>0&&r[r.length-1]?.dialogue===void 0&&(l=void 0),!s&&r.length>0){let c=r[r.length-1];c.labelToOpen||(c.goNextStep=true),r[r.length-1]=c;}e.params&&e.params.length===0&&delete e.params;let h=Jt(e["->t->"],t);if(!h)return;r.push({labelToOpen:{label:h,type:"call",params:e.params},glueEnabled:l});}}}function zd(r,e){let t;if(r.includes(": ")){let n=r.split(": "),i=n[0],a=n.slice(1).join(": ");(e?.has(i)||characters.RegisteredCharacters.has(i))&&(t=i,r=a);}return t?{dialogue:{character:t,text:r}}:{dialogue:r}}function la(r,e,t,n=true,i=false){return Ud(r,e,t,n,i)}function Ud(r,e,t,n,i=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?r.push(ze(e)):r.push(e):typeof e=="object"&&"type"in e&&r.push(e));}function Di(r,e,t,n){if(r.length===0){W.error("Error parsing ink file: Arithmetic statement is not valid",r);return}let i=ft(r,e,t,n);if(i.length===1){let a=i[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function Ht(r,e,t,n="",i,a,s=void 0){let o=[],u="sequential",l=false,h=true;r.forEach(f=>{f==="%"&&(u="loop"),f==="seq"&&(u="random"),f==="MIN"&&(l=true);});let c=r[r.length-1];return Object.keys(c).forEach(f=>{let m=c[f];if(Array.isArray(m)&&m.length>3){m=m.slice(1,m.length-2);let g=[];mt(m,n,i,g,e,e,t,zt,s,true,a),g.length===1?o.push(g[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:g});}else Array.isArray(m)&&m.length===3&&(h=false);}),u==="sequential"?{type:"stepswitch",elements:o,choiceType:u,end:h?"lastItem":void 0,nestedId:s}:l&&u==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:h?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:u}}function mt(r,e,t,n=[],i,a,s,o,u=void 0,l=true,h=[]){let c=false,d=[],f=false,m=false,g=false,b=[],S=[];if(t.preDialog[e]&&(l=false,i(n,`^${t.preDialog[e].text}`,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),t.preDialog[e].glue&&i(n,"<>",e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),delete t.preDialog[e]),r.includes("visit")){let p=Ht(r,a,s,e,t,h,u);p&&(!l&&n.length>0&&i(n,"<>",e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),i(n,p,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}));return}let y=r[0];if(y&&typeof y=="object"&&"temp="in y){for(;r[0]&&typeof r[0]=="object"&&"temp="in r[0];)h.push(r[0]["temp="]),r.shift();h=h.reverse();}if(r.forEach((p,D)=>{if(m){if(typeof p=="string"&&p==="/#"){let C=[];mt(S,e,t,C,la,la,s,o,u,l),i(n,C,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),m=false,S=[];}else S.push(p);return}else if(c)if(Array.isArray(p))d.push(p);else if(p&&typeof p=="object")"CNT?"in p?D>0&&r[D-1]==="ev"?(f=true,b.push(p)):f?b.push(p):(d.push(p),l=false):"VAR="in p||"temp="in p?xn({key:"VAR="in p?p["VAR="]:p["temp="],value:r[D-1],defaultType:"VAR="in p?"storage":"tempstorage"},h,t).forEach(E=>{if(E.value&&typeof E.value=="string"&&E.value==="/str"&&(E.value=r[D-2]),E.value&&typeof E.value=="object"&&"^->"in E.value&&(E.value=E.value["^->"]),d.length>1){let w=Di(d,e,h,t);d=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"&&(E.value=w.operation);}(typeof E.key!="string"||!E.key.includes("$r"))&&(i(n,E,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),l=true);}):"VAR?"in p?d.push(p):"^->"in p?p["^->"].includes("$r")||d.push(p):("f()"in p||"list"in p&&typeof p.list=="object")&&d.push(p);else switch(p){case "/ev":f&&b.push(p),c=false,d.push(p);break;case "out":if(d.length>0){let C=d[d.length-1];if(C&&typeof C=="object"&&"VAR?"in C){d.pop();let E=Pt({key:C["VAR?"],defaultType:"storage"},h);i(n,E,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g});}else {let E=[];for(;d.length>0&&d[d.length-1]!=="/ev";)E.push(d.pop());E=E.reverse();let w=Di(E,e,h,t);d=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"?i(n,{storageOperationType:"get",storageType:"logic",operation:w.operation,type:"value"},e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}):(i(n,"<>",e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),w=`^${w}`,i(n,w,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}));}l=false;}break;case "pop":{let C=d[d.length-1];if(C&&typeof C=="object"&&"f()"in C){let E=[];for(;d.length>0&&d[d.length-1]!=="/ev";)E.push(d.pop());E=E.reverse();let w=ft(E,e,h,t);d=[],w.forEach(P=>{P&&typeof P=="object"&&"type"in P&&P.type==="function"?i(n,P,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}):W.warn("Unhandled case: value is not a function",P);}),l=false;}else d.push(p);return}default:d.push(p);}else if(typeof p=="string")if(p.startsWith("^"))i(n,p,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),l=false;else if(p==="ev")c=true;else if(p===`
68
- `)l=true;else if(p==="done"||p==="end")i(n,p,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),l=false;else if(p==="<>")i(n,p,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),l=false;else if(p==="nop"&&f){let C=_u(b,a,s,e,t,h,u);C&&i(n,C,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),f=false,b=[];}else p==="#"?m=true:p==="thread"&&(g=true);else if(Array.isArray(p))if(f)b.push(p);else if(p.length>1&&typeof p[p.length-2]=="object"&&p[p.length-2]&&"c"in p[p.length-2]&&typeof p[p.length-1]=="object"&&p[p.length-1]&&"b"in p[p.length-1]){d.pop();let C=[],E=[];for(;d.length>0&&d[d.length-1]!=="/ev";)C.push(d.pop());b=[...b,...C.reverse()],f=true,E.push(p.pop()),E.push(p.pop()),b=[...b,...p],b.push(E);}else if(p.length>1&&typeof p[p.length-1]=="object"&&p[p.length-1]&&"#n"in p[p.length-1]){let C=p.pop();if(!C){W.error("Error parsing ink file: el is undefined");return}let E=C["#n"];delete C["#n"],p.push(C),i(n,{"->":e?e+"_|_"+E:E},e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),s({[E]:p},e,t);}else mt(p,e,t,n,i,a,s,o,u,l,h);else if(p&&typeof p=="object")if("->"in p&&typeof p["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(p["->"])){let C=[];d.length>0&&(C=sa(["ev",...d],e,h,t)),p.params=C,i(n,p,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),l=false;}else if("->t->"in p&&typeof p["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(p["->t->"])){let C=[];d.length>0&&(C=sa(["ev",...d],e,h,t)),p.params=C,i(n,p,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g}),l=false;}else if("*"in p&&typeof p["*"]=="string")p["*"].includes("c")&&(d.push(p),l=false);else if("s"in p&&Array.isArray(p.s))d.push(p),l=false;else if("CNT?"in p)d.push(p),l=false;else if("VAR="in p||"temp="in p){let C="VAR="in p?p["VAR="]:p["temp="],E,w=[];if(C!=="$r"){for(d.pop(),d[d.length-1]==="/ev"&&d.pop();d.length>0&&d[d.length-1]!=="/ev";)w.push(d.pop());w=w.reverse(),E=Di(w,e,h,t),d=[],xn({key:C,value:E,defaultType:"VAR="in p?"storage":"tempstorage",artmeticValue:true},h,t).forEach(N=>{(N.value!==void 0||N.value!==null)&&i(n,N,e,t,h,{isNewLine:l,isHashtagScript:m,isThreads:g});}),l=false;}}else s(p,e,t);}),o(d,n,e,t,h),e.includes("_|_")&&n.length===2){let p=n[0],D=n[1];p&&D&&typeof p=="object"&&"dialogue"in p&&typeof D=="object"&&"labelToOpen"in D&&p.dialogue===" "&&D.labelToOpen&&(n.shift(),delete D.glueEnabled,n[0]=D);}}function ha(r,e,t,n,i,a){if(e.length===0)return;let s=ft(e,n,t,i);if(s.length===1){let o={type:"ifelse",condition:s[0],then:r,else:a};return o.else||delete o.else,o}else if(s.length>1){let o={type:"ifelse",condition:{type:"union",unionType:"and",conditions:s},then:r,else:a};return o.else||delete o.else,o}}function _u(r,e,t,n,i,a,s=void 0){if(r.length===0){W.error("Error parsing ink file: Conditional statement is not valid",r);return}let o=[],u=[];if(r.forEach(c=>{Array.isArray(c)?u.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);}),u.length===0){W.error("Error parsing ink file: Conditional statement is not valid",u);return}let l=ua(u[0],e,t,`${n}${"_|_"}then`,i,a,`${s||""}then`),h;return u.length===2?h=ua(u[1],e,t,`${n}${"_|_"}else`,i,a,`${s||""}else`):u.length>2?(u.shift(),u.push("nop"),u=[{b:u}],h=ua(u,e,t,n,i,a,`${s||""}else`)):h=void 0,i.du=void 0,ha(l,o,a,n,i,h)}function ua(r,e,t,n,i,a,s=void 0){let o=[];for(let l of r)typeof l=="object"&&"b"in l&&(l.b=l.b.filter(h=>h!==null&&!(typeof h=="object"&&"->"in h&&new RegExp(/.*\.[0-9]/).test(h["->"]))),mt(l.b,n,i,o,e,e,t,zt,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function ca(r="",e=""){let t=Array.isArray(r)?r:[r],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function zt(r,e,t,n,i){if(r.length>0){let a={};Tu(r,a,i,n);for(let[s,o]of Object.entries(a)){let u=t+"_|_"+s,l={text:o.text.length===1?o.text[0]:o.text,label:u,props:{},type:aa(u,false),oneTime:o.onetime};o.text.length===0&&(l.onlyHaveNoChoice=true,l.autoSelect=true),l.oneTime===false&&delete l.oneTime;let h=ha(l,o.conditions,i,t,n)||l,c=e[e.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),e.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let d=c.choices;d&&Array.isArray(d)?d.push(h):W.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,d),c.choices=d.sort((f,m)=>{try{let g=f.label.split("."),b=g[g.length-1].replaceAll(".","_|_"),S=m.label.split("."),y=S[S.length-1].replaceAll(".","_|_");if(b.includes("c-")&&y.includes("c-")){let p=b.split("c-")[1],D=Number(p),C=y.split("c-")[1],E=Number(C);return D-E}}catch{}return 0});}else e.push({choices:[h]});o.preDialog&&(n.preDialog[u]={...o.preDialog});}}}function Tu(r,e,t,n,i){let a=[],s="",o="",u=false,l=[];for(let h=0;h<r.length;h++){let c=r[h];if(typeof c=="string")c.startsWith("^")?a.push(ze(c)):bu.includes(c)&&l.push(c);else if(Array.isArray(c)&&c.includes("visit")){let d=Ht(c,Ei,(f,m,g)=>{},i,n,t);a.push(d);}else if(c&&typeof c=="object")if("*"in c&&typeof c["*"]&&typeof c["*"]=="string")c["*"].includes("c")&&(s=`c${c["*"].split("c")[1]}`,c.flg&16&&(u=true));else if("s"in c&&Array.isArray(c.s)){let d=Ou(c.s),f=c.s.includes("<>");d&&(i&&e[i]?(e[i].preDialog={text:d,glue:f},e[i].text=ca(d,e[i].text)):(a.push(d),o=d));}else ("CNT?"in c||"VAR?"in c)&&l.push(c);else l.push(c);if(s){e[s]?e[s].text=ca(a,e[s].text):e[s]={text:a,onetime:u,conditions:l},o&&(e[s].preDialog={text:o,glue:false});let d=r.slice(h+1);Tu(d,e,t,n,s);return}}}function Ou(r){for(let e of r)if(typeof e=="string"){if(e.startsWith("^"))return ze(e)}else if(Array.isArray(e)){let t=Ou(e);if(t)return t}}var da;(i=>{function r(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:u=[],enums:l={},functions:h=[],preDialog:c={},characterIds:d}=s,f={$schema:hu};if(f.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:u,enums:l,functions:h,preDialog:c,characterIds:d}),f.labels&&gi in f.labels){let m=f.labels[gi];delete f.labels[gi],m.forEach(g=>{g.operations&&(f.initialOperations=f.initialOperations?[...f.initialOperations,...g.operations]:[...g.operations]);});}if(f.labels&&_t in f.labels){let m=f.labels[_t];delete f.labels[_t],m.forEach(g=>{g.operations&&(f.initialOperations=f.initialOperations?[...f.initialOperations,...g.operations]:[...g.operations]);});}return o.forEach(m=>{f.labels&&m in f.labels&&delete f.labels[m];}),u.forEach(m=>{f.initialOperations&&(f.initialOperations=f.initialOperations.filter(g=>!(g.type==="value"&&g.key===m)));}),f}i.inkToJson=r;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){W.error("Error parsing ink file",o);}}function t(a,s,o){for(let u of a)if(u)if(Array.isArray(u))if(u.includes("visit")){let l=Ht(u,Ei,(h,c,d)=>{},"",o,[]);l&&(o.externalSwitch=l);}else t(u,s,o);else typeof u=="object"&&(u&&"VAR="in u&&o.externalSwitch&&(s[_t]||(s[_t]=[]),s[_t].push({operations:xn({defaultType:"storage",key:u["VAR="],value:o.externalSwitch},[],o)})),n(u,s,"",o));}function n(a,s,o="",u){if(a!==null){for(let[l,h]of Object.entries(a))if(Array.isArray(h)){let c=[],d={},f=(o?o+"_|_":"")+l;mt(h,f,u,c,oa,oa,(m,g,b)=>{n(m,d,g,b);},zt);for(let[m,g]of Object.entries(d))s[m]=g;c.length>0&&(s[f]=c);}}}})(da||={});var Ac=zs(Dc()),xc=zs(Ut()),WC=/(?:^|<>)\s*#\s*([^\r\n]+)/g,jC=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,qC=new Set(["DONE","END"]),MC="_|_",bc=new Map;function wc(r,e){let t=JSON.stringify([e,r]),n=bc.get(t);if(n)return n;let i=new RegExp(r,e);return bc.set(t,i),i}function hi(r,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(s=>hi(r,s));let i=t.oneOf;if(Array.isArray(i))return i.some(s=>hi(r,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>hi(r,s));if(typeof t.const=="string")return r===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===r);if(t.type!=="string"||typeof t.minLength=="number"&&r.length<t.minLength||typeof t.maxLength=="number"&&r.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!wc(t.pattern,"").test(r))return !1}catch{return false}return true}function Js(r,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(o=>Js(r,o));let i=t.oneOf;if(Array.isArray(i))return i.some(o=>Js(r,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>Js(r,o));if(t.type!=="array"||typeof t.minItems=="number"&&r.length<t.minItems||typeof t.maxItems=="number"&&r.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(r.length<s.length)return false;for(let o=0;o<s.length;o++)if(!hi(r[o],s[o]))return false;return r.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:r.slice(s.length).every(o=>hi(o,t.items))}function GC(r,e){if(e.type==="regexp")try{let t=wc(e.source,e.flags);return t.lastIndex=0,t.test(r.join(" "))}catch{return false}return e.type==="literal"?r.join(" ")===e.value:Js(r,e.schema)}function $C(r){let e=r.split(/\r?\n/),t=[];for(let n=0;n<e.length;n++){let i=e[n];for(let a of i.matchAll(WC)){let s=(a[1]??"").trim();if(!s)continue;let o=exports.HashtagCommands.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:n+1,command:s,tokens:o});}}return t}var Vl;(i=>{function r(a,s={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let o=[];try{return {json:new Ac.Compiler(a,{errorHandler:(c,d)=>{let f=c.replace(/^[A-Z]+: line \d+: ?/,""),m=c.match(/line (\d+)/);o.push({message:f,type:d,line:m?Number(m[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:c=>c,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:o}}catch{let l=false,h={...s,textSource:a};return e(o,()=>{l=true;},h),l?r(h.textSource,s):{issues:o}}}i.compile=r;function e(a,s,o){let{functions:u,initialVarsToRemove:l,labelToRemove:h}=o,c=a.find(d=>d.type===xc.ErrorType.Error);if(c){if(c.message.includes("Divert target not found")){let d=c.message.match(/Divert target not found: '-> (\w+)'/);if(d?.[1]){let f=d[1],m=`
66
+ \`\`\``,validation:S__default.default.union([S__default.default.tuple([S__default.default.enum(["load","lazyload"]),S__default.default.literal("assets")]).rest(e(r.assetAliasIds)),S__default.default.tuple([S__default.default.enum(["load","lazyload"]),S__default.default.literal("bundle")]).rest(e(r.bundleIds))])}),exports.HashtagCommands.addMapper(h=>({type:"all",operationType:h[0]}),{name:"Pause/Resume/Stop all sounds",description:"Pauses, resumes, or stops all active sounds at once.\n\n```ink\n# pause all sounds\n# resume all sounds\n# stop all sounds\n```",validation:S__default.default.tuple([S__default.default.enum(["pause","resume","stop"]),S__default.default.literal("all"),S__default.default.enum(["sounds","sound"])])}),exports.HashtagCommands.addMapper(h=>({type:"sound",operationType:"pause",alias:h[2]}),{name:"Pause sound",description:"Pauses the sound identified by its alias.\n\n```ink\n# pause sound <alias>\n```",validation:S__default.default.tuple([S__default.default.literal("pause"),S__default.default.literal("sound"),S__default.default.string()])}),exports.HashtagCommands.addMapper(h=>({type:"channel",operationType:"pause",alias:h[2]}),{name:"Pause channel",description:"Pauses the audio channel identified by its alias.\n\n```ink\n# pause channel <alias>\n```",validation:S__default.default.tuple([S__default.default.literal("pause"),S__default.default.literal("channel"),S__default.default.string()])}),exports.HashtagCommands.addMapper(h=>({type:"sound",operationType:"resume",alias:h[2]}),{name:"Resume sound",description:"Resumes the sound identified by its alias.\n\n```ink\n# resume sound <alias>\n```",validation:S__default.default.tuple([S__default.default.literal("resume"),S__default.default.literal("sound"),S__default.default.string()])}),exports.HashtagCommands.addMapper(h=>({type:"channel",operationType:"resume",alias:h[2]}),{name:"Resume channel",description:"Resumes the audio channel identified by its alias.\n\n```ink\n# resume channel <alias>\n```",validation:S__default.default.tuple([S__default.default.literal("resume"),S__default.default.literal("channel"),S__default.default.string()])}),exports.HashtagCommands.addMapper(h=>({type:"sound",operationType:"stop",alias:h[2]}),{name:"Stop sound",description:"Stops the sound identified by its alias.\n\n```ink\n# stop sound <alias>\n```",validation:S__default.default.tuple([S__default.default.literal("stop"),S__default.default.literal("sound"),S__default.default.string()])}),exports.HashtagCommands.addMapper(h=>({type:"sound",operationType:"stop",alias:h[2]}),{name:"Remove sound",description:"Removes (stops) the sound identified by its alias.\n\n```ink\n# remove sound <alias>\n```",deprecated:true,validation:S__default.default.tuple([S__default.default.literal("remove"),S__default.default.literal("sound"),S__default.default.string()])}),exports.HashtagCommands.addMapper(h=>({type:"sound",operationType:"edit",alias:h[2],props:exports.HashtagCommands.convertListStringToObj(h.slice(3))}),{name:"Edit sound",description:"Edits the properties of a sound identified by its alias.\n\n```ink\n# edit sound <alias> [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("edit"),S__default.default.literal("sound"),S__default.default.string()]).rest(S__default.default.string()).refine(h=>(h.length-3)%2===0)}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p={type:"sound",operationType:"play",alias:c,url:c};return h.length>3&&(p.props=exports.HashtagCommands.convertListStringToObj(h.slice(3))),p},{name:"Play sound",description:"Plays a sound using its alias as the URL, with optional key/value properties.\n\n```ink\n# play sound <alias> [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("play"),S__default.default.literal("sound"),e(r.assetAliasIds)]).rest(S__default.default.string()).refine(h=>(h.length-3)%2===0)}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=h[3],d={type:"sound",operationType:"play",alias:c,url:p};return h.length>4&&(d.props=exports.HashtagCommands.convertListStringToObj(h.slice(4))),d},{name:"Play sound with source",description:"Plays a sound with an explicit source URL and optional key/value properties.\n \n```ink\n# play sound <alias> <source> [<key> <value> \u2026]\n```\n",validation:S__default.default.tuple([S__default.default.literal("play"),S__default.default.literal("sound"),S__default.default.string(),e(r.assetAliasIds)]).rest(S__default.default.string()).refine(h=>h.length>3&&(h.length-3)%2!==0)});function t(h){let c=[],p=0,d="";for(let f of h)f.startsWith("{")?(p++,d+=f):f.endsWith("}")&&p>0?(p--,d+=f,p===0&&(c.push(d),d="")):p>0?d+=f:c.push(f);return c}function n(h,c){switch(h){case "dissolve":case "fade":case "movein":case "moveout":case "zoomin":case "zoomout":case "pushin":case "pushout":break;default:return}let p={type:h};if(c.length>0)try{p.props=exports.HashtagCommands.convertListStringToObj(c);}catch{}return p}function i(h,c,p){let d,f;p.length%2===0?(d=c,f=p):(d=p[0],f=p.slice(1));let g={type:h,operationType:"show",alias:c,url:d};if(f.length>0){if(f.includes("with")&&f.length>f.indexOf("with")+1){let b=f[f.indexOf("with")+1],D=f.slice(f.indexOf("with")+2);f=f.slice(0,f.indexOf("with"));let y=n(b,D);y!==void 0&&(g.transition=y);}f.length>0&&(g.props=exports.HashtagCommands.convertListStringToObj(f));}return g}function a(h,c){let p,d;c.length%2===0?(p=h,d=c):(p=c[0],d=c.slice(1));let f={type:"text",operationType:"show",alias:h,text:p};if(d.length>0){if(d.includes("with")&&d.length>d.indexOf("with")+1){let g=d[d.indexOf("with")+1],b=d.slice(d.indexOf("with")+2);d=d.slice(0,d.indexOf("with"));let D=n(g,b);D!==void 0&&(f.transition=D);}d.length>0&&(f.props=exports.HashtagCommands.convertListStringToObj(d));}return f}function s(h,c,p){let d={type:h,operationType:"remove",alias:c};if(p.includes("with")&&p.length>p.indexOf("with")+1){let f=p[p.indexOf("with")+1],g=p.slice(p.indexOf("with")+2),b=n(f,g);b!==void 0&&(d.transition=b);}return d}function o(h,c){let p=y=>y.startsWith('"')&&y.endsWith('"')||y.startsWith("'")&&y.endsWith("'")||y.startsWith("`")&&y.endsWith("`")?y.substring(1,y.length-1):y,d=c.indexOf("["),f=c.indexOf("]",d+1);if(d===-1||f===-1){j.error("Show imagecontainer must have a list of image ulrs",c);return}let g=c.slice(d+1,f);if(g.length===0){j.error("Show imagecontainer must have a list of image ulrs",c);return}let b={type:"imagecontainer",operationType:"show",alias:h,urls:g.map(y=>p(y))},D=c.slice(f+1);if(D.length>0){if(D.includes("with")&&D.length>D.indexOf("with")+1){let y=D[D.indexOf("with")+1],m=D.slice(D.indexOf("with")+2);D=D.slice(0,D.indexOf("with"));let C=n(y,m);C!==void 0&&(b.transition=C);}D.length>0&&(b.props=exports.HashtagCommands.convertListStringToObj(D));}return b}function l(h){let c=h.indexOf("]",4);if(c===-1)return;let p=h.slice(4,c),d=h.slice(c+1),f=d.indexOf("with");return f===-1?{urls:p,beforeWith:d,afterWith:[]}:{urls:p,beforeWith:d.slice(0,f),afterWith:d.slice(f+1)}}exports.HashtagCommands.addMapper(h=>({alias:h[1],type:"shake",props:exports.HashtagCommands.convertListStringToObj(h.slice(2))}),{name:"Shake",description:"Applies shake effect to a canvas alias with optional key/value parameters.\n\n```ink\n# shake <alias> [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("shake"),S__default.default.string()]).rest(S__default.default.string()).refine(h=>(h.length-2)%2===0)}),exports.HashtagCommands.addMapper(h=>{let c=h.slice(2),p=c,d=[];if(c.includes("options")){let g=c.indexOf("options");p=c.slice(0,g),d=c.slice(g+1);}return {alias:h[1],type:"animate",keyframes:exports.HashtagCommands.convertListStringToObj(p),options:exports.HashtagCommands.convertListStringToObj(d)}},{name:"Animate",description:"Animates a canvas alias with keyframes and optional options section, both in key/value pairs.\n\n```ink\n# animate <alias> [<key> <value> \u2026] [options <key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("animate"),S__default.default.string()]).rest(S__default.default.string()).refine(h=>{let c=h.slice(2),p=c.indexOf("options");if(p===-1)return c.length%2===0;if(c.lastIndexOf("options")!==p)return false;let d=c.slice(0,p),f=c.slice(p+1);return d.length%2===0&&f.length%2===0})}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return i("image",c,p)},{name:"Show image",description:"Shows an image canvas element with optional source URL, key/value properties, and transition effect.\n\n```ink\n# show image <alias> [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("show"),S__default.default.literal("image"),e(r.assetAliasIds)]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return i("image",c,p)},{name:"Show image with source",description:"Shows an image canvas element with optional source URL, key/value properties, and transition effect.\n\n```ink\n# show image <alias> <source> [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("show"),S__default.default.literal("image"),S__default.default.string(),e(r.assetAliasIds)]).rest(S__default.default.string())});let u=e(r.assetAliasIds);exports.HashtagCommands.addMapper(h=>o(h[2],t(h.slice(3))),{name:"Show imagecontainer",description:"Shows an image-container canvas element with a list of image URLs and optional key/value properties.\n\n```ink\n# show imagecontainer <alias> [ <source1> <ursource2> \u2026 ] [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("show"),S__default.default.literal("imagecontainer"),S__default.default.string(),S__default.default.literal("[")]).rest(S__default.default.string()).refine(h=>{let c=l(h);return c===void 0?false:c.urls.length>0&&c.urls.every(p=>u.safeParse(p).success)&&c.afterWith.length===0&&c.beforeWith.length%2===0})}),exports.HashtagCommands.addMapper(h=>o(h[2],t(h.slice(3))),{name:"Show imagecontainer with transition",description:"Shows an image-container canvas element with a list of image URLs, optional properties, and a transition effect.\n\n```ink\n# show imagecontainer <alias> [ <ursource1> <source2> \u2026 ] [<key> <value> \u2026] with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout\n```",validation:S__default.default.tuple([S__default.default.literal("show"),S__default.default.literal("imagecontainer"),S__default.default.string(),S__default.default.literal("[")]).rest(S__default.default.string()).refine(h=>{let c=l(h);return c===void 0?false:c.urls.length>0&&c.urls.every(p=>u.safeParse(p).success)&&c.afterWith.length===1&&c.beforeWith.length%2===0})}),exports.HashtagCommands.addMapper(h=>o(h[2],t(h.slice(3))),{name:"Show imagecontainer with transition and props",description:"Shows an image-container canvas element with a list of image URLs, optional properties, a transition effect, and transition key/value properties.\n\n```ink\n# show imagecontainer <alias> [ <url1> <url2> \u2026 ] [<key> <value> \u2026] with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout <key> <value> \u2026\n```",validation:S__default.default.tuple([S__default.default.literal("show"),S__default.default.literal("imagecontainer"),S__default.default.string(),S__default.default.literal("[")]).rest(S__default.default.string()).refine(h=>{let c=l(h);return c===void 0?false:c.urls.length>0&&c.urls.every(p=>u.safeParse(p).success)&&c.afterWith.length>1&&(c.afterWith.length-1)%2===0&&c.beforeWith.length%2===0})}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return i("video",c,p)},{name:"Show video",description:"Shows a video canvas element with optional source URL, key/value properties, and transition effect.\n\n```ink\n# show video <alias> [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("show"),S__default.default.literal("video"),e(r.assetAliasIds)]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return i("video",c,p)},{name:"Show video",description:"Shows a video canvas element with optional source URL, key/value properties, and transition effect.\n\n```ink\n# show video <alias> <source> [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("show"),S__default.default.literal("video"),S__default.default.string(),e(r.assetAliasIds)]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>{let c=h[2];return a(c,h.slice(3))},{name:"Show text",description:"Shows a text canvas element with optional text content, key/value properties, and transition effect.\n\n```ink\n# show text <alias> [<text>] [<key> <value> \u2026] [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("show"),S__default.default.literal("text"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return s("image",c,p)},{name:"Remove image",description:"Removes an image canvas element with an optional transition effect.\n\n```ink\n# remove image <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("remove"),S__default.default.literal("image"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return s("video",c,p)},{name:"Remove video",description:"Removes a video canvas element with an optional transition effect.\n\n```ink\n# remove video <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("remove"),S__default.default.literal("video"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return s("canvaselement",c,p)},{name:"Remove canvas element",description:"Removes a canvas element with an optional transition effect.\n\n```ink\n# remove canvaselement <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("remove"),S__default.default.literal("canvaselement"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return s("text",c,p)},{name:"Remove text",description:"Removes a text canvas element with an optional transition effect.\n\n```ink\n# remove text <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("remove"),S__default.default.literal("text"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>{let c=h[2],p=t(h.slice(3));return s("imagecontainer",c,p)},{name:"Remove imagecontainer",description:"Removes an image-container canvas element with an optional transition effect.\n\n```ink\n# remove imagecontainer <alias> [with dissolve|fade|movein|moveout|zoomin|zoomout|pushin|pushout [<key> <value> \u2026]]\n```",validation:S__default.default.tuple([S__default.default.literal("remove"),S__default.default.literal("imagecontainer"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(()=>({type:"canvas",operationType:"clear"}),{name:"Clear canvas",description:"Removes every element currently on the canvas.\n\n```ink\n# clear canvas\n```",validation:S__default.default.tuple([S__default.default.literal("clear"),S__default.default.literal("canvas")])}),exports.HashtagCommands.addMapper(h=>({type:"image",operationType:"edit",alias:h[2],props:exports.HashtagCommands.convertListStringToObj(h.slice(3))}),{name:"Edit image",description:"Edits the properties of an image canvas element identified by its alias.\n\n```ink\n# edit image <alias> [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("edit"),S__default.default.literal("image"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>({type:"imagecontainer",operationType:"edit",alias:h[2],props:exports.HashtagCommands.convertListStringToObj(h.slice(3))}),{name:"Edit imagecontainer",description:"Edits the properties of an image-container canvas element identified by its alias.\n\n```ink\n# edit imagecontainer <alias> [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("edit"),S__default.default.literal("imagecontainer"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>({type:"canvaselement",operationType:"edit",alias:h[2],props:exports.HashtagCommands.convertListStringToObj(h.slice(3))}),{name:"Edit canvas element",description:"Edits the properties of a canvas element identified by its alias.\n\n```ink\n# edit canvaselement <alias> [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("edit"),S__default.default.literal("canvaselement"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>({type:"video",operationType:"edit",alias:h[2],props:exports.HashtagCommands.convertListStringToObj(h.slice(3))}),{name:"Edit video",description:"Edits the properties of a video canvas element identified by its alias.\n\n```ink\n# edit video <alias> [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("edit"),S__default.default.literal("video"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>({type:"text",operationType:"edit",alias:h[2],props:exports.HashtagCommands.convertListStringToObj(h.slice(3))}),{name:"Edit text",description:"Edits the properties of a text canvas element identified by its alias.\n\n```ink\n# edit text <alias> [<key> <value> \u2026]\n```",validation:S__default.default.tuple([S__default.default.literal("edit"),S__default.default.literal("text"),S__default.default.string()]).rest(S__default.default.string())}),exports.HashtagCommands.addMapper(h=>({type:"input",operationType:"request"}),{name:"Request input",description:"Requests player input without any additional constraints.\n\n```ink\n# request input\n```",validation:S__default.default.tuple([S__default.default.literal("request"),S__default.default.literal("input")])}),exports.HashtagCommands.addMapper(h=>{let c={type:"input",operationType:"request"};try{let p=exports.HashtagCommands.convertListStringToObj(h.slice(2));"type"in p&&typeof p.type=="string"&&(c.valueType=p.type),"default"in p&&(c.defaultValue=p.default);}catch{}return c},{name:"Request input with params",description:"Requests player input with optional key/value parameters (e.g. type, default).\n\n```ink\n# request input <key> <value> [<key> <value> \u2026]\n# request input type number default 18\n```",validation:S__default.default.tuple([S__default.default.literal("request"),S__default.default.literal("input")]).rest(S__default.default.string()).refine(h=>h.length>2&&(h.length-2)%2===0)});}function Jp(r){oe.translate=r;}async function Hp(r,e={},t={}){let n=[];return r.labels&&Object.values(r.labels).forEach(i=>{n=n.concat(i);}),await oe.generateJsonTranslation(n,e,{...t,operationStringConvert:exports.HashtagCommands.run})}var Au=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],wu=["+","-","/","*","%","POW","RANDOM","L^"],xu=["INT","FLOOR","FLOAT"];function Jt(r,e){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 na(e)+"_|_"+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(r);)t++,r=r.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(r)&&e){let n=r.substring(1);return na(e,t)+"_|_"+n.replaceAll(".","_|_")}return r.replaceAll(".","_|_")||na(e,t).replaceAll(".","_|_")}function na(r,e=0){let t=r.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var _u="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Ue(r){return r.startsWith("^")&&(r=r.substring(1)),r=r.replaceAll("\\\\",_u),r=r.replaceAll("\\n",`
67
+ `),r=r.replaceAll("\\t"," "),r=r.replaceAll(" "," "),r=r.replaceAll(_u,"\\\\"),r}function mt(r,e,t,n){let{functions:i}=n;r=r.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return r.forEach(s=>{if(typeof s=="string")switch(s){case "&&":case "||":if(a.length>=2){let o={type:"union",unionType:s==="&&"?"and":"or",conditions:[a[a.length-2],a[a.length-1]]};a.pop(),a.pop(),a.push(o);}break;case "!":if(a.length===0)j.error("Error parsing ink file: Conditional statement is not valid",r);else {let o={type:"union",unionType:"not",condition:a[a.length-1]};a[a.length-1]=o;}break;case "!?":if(a.length>1){let o={type:"union",unionType:"not",condition:{type:"compare",operator:"CONTAINS",leftValue:a[a.length-2],rightValue:a[a.length-1]}};a.pop(),a.pop(),a.push(o);}else j.error("Error parsing ink file: Conditional statement is not valid",r);break;default:if(cu.includes(s))if(a.length<2)j.error("Error parsing ink file: Conditional statement is not valid",r);else {let o={type:"compare",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(wu.includes(s))if(a.length<2)j.error("Error parsing ink file: Conditional statement is not valid",r);else {s==="L^"&&(s="INTERSECTION");let o={type:"arithmetic",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(xu.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(Ue(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),l=o.pop(),u=o.pop();if(u===void 0||l===void 0){j.error("Error parsing ink file: Conditional statement is not valid",r);return}let h=Number(u),c=o.join(".");if(c.includes("^.")){let d=c.split("."),f=d[d.length-1].replaceAll(".","_|_");d.pop(),c=`${d.join(".")}.${f}`,l.includes("c-")&&(c=c+"_|_"+l);}else c=c.replaceAll(".","_|_");let p=Jt(c,e);if(!p)return;a.push({type:"compare",leftValue:ia(p),operator:">=",rightValue:{type:"value",value:h}});}else {let o=Jt(s["CNT?"],e);if(!o)return;a.push(ia(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(Ft({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],l=i.find(h=>h.name===o);if(!l){j.error(`Error parsing ink file: Function ${o} is not defined`,r);return}let u=[];for(let h=0;h<l.args;h++)a.length!==0&&u.push(a.pop());a.push({type:"function",functionName:o,args:u.reverse()});}else if(typeof s=="object"&&"^->"in s)s["^->"].includes("$r")||a.push(s["^->"]);else if(typeof s=="object"&&"list"in s){let o=Object.values(s.list).map(l=>l);a.push(o);}else a.push(s);}),a}function ra(r,e,t,n){return mt(r,e,t,n)}function Ft(r,e,t){let{key:n,defaultType:i}=r,a=e.indexOf(n);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:i,key:n}}function wn(r,e,t){let{key:n,value:i,defaultType:a,artmeticValue:s}=r,o=e.indexOf(n);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:i}];if(s){if(typeof i=="object"&&"list"in i){let l=Object.values(i.list).map(u=>u);return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:l}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:i}]}else if(typeof i=="object"){if("list"in i&&typeof i.list=="object"){if("origins"in i&&Array.isArray(i.origins)&&i.origins.length>0)return i.origins.reduce(l=>(l.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(t.enums[n])}),Object.entries(t.enums[n]).forEach(([u,h])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${u}`,value:h});}),l),[]);{let l=new Set,u=Object.entries(i.list).reduce((h,[c,p])=>{let[d,f]=c.split(".");return h.push({type:"value",storageOperationType:"set",storageType:a,key:f,value:p}),l.add(d),h},[]);return l.forEach(h=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:h,value:Object.values(t.enums[h])});}),n in t.enums?Object.entries(t.enums[n]).forEach(([h,c])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${h}`,value:c});}):u.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(i.list)}),u}}else if(typeof i=="object"&&"VAR?"in i){if(typeof i["VAR?"]=="string"&&i["VAR?"].includes(".")){let[l,u]=i["VAR?"].split(".");if(l in t.enums&&u in t.enums[l])return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:t.enums[l][u]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:Ft({key:i["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:i}]}function ia(r){return {type:"value",storageType:"label",storageOperationType:"get",label:r}}function sa(r,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(r)?"call":"jump"}function Si(r,e){if(e){if(typeof e=="string")e.startsWith("^")&&r.push(Ue(e));else if(typeof e=="object"&&"type"in e)switch(e.type){case "value":case "function":console.warn("Warning: trying to add a value or function operation as text. This is likely a mistake, so it will be ignored.");break;default:r.push(e);}}}function aa(r,e,t,n,i,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:l=false}=a;return Up(r,e,t,n,i,{isNewLine:s,isHashtagScript:o,isThreads:l})}function Up(r,e,t,n,i,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:l}=a;if(o){if(Array.isArray(e)&&e.length>0){let u={goNextStep:true},h=[];try{if(e.length===1&&typeof e[0]=="string"){let c=e[0],p=exports.HashtagCommands.convertTagTolist(c),d=exports.HashtagCommands.convertOperation(p,u,{silent:!0});d&&(d.$origin=c,h.push(d));}}catch{}h.length===0&&h.push({type:"operationtoconvert",values:e}),r.push({...u,operations:h});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&r.length>0){let u=r[r.length-1];!u.glueEnabled&&!u.operations&&!u.labelToOpen&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),r[r.length-1]=u;}typeof e=="string"?r.push(Kp(Ue(e),n.characterIds)):r.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")r.push({end:"game_end"});else if(e==="done")r.push({end:"label_end",goNextStep:true});else if(e==="<>")if(r.length>0){let u=r[r.length-1];u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true),r[r.length-1]=u;}else r.push({glueEnabled:true,goNextStep:false});}else if(typeof e=="object"){if("type"in e)switch(e.type){case "value":e.storageOperationType==="set"?(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=Ue(e.value)),r.push({goNextStep:true,operations:[e]})):console.warn("Warning: trying to add a value get operation as step. This is likely a mistake, so it will be ignored.");break;case "function":r.push({goNextStep:true,operations:[e]});break;default:if(!s&&r.length>0){let u=r[r.length-1];!u.glueEnabled&&!u.operations&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),r[r.length-1]=u;}r.push({conditionalStep:e});}else if("->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&r.length>0&&r[r.length-1]?.dialogue===void 0&&(u=void 0),!s&&r.length>0){let h=r[r.length-1];h.labelToOpen||(h.goNextStep=true),r[r.length-1]=h;}if(e.params&&e.params.length===0&&delete e.params,e.var)r.push({labelToOpen:{label:Ft({key:e["->"],defaultType:"storage"},i),type:l?"call":"jump",params:e.params},glueEnabled:u});else {let h=Jt(e["->"],t);if(!h)return;r.push({labelToOpen:{label:h,type:sa(h,l),params:e.params},glueEnabled:u});}}else if("->t->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&r.length>0&&r[r.length-1]?.dialogue===void 0&&(u=void 0),!s&&r.length>0){let c=r[r.length-1];c.labelToOpen||(c.goNextStep=true),r[r.length-1]=c;}e.params&&e.params.length===0&&delete e.params;let h=Jt(e["->t->"],t);if(!h)return;r.push({labelToOpen:{label:h,type:"call",params:e.params},glueEnabled:u});}}}function Kp(r,e){let t;if(r.includes(": ")){let n=r.split(": "),i=n[0],a=n.slice(1).join(": ");(e?.has(i)||characters.RegisteredCharacters.has(i))&&(t=i,r=a);}return t?{dialogue:{character:t,text:r}}:{dialogue:r}}function oa(r,e,t,n=true,i=false){return Xp(r,e,t,n,i)}function Xp(r,e,t,n,i=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?r.push(Ue(e)):r.push(e):typeof e=="object"&&"type"in e&&r.push(e));}function Ei(r,e,t,n){if(r.length===0){j.error("Error parsing ink file: Arithmetic statement is not valid",r);return}let i=mt(r,e,t,n);if(i.length===1){let a=i[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function Ht(r,e,t,n="",i,a,s=void 0){let o=[],l="sequential",u=false,h=true;r.forEach(d=>{d==="%"&&(l="loop"),d==="seq"&&(l="random"),d==="MIN"&&(u=true);});let c=r[r.length-1];return Object.keys(c).forEach(d=>{let f=c[d];if(Array.isArray(f)&&f.length>3){f=f.slice(1,f.length-2);let g=[];gt(f,n,i,g,e,e,t,zt,s,true,a),g.length===1?o.push(g[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:g});}else Array.isArray(f)&&f.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 gt(r,e,t,n=[],i,a,s,o,l=void 0,u=true,h=[]){let c=false,p=[],d=false,f=false,g=false,b=[],D=[];if(t.preDialog[e]&&(u=false,i(n,`^${t.preDialog[e].text}`,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),t.preDialog[e].glue&&i(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),delete t.preDialog[e]),r.includes("visit")){let m=Ht(r,a,s,e,t,h,l);m&&(!u&&n.length>0&&i(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),i(n,m,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}));return}let y=r[0];if(y&&typeof y=="object"&&"temp="in y){for(;r[0]&&typeof r[0]=="object"&&"temp="in r[0];)h.push(r[0]["temp="]),r.shift();h=h.reverse();}if(r.forEach((m,C)=>{if(f){if(typeof m=="string"&&m==="/#"){let v=[];gt(D,e,t,v,oa,oa,s,o,l,u),i(n,v,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),f=false,D=[];}else D.push(m);return}else if(c)if(Array.isArray(m))p.push(m);else if(m&&typeof m=="object")"CNT?"in m?C>0&&r[C-1]==="ev"?(d=true,b.push(m)):d?b.push(m):(p.push(m),u=false):"VAR="in m||"temp="in m?wn({key:"VAR="in m?m["VAR="]:m["temp="],value:r[C-1],defaultType:"VAR="in m?"storage":"tempstorage"},h,t).forEach(E=>{if(E.value&&typeof E.value=="string"&&E.value==="/str"&&(E.value=r[C-2]),E.value&&typeof E.value=="object"&&"^->"in E.value&&(E.value=E.value["^->"]),p.length>1){let w=Ei(p,e,h,t);p=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"&&(E.value=w.operation);}(typeof E.key!="string"||!E.key.includes("$r"))&&(i(n,E,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),u=true);}):"VAR?"in m?p.push(m):"^->"in m?m["^->"].includes("$r")||p.push(m):("f()"in m||"list"in m&&typeof m.list=="object")&&p.push(m);else switch(m){case "/ev":d&&b.push(m),c=false,p.push(m);break;case "out":if(p.length>0){let v=p[p.length-1];if(v&&typeof v=="object"&&"VAR?"in v){p.pop();let E=Ft({key:v["VAR?"],defaultType:"storage"},h);i(n,E,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g});}else {let E=[];for(;p.length>0&&p[p.length-1]!=="/ev";)E.push(p.pop());E=E.reverse();let w=Ei(E,e,h,t);p=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"?i(n,{storageOperationType:"get",storageType:"logic",operation:w.operation,type:"value"},e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}):(i(n,"<>",e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),w=`^${w}`,i(n,w,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}));}u=false;}break;case "pop":{let v=p[p.length-1];if(v&&typeof v=="object"&&"f()"in v){let E=[];for(;p.length>0&&p[p.length-1]!=="/ev";)E.push(p.pop());E=E.reverse();let w=mt(E,e,h,t);p=[],w.forEach(T=>{T&&typeof T=="object"&&"type"in T&&T.type==="function"?i(n,T,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}):j.warn("Unhandled case: value is not a function",T);}),u=false;}else p.push(m);return}default:p.push(m);}else if(typeof m=="string")if(m.startsWith("^"))i(n,m,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),u=false;else if(m==="ev")c=true;else if(m===`
68
+ `)u=true;else if(m==="done"||m==="end")i(n,m,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),u=false;else if(m==="<>")i(n,m,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),u=false;else if(m==="nop"&&d){let v=Ou(b,a,s,e,t,h,l);v&&i(n,v,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),d=false,b=[];}else m==="#"?f=true:m==="thread"&&(g=true);else if(Array.isArray(m))if(d)b.push(m);else if(m.length>1&&typeof m[m.length-2]=="object"&&m[m.length-2]&&"c"in m[m.length-2]&&typeof m[m.length-1]=="object"&&m[m.length-1]&&"b"in m[m.length-1]){p.pop();let v=[],E=[];for(;p.length>0&&p[p.length-1]!=="/ev";)v.push(p.pop());b=[...b,...v.reverse()],d=true,E.push(m.pop()),E.push(m.pop()),b=[...b,...m],b.push(E);}else if(m.length>1&&typeof m[m.length-1]=="object"&&m[m.length-1]&&"#n"in m[m.length-1]){let v=m.pop();if(!v){j.error("Error parsing ink file: el is undefined");return}let E=v["#n"];delete v["#n"],m.push(v),i(n,{"->":e?e+"_|_"+E:E},e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),s({[E]:m},e,t);}else gt(m,e,t,n,i,a,s,o,l,u,h);else if(m&&typeof m=="object")if("->"in m&&typeof m["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(m["->"])){let v=[];p.length>0&&(v=ra(["ev",...p],e,h,t)),m.params=v,i(n,m,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),u=false;}else if("->t->"in m&&typeof m["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(m["->t->"])){let v=[];p.length>0&&(v=ra(["ev",...p],e,h,t)),m.params=v,i(n,m,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g}),u=false;}else if("*"in m&&typeof m["*"]=="string")m["*"].includes("c")&&(p.push(m),u=false);else if("s"in m&&Array.isArray(m.s))p.push(m),u=false;else if("CNT?"in m)p.push(m),u=false;else if("VAR="in m||"temp="in m){let v="VAR="in m?m["VAR="]:m["temp="],E,w=[];if(v!=="$r"){for(p.pop(),p[p.length-1]==="/ev"&&p.pop();p.length>0&&p[p.length-1]!=="/ev";)w.push(p.pop());w=w.reverse(),E=Ei(w,e,h,t),p=[],wn({key:v,value:E,defaultType:"VAR="in m?"storage":"tempstorage",artmeticValue:true},h,t).forEach(P=>{(P.value!==void 0||P.value!==null)&&i(n,P,e,t,h,{isNewLine:u,isHashtagScript:f,isThreads:g});}),u=false;}}else s(m,e,t);}),o(p,n,e,t,h),e.includes("_|_")&&n.length===2){let m=n[0],C=n[1];m&&C&&typeof m=="object"&&"dialogue"in m&&typeof C=="object"&&"labelToOpen"in C&&m.dialogue===" "&&C.labelToOpen&&(n.shift(),delete C.glueEnabled,n[0]=C);}}function ua(r,e,t,n,i,a){if(e.length===0)return;let s=mt(e,n,t,i);if(s.length===1){let o={type:"ifelse",condition:s[0],then:r,else:a};return o.else||delete o.else,o}else if(s.length>1){let o={type:"ifelse",condition:{type:"union",unionType:"and",conditions:s},then:r,else:a};return o.else||delete o.else,o}}function Ou(r,e,t,n,i,a,s=void 0){if(r.length===0){j.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){j.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=la(l[0],e,t,`${n}${"_|_"}then`,i,a,`${s||""}then`),h;return l.length===2?h=la(l[1],e,t,`${n}${"_|_"}else`,i,a,`${s||""}else`):l.length>2?(l.shift(),l.push("nop"),l=[{b:l}],h=la(l,e,t,n,i,a,`${s||""}else`)):h=void 0,i.du=void 0,ua(u,o,a,n,i,h)}function la(r,e,t,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["->"]))),gt(u.b,n,i,o,e,e,t,zt,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function ha(r="",e=""){let t=Array.isArray(r)?r:[r],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function zt(r,e,t,n,i){if(r.length>0){let a={};Pu(r,a,i,n);for(let[s,o]of Object.entries(a)){let l=t+"_|_"+s,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:sa(l,false),oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let h=ua(u,o.conditions,i,t,n)||u,c=e[e.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),e.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let p=c.choices;p&&Array.isArray(p)?p.push(h):j.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,p),c.choices=p.sort((d,f)=>{try{let g=d.label.split("."),b=g[g.length-1].replaceAll(".","_|_"),D=f.label.split("."),y=D[D.length-1].replaceAll(".","_|_");if(b.includes("c-")&&y.includes("c-")){let m=b.split("c-")[1],C=Number(m),v=y.split("c-")[1],E=Number(v);return C-E}}catch{}return 0});}else e.push({choices:[h]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function Pu(r,e,t,n,i){let a=[],s="",o="",l=false,u=[];for(let h=0;h<r.length;h++){let c=r[h];if(typeof c=="string")c.startsWith("^")?a.push(Ue(c)):Au.includes(c)&&u.push(c);else if(Array.isArray(c)&&c.includes("visit")){let p=Ht(c,Si,(d,f,g)=>{},i,n,t);a.push(p);}else if(c&&typeof c=="object")if("*"in c&&typeof c["*"]&&typeof c["*"]=="string")c["*"].includes("c")&&(s=`c${c["*"].split("c")[1]}`,c.flg&16&&(l=true));else if("s"in c&&Array.isArray(c.s)){let p=Tu(c.s),d=c.s.includes("<>");p&&(i&&e[i]?(e[i].preDialog={text:p,glue:d},e[i].text=ha(p,e[i].text)):(a.push(p),o=p));}else ("CNT?"in c||"VAR?"in c)&&u.push(c);else u.push(c);if(s){e[s]?e[s].text=ha(a,e[s].text):e[s]={text:a,onetime:l,conditions:u},o&&(e[s].preDialog={text:o,glue:false});let p=r.slice(h+1);Pu(p,e,t,n,s);return}}}function Tu(r){for(let e of r)if(typeof e=="string"){if(e.startsWith("^"))return Ue(e)}else if(Array.isArray(e)){let t=Tu(e);if(t)return t}}var ca;(i=>{function r(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:l=[],enums:u={},functions:h=[],preDialog:c={},characterIds:p}=s,d={$schema:hu};if(d.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:l,enums:u,functions:h,preDialog:c,characterIds:p}),d.labels&&gi in d.labels){let f=d.labels[gi];delete d.labels[gi],f.forEach(g=>{g.operations&&(d.initialOperations=d.initialOperations?[...d.initialOperations,...g.operations]:[...g.operations]);});}if(d.labels&&Ot in d.labels){let f=d.labels[Ot];delete d.labels[Ot],f.forEach(g=>{g.operations&&(d.initialOperations=d.initialOperations?[...d.initialOperations,...g.operations]:[...g.operations]);});}return o.forEach(f=>{d.labels&&f in d.labels&&delete d.labels[f];}),l.forEach(f=>{d.initialOperations&&(d.initialOperations=d.initialOperations.filter(g=>!(g.type==="value"&&g.key===f)));}),d}i.inkToJson=r;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){j.error("Error parsing ink file",o);}}function t(a,s,o){for(let l of a)if(l)if(Array.isArray(l))if(l.includes("visit")){let u=Ht(l,Si,(h,c,p)=>{},"",o,[]);u&&(o.externalSwitch=u);}else t(l,s,o);else typeof l=="object"&&(l&&"VAR="in l&&o.externalSwitch&&(s[Ot]||(s[Ot]=[]),s[Ot].push({operations:wn({defaultType:"storage",key:l["VAR="],value:o.externalSwitch},[],o)})),n(l,s,"",o));}function n(a,s,o="",l){if(a!==null){for(let[u,h]of Object.entries(a))if(Array.isArray(h)){let c=[],p={},d=(o?o+"_|_":"")+u;gt(h,d,l,c,aa,aa,(f,g,b)=>{n(f,p,g,b);},zt);for(let[f,g]of Object.entries(p))s[f]=g;c.length>0&&(s[d]=c);}}}})(ca||={});var wc=Hs(bc()),xc=Hs(Ut());var MC=/(?:^|<>)\s*#\s*([^\r\n]+)/g,GC=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,$C=new Set(["DONE","END"]),JC="_|_",Ac=new Map;function _c(r,e){let t=JSON.stringify([e,r]),n=Ac.get(t);if(n)return n;let i=new RegExp(r,e);return Ac.set(t,i),i}function hi(r,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(s=>hi(r,s));let i=t.oneOf;if(Array.isArray(i))return i.some(s=>hi(r,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>hi(r,s));if(typeof t.const=="string")return r===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===r);if(t.type!=="string"||typeof t.minLength=="number"&&r.length<t.minLength||typeof t.maxLength=="number"&&r.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!_c(t.pattern,"").test(r))return !1}catch{return false}return true}function $s(r,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(o=>$s(r,o));let i=t.oneOf;if(Array.isArray(i))return i.some(o=>$s(r,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>$s(r,o));if(t.type!=="array"||typeof t.minItems=="number"&&r.length<t.minItems||typeof t.maxItems=="number"&&r.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(r.length<s.length)return false;for(let o=0;o<s.length;o++)if(!hi(r[o],s[o]))return false;return r.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:r.slice(s.length).every(o=>hi(o,t.items))}function HC(r,e){if(e.type==="regexp")try{let t=_c(e.source,e.flags);return t.lastIndex=0,t.test(r.join(" "))}catch{return false}return e.type==="literal"?r.join(" ")===e.value:$s(r,e.schema)}function zC(r){let e=r.split(/\r?\n/),t=[];for(let n=0;n<e.length;n++){let i=e[n];for(let a of i.matchAll(MC)){let s=(a[1]??"").trim();if(!s)continue;let o=exports.HashtagCommands.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:n+1,command:s,tokens:o});}}return t}function Oc(r){return r.keyword==="required"&&typeof r.params?.missingProperty=="string"?r.params.missingProperty:r.instancePath.split("/").pop()||"(root)"}function UC(r,e){let t=e.split("/").filter(Boolean).map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~")),n=r,i,a=s=>{s&&typeof s=="object"&&typeof s.$origin=="string"&&(i=s.$origin);};a(n);for(let s of t){if(n===null||typeof n!="object")break;n=n[s],a(n);}return i}function KC(r){let e=r.map(o=>o.instancePath),t=o=>e.some(l=>l!==o&&l.startsWith(`${o}/`)),n=r.filter(o=>!t(o.instancePath)),i=new Map;for(let o of n){let l=i.get(o.instancePath)??[];l.push(o),i.set(o.instancePath,l);}let a=[];for(let o of i.values()){let l=o.filter(u=>u.keyword!=="anyOf"&&u.keyword!=="oneOf");a.push(...l.length>0?l:o);}let s=new Set;return a.filter(o=>{let l=`${Oc(o)}|${o.message}`;return s.has(l)?false:(s.add(l),true)})}var Il;(s=>{function r(o,l={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let u=[];try{return {json:new wc.Compiler(o,{errorHandler:(d,f)=>{let g=d.replace(/^[A-Z]+: line \d+: ?/,""),b=d.match(/line (\d+)/);u.push({message:g,type:f,line:b?Number(b[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:d=>d,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:u}}catch{let c=false,p={...l,textSource:o};return e(u,()=>{c=true;},p),c?r(p.textSource,l):{issues:u}}}s.compile=r;function e(o,l,u){let{functions:h,initialVarsToRemove:c,labelToRemove:p}=u,d=o.find(f=>f.type===xc.ErrorType.Error);if(d){if(d.message.includes("Divert target not found")){let f=d.message.match(/Divert target not found: '-> (\w+)'/);if(f?.[1]){let g=f[1],b=`
69
69
 
70
- === ${f} ===
70
+ === ${g} ===
71
71
 
72
- -> DONE`;return o.textSource=o.textSource.concat(m),h.push(f),s()}}if(c.message.includes("Unresolved variable")){let d=c.message.match(/Unresolved variable: (\w+)/);if(d?.[1]){let f=d[1],m=`VAR ${f} = ""
72
+ -> DONE`;return u.textSource=u.textSource.concat(b),p.push(g),l()}}if(d.message.includes("Unresolved variable")){let f=d.message.match(/Unresolved variable: (\w+)/);if(f?.[1]){let g=f[1],b=`VAR ${g} = ""
73
73
 
74
- `;return o.textSource=m.concat(o.textSource),l.push(f),s()}}if(c.message.includes("Variable could not be found to assign to")){let d=c.message.match(/Variable could not be found to assign to: (\w+)/);if(d?.[1]){let f=d[1],m=`VAR ${f} = ""
74
+ `;return u.textSource=b.concat(u.textSource),c.push(g),l()}}if(d.message.includes("Variable could not be found to assign to")){let f=d.message.match(/Variable could not be found to assign to: (\w+)/);if(f?.[1]){let g=f[1],b=`VAR ${g} = ""
75
75
 
76
- `;return o.textSource=m.concat(o.textSource),l.push(f),s()}}if(c.message.includes("Variable could not be found to assign to")){let d=c.message.match(/Variable could not be found to assign to: '(\w+)'/);if(d?.[1]){let f=d[1],m=`VAR ${f} = ""
76
+ `;return u.textSource=b.concat(u.textSource),c.push(g),l()}}if(d.message.includes("Variable could not be found to assign to")){let f=d.message.match(/Variable could not be found to assign to: '(\w+)'/);if(f?.[1]){let g=f[1],b=`VAR ${g} = ""
77
77
 
78
- `;return o.textSource=m.concat(o.textSource),l.push(f),s()}}if(c.message.includes("Function call target not found")){let d=c.message.match(/Function call target not found: '-> (\w+)'/);if(d?.[1]){let f=d[1],m=`
78
+ `;return u.textSource=b.concat(u.textSource),c.push(g),l()}}if(d.message.includes("Function call target not found")){let f=d.message.match(/Function call target not found: '-> (\w+)'/);if(f?.[1]){let g=f[1],b=`
79
79
 
80
- === function ${f}() ===
80
+ === function ${g}() ===
81
81
 
82
82
  ~ return
83
83
 
84
- `;return o.textSource=o.textSource.concat(m),u.push({name:f,args:0}),h.push(f),s()}}if(c.message.includes(" arguments, but got ")){let d=c.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(d?.[1]){let f=d[1],m=parseInt(d[3]||"0",10),g=m>0?Array.from({length:m},(y,p)=>`arg${p+1}`).join(", "):"",b=`
84
+ `;return u.textSource=u.textSource.concat(b),h.push({name:g,args:0}),p.push(g),l()}}if(d.message.includes(" arguments, but got ")){let f=d.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(f?.[1]){let g=f[1],b=parseInt(f[3]||"0",10),D=b>0?Array.from({length:b},(C,v)=>`arg${v+1}`).join(", "):"",y=`
85
85
 
86
- === function ${f}(${g}) ===
86
+ === function ${g}(${D}) ===
87
87
 
88
88
  ~ return
89
89
 
90
- `;o.textSource=o.textSource.replaceAll(`
90
+ `;u.textSource=u.textSource.replaceAll(`
91
91
 
92
- === function ${f}() ===
92
+ === function ${g}() ===
93
93
 
94
94
  ~ return
95
95
 
96
- `,""),o.textSource=o.textSource.concat(b);let S=u.find(y=>y.name===f);return S?S.args=m:(u.push({name:f,args:m}),h.push(f)),s()}}if(c.message.includes("Could not find target for read count")){let d=c.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(d?.[1]){let f=d[1],[m,g]=f.split("."),b=`
96
+ `,""),u.textSource=u.textSource.concat(y);let m=h.find(C=>C.name===g);return m?m.args=b:(h.push({name:g,args:b}),p.push(g)),l()}}if(d.message.includes("Could not find target for read count")){let f=d.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(f?.[1]){let g=f[1],[b,D]=g.split("."),y=`
97
97
 
98
- LIST ${m} = ${g}
98
+ LIST ${b} = ${D}
99
99
 
100
- `;return o.textSource=o.textSource.concat(b),o.initialVarsToRemove.push(m),o.initialVarsToRemove.push(`${m}.${g}`),s()}}if(c.message.includes("variable for increment could not be found")){let d=c.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(d?.[1]){let f=d[1],m=`VAR ${f} = 0
100
+ `;return u.textSource=u.textSource.concat(y),u.initialVarsToRemove.push(b),u.initialVarsToRemove.push(`${b}.${D}`),l()}}if(d.message.includes("variable for increment could not be found")){let f=d.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(f?.[1]){let g=f[1],b=`VAR ${g} = 0
101
101
 
102
- `;return o.textSource=m.concat(o.textSource),o.initialVarsToRemove.push(f),s()}}return a.forEach(d=>{let f=d.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);f?.[1]&&(d.message=`The function '${f[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:a}}return {issues:a}}i.getErrors=e;function t(a,s){return $C(a).filter(({tokens:o})=>!s.some(({validation:u})=>GC(o,u)))}i.getUnknownHashtagCommands=t;function n(a,s){let o=new Set;for(let d of a.matchAll(jC))d[1]&&o.add(d[1]);let u=new Set(s),l=new Set,h=a.split(/\r?\n/),c=[];for(let d=0;d<h.length;d++){let f=(h[d]??"").replace(/\/\/.*$/,"");for(let m of f.matchAll(/->[ \t]+(\w[\w.]*)/g)){let g=m[1];if(!g)continue;let b=g.split(".")[0]??g;qC.has(b)||o.has(b)||u.has(g)||u.has(g.replaceAll(".",MC))||u.has(b)||l.has(g)||(l.add(g),c.push({line:d+1,target:g}));}}return c}i.getUnknownDivertTargets=n;})(Vl||={});var kl=zs(Ut());function JC(r){if(!r||r.length===0)return;let e=new Set;for(let t of r){let n=typeof t=="string"?t:t?.id;typeof n=="string"&&n.length>0&&e.add(n);}return e.size>0?e:void 0}function Hs(r,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:r},{json:n,issues:i}=Vl.compile(r,t);if(i.forEach(({message:s,type:o})=>{o===kl.ErrorType.Error?W.error(`Ink compilation error: ${s}`):o===kl.ErrorType.Warning?W.warn(`Ink compilation warning: ${s}`):W.info(`Ink compilation info: ${s}`);}),!n){W.error("No JSON generated from ink file");return}let a;try{a=An.parse(n);}catch{W.error("Error parsing ink file");return}return t.enums=a.listDefs||{},da.inkToJson(a,{...t,characterIds:JC(e.characters)})}async function HC(r,e={}){Array.isArray(r)||(r=[r]),Xs();let t={functions:[],enums:{},characters:e.characters},n=r.map(async i=>{let a=Hs(i,t);return a&&await Ks(a,{operationStringConvert:exports.HashtagCommands.run,skipEmptyDialogs:true}),i});return await Promise.all(n)}async function zC(r){return Xs(),await Ks(r,{operationStringConvert:exports.HashtagCommands.run,skipEmptyDialogs:true})}exports.addBaseHashtagCommands=Md;exports.convertInkText=Hs;exports.convertInkToJson=Hs;exports.generateJsonInkTranslation=$d;exports.importInkText=HC;exports.importJson=zC;exports.onInkHashtagScript=qd;exports.onInkTranslate=Gd;exports.onReplaceTextAfterTranslation=wd;exports.onReplaceTextBeforeTranslation=_d;
102
+ `;return u.textSource=b.concat(u.textSource),u.initialVarsToRemove.push(g),l()}}return o.forEach(f=>{let g=f.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);g?.[1]&&(f.message=`The function '${g[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:o}}return {issues:o}}s.getErrors=e;function t(o,l){return zC(o).filter(({tokens:u})=>!l.some(({validation:h})=>HC(u,h)))}s.getUnknownHashtagCommands=t;function n(o,l){let u=new Set;for(let f of o.matchAll(GC))f[1]&&u.add(f[1]);let h=new Set(l),c=new Set,p=o.split(/\r?\n/),d=[];for(let f=0;f<p.length;f++){let g=(p[f]??"").replace(/\/\/.*$/,"");for(let b of g.matchAll(/->[ \t]+(\w[\w.]*)/g)){let D=b[1];if(!D)continue;let y=D.split(".")[0]??D;$C.has(y)||u.has(y)||h.has(D)||h.has(D.replaceAll(".",JC))||h.has(y)||c.has(D)||(c.add(D),d.push({line:f+1,target:D}));}}return d}s.getUnknownDivertTargets=n;function i(o){return new qC__default.default({strict:false,allErrors:true}).compile(o)}s.getSchemaValidator=i;function a(o,l){let u=typeof l=="function"?l:i(l);return u(o)?[]:KC(u.errors??[]).map(c=>({instancePath:c.instancePath||"(root)",element:Oc(c),message:c.message??"invalid value",origin:UC(o,c.instancePath)}))}s.validateAgainstJsonSchema=a;})(Il||={});var Vl=Hs(Ut());function XC(r){if(!r||r.length===0)return;let e=new Set;for(let t of r){let n=typeof t=="string"?t:t?.id;typeof n=="string"&&n.length>0&&e.add(n);}return e.size>0?e:void 0}function Js(r,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:r},{json:n,issues:i}=Il.compile(r,t);if(i.forEach(({message:s,type:o})=>{o===Vl.ErrorType.Error?j.error(`Ink compilation error: ${s}`):o===Vl.ErrorType.Warning?j.warn(`Ink compilation warning: ${s}`):j.info(`Ink compilation info: ${s}`);}),!n){j.error("No JSON generated from ink file");return}let a;try{a=An.parse(n);}catch{j.error("Error parsing ink file");return}return t.enums=a.listDefs||{},ca.inkToJson(a,{...t,characterIds:XC(e.characters)})}async function YC(r,e={}){Array.isArray(r)||(r=[r]),Ks();let t={functions:[],enums:{},characters:e.characters},n=r.map(async i=>{let a=Js(i,t);return a&&await Us(a,{operationStringConvert:exports.HashtagCommands.run,skipEmptyDialogs:true}),i});return await Promise.all(n)}async function QC(r){return Ks(),await Us(r,{operationStringConvert:exports.HashtagCommands.run,skipEmptyDialogs:true})}exports.addBaseHashtagCommands=$p;exports.convertInkText=Js;exports.convertInkToJson=Js;exports.generateJsonInkTranslation=Hp;exports.importInkText=YC;exports.importJson=QC;exports.onInkHashtagScript=Gp;exports.onInkTranslate=Jp;exports.onReplaceTextAfterTranslation=Op;exports.onReplaceTextBeforeTranslation=Pp;