@drincs/pixi-vn-ink 0.8.0 → 0.8.2

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.
Files changed (147) hide show
  1. package/dist/functions/index.cjs +36 -36
  2. package/dist/functions/index.d.cts +168 -7
  3. package/dist/functions/index.d.ts +168 -7
  4. package/dist/functions/{index.js → index.mjs} +36 -36
  5. package/dist/index.cjs +36 -36
  6. package/dist/index.d.cts +2 -6
  7. package/dist/index.d.ts +2 -6
  8. package/dist/{functions/importer.js → index.mjs} +36 -36
  9. package/package.json +13 -3
  10. package/dist/RootParserItemType-BeypaLqW.d.ts +0 -41
  11. package/dist/RootParserItemType-DV41SbdA.d.cts +0 -41
  12. package/dist/constant.cjs +0 -1
  13. package/dist/constant.d.cts +0 -5
  14. package/dist/constant.d.ts +0 -5
  15. package/dist/constant.js +0 -1
  16. package/dist/functions/choice-info-converter.cjs +0 -3
  17. package/dist/functions/choice-info-converter.d.cts +0 -19
  18. package/dist/functions/choice-info-converter.d.ts +0 -19
  19. package/dist/functions/choice-info-converter.js +0 -3
  20. package/dist/functions/hashtag-script.cjs +0 -1
  21. package/dist/functions/hashtag-script.d.cts +0 -45
  22. package/dist/functions/hashtag-script.d.ts +0 -45
  23. package/dist/functions/hashtag-script.js +0 -1
  24. package/dist/functions/importer.cjs +0 -48
  25. package/dist/functions/importer.d.cts +0 -18
  26. package/dist/functions/importer.d.ts +0 -18
  27. package/dist/functions/ink-to-pixivn.cjs +0 -46
  28. package/dist/functions/ink-to-pixivn.d.cts +0 -10
  29. package/dist/functions/ink-to-pixivn.d.ts +0 -10
  30. package/dist/functions/ink-to-pixivn.js +0 -46
  31. package/dist/functions/labels-converter.cjs +0 -3
  32. package/dist/functions/labels-converter.d.cts +0 -17
  33. package/dist/functions/labels-converter.d.ts +0 -17
  34. package/dist/functions/labels-converter.js +0 -3
  35. package/dist/functions/log-utility.cjs +0 -1
  36. package/dist/functions/log-utility.d.cts +0 -8
  37. package/dist/functions/log-utility.d.ts +0 -8
  38. package/dist/functions/log-utility.js +0 -1
  39. package/dist/functions/replace.cjs +0 -1
  40. package/dist/functions/replace.d.cts +0 -61
  41. package/dist/functions/replace.d.ts +0 -61
  42. package/dist/functions/replace.js +0 -1
  43. package/dist/functions/translate.cjs +0 -1
  44. package/dist/functions/translate.d.cts +0 -41
  45. package/dist/functions/translate.d.ts +0 -41
  46. package/dist/functions/translate.js +0 -1
  47. package/dist/index.js +0 -48
  48. package/dist/managers/HashtagScriptManager.cjs +0 -1
  49. package/dist/managers/HashtagScriptManager.d.cts +0 -33
  50. package/dist/managers/HashtagScriptManager.d.ts +0 -33
  51. package/dist/managers/HashtagScriptManager.js +0 -1
  52. package/dist/parser/adding-elements.cjs +0 -2
  53. package/dist/parser/adding-elements.d.cts +0 -10
  54. package/dist/parser/adding-elements.d.ts +0 -10
  55. package/dist/parser/adding-elements.js +0 -2
  56. package/dist/parser/arithmetic-parser.cjs +0 -2
  57. package/dist/parser/arithmetic-parser.d.cts +0 -8
  58. package/dist/parser/arithmetic-parser.d.ts +0 -8
  59. package/dist/parser/arithmetic-parser.js +0 -2
  60. package/dist/parser/conditiona-aritmetic-parser.cjs +0 -2
  61. package/dist/parser/conditiona-aritmetic-parser.d.cts +0 -64
  62. package/dist/parser/conditiona-aritmetic-parser.d.ts +0 -64
  63. package/dist/parser/conditiona-aritmetic-parser.js +0 -2
  64. package/dist/parser/conditional-statements-parser.cjs +0 -3
  65. package/dist/parser/conditional-statements-parser.d.cts +0 -18
  66. package/dist/parser/conditional-statements-parser.d.ts +0 -18
  67. package/dist/parser/conditional-statements-parser.js +0 -3
  68. package/dist/parser/label-parser.cjs +0 -3
  69. package/dist/parser/label-parser.d.cts +0 -25
  70. package/dist/parser/label-parser.d.ts +0 -25
  71. package/dist/parser/label-parser.js +0 -3
  72. package/dist/parser/switch-parser.cjs +0 -3
  73. package/dist/parser/switch-parser.d.cts +0 -17
  74. package/dist/parser/switch-parser.d.ts +0 -17
  75. package/dist/parser/switch-parser.js +0 -3
  76. package/dist/types/InkRootType.cjs +0 -1
  77. package/dist/types/InkRootType.d.cts +0 -16
  78. package/dist/types/InkRootType.d.ts +0 -16
  79. package/dist/types/InkRootType.js +0 -0
  80. package/dist/types/InkStoryType.cjs +0 -1
  81. package/dist/types/InkStoryType.d.cts +0 -19
  82. package/dist/types/InkStoryType.d.ts +0 -19
  83. package/dist/types/InkStoryType.js +0 -0
  84. package/dist/types/LabelChoiceRes.cjs +0 -1
  85. package/dist/types/LabelChoiceRes.d.cts +0 -17
  86. package/dist/types/LabelChoiceRes.d.ts +0 -17
  87. package/dist/types/LabelChoiceRes.js +0 -0
  88. package/dist/types/parserItems/ChoicePoint.cjs +0 -1
  89. package/dist/types/parserItems/ChoicePoint.d.cts +0 -10
  90. package/dist/types/parserItems/ChoicePoint.d.ts +0 -10
  91. package/dist/types/parserItems/ChoicePoint.js +0 -0
  92. package/dist/types/parserItems/Cond.cjs +0 -1
  93. package/dist/types/parserItems/Cond.d.cts +0 -16
  94. package/dist/types/parserItems/Cond.d.ts +0 -16
  95. package/dist/types/parserItems/Cond.js +0 -0
  96. package/dist/types/parserItems/ContainerType.cjs +0 -1
  97. package/dist/types/parserItems/ContainerType.d.cts +0 -13
  98. package/dist/types/parserItems/ContainerType.d.ts +0 -13
  99. package/dist/types/parserItems/ContainerType.js +0 -0
  100. package/dist/types/parserItems/ControlCommands.cjs +0 -1
  101. package/dist/types/parserItems/ControlCommands.d.cts +0 -26
  102. package/dist/types/parserItems/ControlCommands.d.ts +0 -26
  103. package/dist/types/parserItems/ControlCommands.js +0 -0
  104. package/dist/types/parserItems/Divert.cjs +0 -1
  105. package/dist/types/parserItems/Divert.d.cts +0 -38
  106. package/dist/types/parserItems/Divert.d.ts +0 -38
  107. package/dist/types/parserItems/Divert.js +0 -0
  108. package/dist/types/parserItems/NativeFunctions.cjs +0 -1
  109. package/dist/types/parserItems/NativeFunctions.d.cts +0 -20
  110. package/dist/types/parserItems/NativeFunctions.d.ts +0 -20
  111. package/dist/types/parserItems/NativeFunctions.js +0 -1
  112. package/dist/types/parserItems/ReadCount.cjs +0 -1
  113. package/dist/types/parserItems/ReadCount.d.cts +0 -14
  114. package/dist/types/parserItems/ReadCount.d.ts +0 -14
  115. package/dist/types/parserItems/ReadCount.js +0 -0
  116. package/dist/types/parserItems/RootParserItemType.cjs +0 -1
  117. package/dist/types/parserItems/RootParserItemType.d.cts +0 -10
  118. package/dist/types/parserItems/RootParserItemType.d.ts +0 -10
  119. package/dist/types/parserItems/RootParserItemType.js +0 -0
  120. package/dist/types/parserItems/TextType.cjs +0 -1
  121. package/dist/types/parserItems/TextType.d.cts +0 -6
  122. package/dist/types/parserItems/TextType.d.ts +0 -6
  123. package/dist/types/parserItems/TextType.js +0 -0
  124. package/dist/types/parserItems/VariableAssignment.cjs +0 -1
  125. package/dist/types/parserItems/VariableAssignment.d.cts +0 -23
  126. package/dist/types/parserItems/VariableAssignment.d.ts +0 -23
  127. package/dist/types/parserItems/VariableAssignment.js +0 -0
  128. package/dist/types/parserItems/VariableReference.cjs +0 -1
  129. package/dist/types/parserItems/VariableReference.d.cts +0 -14
  130. package/dist/types/parserItems/VariableReference.d.ts +0 -14
  131. package/dist/types/parserItems/VariableReference.js +0 -0
  132. package/dist/utility/array-utility.cjs +0 -1
  133. package/dist/utility/array-utility.d.cts +0 -3
  134. package/dist/utility/array-utility.d.ts +0 -3
  135. package/dist/utility/array-utility.js +0 -1
  136. package/dist/utility/divert-utility.cjs +0 -1
  137. package/dist/utility/divert-utility.d.cts +0 -3
  138. package/dist/utility/divert-utility.d.ts +0 -3
  139. package/dist/utility/divert-utility.js +0 -1
  140. package/dist/utility/text-utility.cjs +0 -2
  141. package/dist/utility/text-utility.d.cts +0 -3
  142. package/dist/utility/text-utility.d.ts +0 -3
  143. package/dist/utility/text-utility.js +0 -2
  144. package/dist/utility/value-utility.cjs +0 -2
  145. package/dist/utility/value-utility.d.cts +0 -7
  146. package/dist/utility/value-utility.d.ts +0 -7
  147. package/dist/utility/value-utility.js +0 -2
@@ -1,48 +1,48 @@
1
- 'use strict';var pixiVn=require('@drincs/pixi-vn');var ch=Object.create;var Jo=Object.defineProperty;var dh=Object.getOwnPropertyDescriptor;var fh=Object.getOwnPropertyNames;var ph=Object.getPrototypeOf,gh=Object.prototype.hasOwnProperty;var tt=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var C=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var mh=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fh(e))!gh.call(s,i)&&i!==t&&Jo(s,i,{get:()=>e[i],enumerable:!(n=dh(e,i))||n.enumerable});return s};var Ch=(s,e,t)=>(t=s!=null?ch(ph(s)):{},mh(Jo(t,"default",{value:s,enumerable:true}),s));var ps=C(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.CompilerOptions=void 0;var fs=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;}};qn.CompilerOptions=fs;});var rl=C(jn=>{Object.defineProperty(jn,"__esModule",{value:true});jn.DebugSourceRange=void 0;var gs=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};jn.DebugSourceRange=gs;});var Bn=C(Mn=>{Object.defineProperty(Mn,"__esModule",{value:true});Mn.ErrorType=void 0;var sl;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(sl||(Mn.ErrorType=sl={}));});var al=C(Gn=>{Object.defineProperty(Gn,"__esModule",{value:true});Gn.Argument=void 0;var ms=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};Gn.Argument=ms;});var R=C(z=>{Object.defineProperty(z,"__esModule",{value:true});z.filterUndef=z.isEquatable=z.nullIfUndefined=z.asINamedContentOrNull=z.asBooleanOrThrows=z.asNumberOrThrows=z.asOrThrows=z.asOrNull=void 0;function sc(s,e){return s instanceof e?ol(s):null}z.asOrNull=sc;function ac(s,e){if(s instanceof e)return ol(s);throw new Error(`${s} is not of type ${e}`)}z.asOrThrows=ac;function oc(s){if(typeof s=="number")return s;throw new Error(`${s} is not a number`)}z.asNumberOrThrows=oc;function lc(s){if(typeof s=="boolean")return s;throw new Error(`${s} is not a boolean`)}z.asBooleanOrThrows=lc;function uc(s){return s.hasValidName&&s.name?s:null}z.asINamedContentOrNull=uc;function hc(s){return typeof s>"u"?null:s}z.nullIfUndefined=hc;function cc(s){return typeof s=="object"&&typeof s.Equals=="function"}z.isEquatable=cc;function ol(s,e){return s}function dc(s){return s!=null}z.filterUndef=dc;});var j=C($n=>{Object.defineProperty($n,"__esModule",{value:true});$n.ParsedObject=void 0;var ll=R(),Cs=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=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, ll.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, ll.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&i.push(a),this.content===null)return [];for(let r of this.content)r.FindAll&&r.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,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;}}};$n.ParsedObject=Cs;});var Hn=C(Jn=>{Object.defineProperty(Jn,"__esModule",{value:true});Jn.AuthorWarning=void 0;var fc=j(),vs=class extends fc.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Jn.AuthorWarning=vs;});var le=C(Kt=>{Object.defineProperty(Kt,"__esModule",{value:true});Kt.Path=void 0;var Ct=class s{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 s.Component&&arguments[1]instanceof s){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new s(e)}else return s.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new s;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new s,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 s.Component(parseInt(n))):this._components.push(new s.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 s;return t._components.push(...this._components),t._components.push(e),t}};Kt.Path=Ct;Ct.parentId="^";(function(s){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==s.parentId}static ToParent(){return new e(s.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}s.Component=e;})(Ct||(Kt.Path=Ct={}));});var zt=C(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.Debug=void 0;var ul;(function(s){function e(n,i,a){t(n instanceof i,a);}s.AssertType=e;function t(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}s.Assert=t;})(ul||(Un.Debug=ul={}));});var te=C(vt=>{Object.defineProperty(vt,"__esModule",{value:true});vt.throwNullException=vt.NullException=void 0;var Kn=class extends Error{};vt.NullException=Kn;function pc(s){throw new Kn(`${s} is null or undefined`)}vt.throwNullException=pc;});var ue=C(Xn=>{Object.defineProperty(Xn,"__esModule",{value:true});Xn.InkObject=void 0;var yt=le(),Xt=J(),ys=zt(),St=R(),zn=te(),Ss=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, St.asOrNull)(t.parent,Xt.Container);for(;n!==null;){let i=(0, St.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, zn.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, St.asOrNull)(n.parent,Xt.Container);}this._path=new yt.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, zn.throwNullException)("path");if(e.isRelative){let t=(0, St.asOrNull)(this,Xt.Container);return t===null&&(ys.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, St.asOrNull)(this.parent,Xt.Container),ys.Debug.Assert(t!==null,"Expected parent to be a container"),ys.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, zn.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, zn.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,r=[];for(let l=0;l<a;++l)r.push(yt.Path.Component.ToParent());for(let l=i+1;l<e.componentCount;++l)r.push(e.GetComponent(l));return new yt.Path(r,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, St.asOrNull)(e,Xt.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}};Xn.InkObject=Ss;});var rt=C(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.StringBuilder=void 0;var bs=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="";}};Yn.StringBuilder=bs;});var ce=C(bt=>{Object.defineProperty(bt,"__esModule",{value:true});bt.InkList=bt.InkListItem=void 0;var Pe=te(),gc=rt(),he=class s{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new s(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(e){if(e instanceof s){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new s(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!s.isLikeInkListItem(t))return s.Null;let n=t;return new s(n.originName,n.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};bt.InkListItem=he;var _s=class s extends Map{constructor(){if(super(arguments[0]instanceof s?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof s){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, Pe.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, Pe.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var n;if(e==null||e=="")return new s;let i=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(i)return i.value===null?(0, Pe.throwNullException)("listValue.value"):new s(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof he){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, Pe.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, Pe.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, Pe.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=s.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new he(i.name,n),r=i.ValueForItem(a);this.Add(a,r);}}}ContainsItemNamed(e){for(let[t]of this)if(he.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=he.fromSerializedKey(e);if(t.originName===null)return (0, Pe.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:he.Null,Value:0};for(let[t,n]of this){let i=he.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:i,Value:n});}return e}get minItem(){let e={Key:he.Null,Value:0};for(let[t,n]of this){let i=he.fromSerializedKey(t);(e.Key.isNull||n<e.Value)&&(e={Key:i,Value:n});}return e}get inverse(){let e=new s;if(this.origins!=null)for(let t of this.origins)for(let[n,i]of t.items){let a=he.fromSerializedKey(n);this.ContainsKey(a)||e.Add(a,i);}return e}get all(){let e=new s;if(this.origins!=null)for(let t of this.origins)for(let[n,i]of t.items){let a=he.fromSerializedKey(n);e.set(a.serialized(),i);}return e}Union(e){let t=new s(this);for(let[n,i]of e)t.set(n,i);return t}Intersect(e){let t=new s;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 s(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 s(this.maxItem):new s}MinAsList(){return this.Count>0?new s(this.minItem):new s}ListWithSubRange(e,t){if(this.Count==0)return new s;let n=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof s&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof s&&t.Count>0&&(a=t.maxItem.Value);let r=new s;r.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=i&&o.Value<=a&&r.Add(o.Key,o.Value);return r}Equals(e){if(!(e instanceof s)||e.Count!=this.Count)return 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=he.fromSerializedKey(t);e.push({Key:i,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, Pe.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, Pe.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 gc.StringBuilder;for(let n=0;n<e.length;n++){n>0&&t.Append(", ");let i=e[n].Key;if(i.itemName===null)return (0, Pe.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};bt.InkList=_s;});var Yt=C(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.StoryException=void 0;var Es=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};Qn.StoryException=Es;});var _t=C(Ge=>{Object.defineProperty(Ge,"__esModule",{value:true});Ge.tryParseFloat=Ge.tryParseInt=Ge.tryGetValueFromMap=void 0;function mc(s,e,t){if(s===null)return {result:t,exists:false};let n=s.get(e);return typeof n>"u"?{result:t,exists:false}:{result:n,exists:true}}Ge.tryGetValueFromMap=mc;function Cc(s,e=0){let t=parseInt(s);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ge.tryParseInt=Cc;function vc(s,e=0){let t=parseFloat(s);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ge.tryParseFloat=vc;});var M=C(B=>{Object.defineProperty(B,"__esModule",{value:true});B.ValueType=B.ListValue=B.VariablePointerValue=B.DivertTargetValue=B.StringValue=B.FloatValue=B.IntValue=B.BoolValue=B.Value=B.AbstractValue=void 0;var hl=ue(),cl=le(),st=ce(),yc=Yt(),Qt=R(),dl=_t(),ve=te(),Zn=class s extends hl.InkObject{static Create(e,t){if(t){if(t===W.Int&&Number.isInteger(Number(e)))return new Ne(Number(e));if(t===W.Float&&!isNaN(e))return new Ae(Number(e))}if(typeof e=="boolean")return new Et(!!e);if(typeof e=="string")return new qe(String(e));if(Number.isInteger(Number(e)))return new Ne(Number(e));if(isNaN(e)){if(e instanceof cl.Path)return new ei((0, Qt.asOrThrows)(e,cl.Path));if(e instanceof st.InkList)return new ti((0, Qt.asOrThrows)(e,st.InkList))}else return new Ae(Number(e));return null}Copy(){return (0, Qt.asOrThrows)(s.Create(this.valueObject),hl.InkObject)}BadCastException(e){return new yc.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};B.AbstractValue=Zn;var Oe=class extends Zn{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, ve.throwNullException)("Value.value"):this.value.toString()}};B.Value=Oe;var Et=class extends Oe{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return W.Bool}Cast(e){if(this.value===null)return (0, ve.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==W.Int)return new Ne(this.value?1:0);if(e==W.Float)return new Ae(this.value?1:0);if(e==W.String)return new qe(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};B.BoolValue=Et;var Ne=class extends Oe{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return W.Int}Cast(e){if(this.value===null)return (0, ve.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==W.Bool)return new Et(this.value!==0);if(e==W.Float)return new Ae(this.value);if(e==W.String)return new qe(""+this.value);throw this.BadCastException(e)}};B.IntValue=Ne;var Ae=class extends Oe{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return W.Float}Cast(e){if(this.value===null)return (0, ve.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==W.Bool)return new Et(this.value!==0);if(e==W.Int)return new Ne(this.value);if(e==W.String)return new qe(""+this.value);throw this.BadCastException(e)}};B.FloatValue=Ae;var qe=class extends Oe{constructor(e){if(super(e||""),this._isNewline=this.value==`
3
- `,this._isInlineWhitespace=true,this.value===null)return (0, ve.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return W.String}get isTruthy(){return this.value===null?(0, ve.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==W.Int){let t=(0, dl.tryParseInt)(this.value);if(t.exists)return new Ne(t.result);throw this.BadCastException(e)}if(e==W.Float){let t=(0, dl.tryParseFloat)(this.value);if(t.exists)return new Ae(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};B.StringValue=qe;var ei=class extends Oe{constructor(e=null){super(e);}get valueType(){return W.DivertTarget}get targetPath(){return this.value===null?(0, ve.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+")"}};B.DivertTargetValue=ei;var Ts=class s extends Oe{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, ve.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return W.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new s(this.variableName,this.contextIndex)}};B.VariablePointerValue=Ts;var ti=class s extends Oe{get isTruthy(){return this.value===null?(0, ve.throwNullException)("this.value"):this.value.Count>0}get valueType(){return W.List}Cast(e){if(this.value===null)return (0, ve.throwNullException)("Value.value");if(e==W.Int){let t=this.value.maxItem;return t.Key.isNull?new Ne(0):new Ne(t.Value)}else if(e==W.Float){let t=this.value.maxItem;return t.Key.isNull?new Ae(0):new Ae(t.Value)}else if(e==W.String){let t=this.value.maxItem;return t.Key.isNull?new qe(""):new qe(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new st.InkList:e instanceof st.InkList?this.value=new st.InkList(e):e instanceof st.InkListItem&&typeof t=="number"&&(this.value=new st.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, Qt.asOrNull)(e,s),i=(0, Qt.asOrNull)(t,s);if(i&&i.value===null)return (0, ve.throwNullException)("newList.value");if(n&&n.value===null)return (0, ve.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};B.ListValue=ti;var W;(function(s){s[s.Bool=-1]="Bool",s[s.Int=0]="Int",s[s.Float=1]="Float",s[s.List=2]="List",s[s.String=3]="String",s[s.DivertTarget=4]="DivertTarget",s[s.VariablePointer=5]="VariablePointer";})(W||(B.ValueType=W={}));});var fl=C(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.SearchResult=void 0;var Sc=J(),ws=class s{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof Sc.Container?this.obj:null}copy(){let e=new s;return e.obj=this.obj,e.approximate=this.approximate,e}};ni.SearchResult=ws;});var J=C(en=>{Object.defineProperty(en,"__esModule",{value:true});en.Container=void 0;var bc=M(),pl=te(),_c=rt(),Tt=ue(),Ec=fl(),gl=le(),ml=zt(),Tc=_t(),$e=R(),Zt=class s extends Tt.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, $e.asOrThrows)(n,Tt.InkObject);e.set(t,i);}for(let t of this.content){let n=(0, $e.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, $e.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=s.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=s.CountFlags.Turns),this.countingAtStartOnly&&(e|=s.CountFlags.CountStartOnly),e==s.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&s.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&s.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&s.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof s;)t.content.length>0&&(e.push(new gl.Path.Component(0)),t=t.content[0]);return new gl.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, $e.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){ml.Debug.AssertType(e,Tt.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, $e.asOrThrows)(e,Tt.InkObject);if(t.parent=this,e.name===null)return (0, pl.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let i=new Ec.SearchResult;i.approximate=false;let a=this,r=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, $e.asOrNull)(u,s);if(o<n-1&&h==null){i.approximate=true;break}r=u,a=h;}return i.obj=r,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, pl.throwNullException)("component.name");let t=(0, Tc.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, $e.asOrThrows)(t.result,Tt.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new _c.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 r=0;r<this.content.length;++r){let o=this.content[r];o instanceof s?o.BuildStringOfHierarchy(e,t,n):(i(),o instanceof bc.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
4
- `,"\\n")),e.Append('"')):e.Append(o.toString())),r!=this.content.length-1&&e.Append(","),!(o instanceof s)&&o==n&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[r,o]of this.namedContent)this.content.indexOf((0, $e.asOrThrows)(o,Tt.InkObject))>=0||a.set(r,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,r]of a)ml.Debug.AssertType(r,s,"Can only print out named Containers"),r.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,i(),e.Append("]");}};en.Container=Zt;(function(s){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(s.CountFlags||(s.CountFlags={}));})(Zt||(en.Container=Zt={}));});var ne=C(nn=>{Object.defineProperty(nn,"__esModule",{value:true});nn.ControlCommand=void 0;var wc=ue(),tn=class s extends wc.InkObject{get commandType(){return this._commandType}constructor(e=s.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new s(this.commandType)}static EvalStart(){return new s(s.CommandType.EvalStart)}static EvalOutput(){return new s(s.CommandType.EvalOutput)}static EvalEnd(){return new s(s.CommandType.EvalEnd)}static Duplicate(){return new s(s.CommandType.Duplicate)}static PopEvaluatedValue(){return new s(s.CommandType.PopEvaluatedValue)}static PopFunction(){return new s(s.CommandType.PopFunction)}static PopTunnel(){return new s(s.CommandType.PopTunnel)}static BeginString(){return new s(s.CommandType.BeginString)}static EndString(){return new s(s.CommandType.EndString)}static NoOp(){return new s(s.CommandType.NoOp)}static ChoiceCount(){return new s(s.CommandType.ChoiceCount)}static Turns(){return new s(s.CommandType.Turns)}static TurnsSince(){return new s(s.CommandType.TurnsSince)}static ReadCount(){return new s(s.CommandType.ReadCount)}static Random(){return new s(s.CommandType.Random)}static SeedRandom(){return new s(s.CommandType.SeedRandom)}static VisitIndex(){return new s(s.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new s(s.CommandType.SequenceShuffleIndex)}static StartThread(){return new s(s.CommandType.StartThread)}static Done(){return new s(s.CommandType.Done)}static End(){return new s(s.CommandType.End)}static ListFromInt(){return new s(s.CommandType.ListFromInt)}static ListRange(){return new s(s.CommandType.ListRange)}static ListRandom(){return new s(s.CommandType.ListRandom)}static BeginTag(){return new s(s.CommandType.BeginTag)}static EndTag(){return new s(s.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};nn.ControlCommand=tn;(function(s){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(s.CommandType||(s.CommandType={}));})(tn||(nn.ControlCommand=tn={}));});var ye=C(ii=>{Object.defineProperty(ii,"__esModule",{value:true});ii.Expression=void 0;var Cl=J(),xs=ne(),xc=j(),Ps=class extends xc.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new Cl.Container;return e.AddContent(xs.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(xs.ControlCommand.EvalOutput()),e.AddContent(xs.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new Cl.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}};ii.Expression=Ps;});var at=C(ri=>{Object.defineProperty(ri,"__esModule",{value:true});ri.Void=void 0;var Pc=ue(),Os=class extends Pc.InkObject{toString(){return "Void"}};ri.Void=Os;});var Ie=C(ai=>{Object.defineProperty(ai,"__esModule",{value:true});ai.NativeFunctionCall=void 0;var T=M(),rn=Yt(),Oc=at(),si=ce(),Nc=ue(),Se=R(),de=te(),A=class s extends Nc.InkObject{static CallWithName(e){return new s(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, de.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(s._nativeFunctions===null?(0, de.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=s._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof Oc.Void)throw new rn.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 T.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),i=n[0].valueType;return i==T.ValueType.Int?this.CallType(n):i==T.ValueType.Float?this.CallType(n):i==T.ValueType.String?this.CallType(n):i==T.ValueType.DivertTarget?this.CallType(n):i==T.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, Se.asOrThrows)(e[0],T.Value),n=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, de.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(n);if(!r){let o=T.ValueType[n];throw new rn.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, Se.asOrThrows)(e[1],T.Value),u=r;if(i.value===null||l.value===null)return (0, de.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(i.value,l.value);return T.Value.Create(h)}else {let o=r;if(i.value===null)return (0, de.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(i.value);return this.name===s.Int?T.Value.Create(l,T.ValueType.Int):this.name===s.Float?T.Value.Create(l,T.ValueType.Float):T.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 T.ListValue&&e[1]instanceof T.IntValue)return this.CallListIncrementOperation(e);let t=(0, Se.asOrThrows)(e[0],T.Value),n=(0, Se.asOrThrows)(e[1],T.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=T.ValueType.List||n.valueType!=T.ValueType.List)){if(this._operationFuncs===null)return (0, de.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(T.ValueType.Int);if(i===null)return (0, de.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, Se.asBooleanOrThrows)(i(t.isTruthy?1:0,n.isTruthy?1:0));return new T.BoolValue(a)}if(t.valueType==T.ValueType.List&&n.valueType==T.ValueType.List)return this.CallType([t,n]);throw new rn.StoryException("Can not call use "+this.name+" operation on "+T.ValueType[t.valueType]+" and "+T.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, Se.asOrThrows)(e[0],T.ListValue),n=(0, Se.asOrThrows)(e[1],T.IntValue),i=new si.InkList;if(t.value===null)return (0, de.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,r]of t.value){let o=si.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, de.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(T.ValueType.Int);if(n.value===null)return (0, de.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(r,n.value),h=null;if(t.value.origins===null)return (0, de.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,si.InkListItem.Null);c.exists&&i.Add(c.result,u);}}return new T.ListValue(i)}CoerceValuesToSingleType(e){let t=T.ValueType.Int,n=null;for(let a of e){let r=(0, Se.asOrThrows)(a,T.Value);r.valueType>t&&(t=r.valueType),r.valueType==T.ValueType.List&&(n=(0, Se.asOrNull)(r,T.ListValue));}let i=[];if(T.ValueType[t]==T.ValueType[T.ValueType.List])for(let a of e){let r=(0, Se.asOrThrows)(a,T.Value);if(r.valueType==T.ValueType.List)i.push(r);else if(r.valueType==T.ValueType.Int){let o=parseInt(r.valueObject);if(n=(0, Se.asOrThrows)(n,T.ListValue),n.value===null)return (0, de.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, de.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,si.InkListItem.Null);if(u.exists){let h=new T.ListValue(u.result,o);i.push(h);}else throw new rn.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=T.ValueType[r.valueType];throw new rn.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, Se.asOrThrows)(a,T.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)s.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];s.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=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,s.Identity),this.AddIntUnaryOp(this.Ceiling,s.Identity),this.AddIntUnaryOp(this.Int,s.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,i)=>n+i),this.AddFloatBinaryOp(this.Subtract,(n,i)=>n-i),this.AddFloatBinaryOp(this.Multiply,(n,i)=>n*i),this.AddFloatBinaryOp(this.Divide,(n,i)=>n/i),this.AddFloatBinaryOp(this.Mod,(n,i)=>n%i),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,i)=>n==i),this.AddFloatBinaryOp(this.Greater,(n,i)=>n>i),this.AddFloatBinaryOp(this.Less,(n,i)=>n<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddFloatBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddFloatBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddFloatBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddFloatBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,s.Identity),this.AddStringBinaryOp(this.Add,(n,i)=>n+i),this.AddStringBinaryOp(this.Equal,(n,i)=>n===i),this.AddStringBinaryOp(this.NotEquals,(n,i)=>n!==i),this.AddStringBinaryOp(this.Has,(n,i)=>n.includes(i)),this.AddStringBinaryOp(this.Hasnt,(n,i)=>!n.includes(i)),this.AddListBinaryOp(this.Add,(n,i)=>n.Union(i)),this.AddListBinaryOp(this.Subtract,(n,i)=>n.Without(i)),this.AddListBinaryOp(this.Has,(n,i)=>n.Contains(i)),this.AddListBinaryOp(this.Hasnt,(n,i)=>!n.Contains(i)),this.AddListBinaryOp(this.Intersect,(n,i)=>n.Intersect(i)),this.AddListBinaryOp(this.Equal,(n,i)=>n.Equals(i)),this.AddListBinaryOp(this.Greater,(n,i)=>n.GreaterThan(i)),this.AddListBinaryOp(this.Less,(n,i)=>n.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,i)=>n.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(n,i)=>n.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(n,i)=>!n.Equals(i)),this.AddListBinaryOp(this.And,(n,i)=>n.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(n,i)=>n.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let e=(n,i)=>n.Equals(i),t=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,T.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,T.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, de.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new s(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};ai.NativeFunctionCall=A;A.Add="+";A.Subtract="-";A.Divide="/";A.Multiply="*";A.Mod="%";A.Negate="_";A.Equal="==";A.Greater=">";A.Less="<";A.GreaterThanOrEquals=">=";A.LessThanOrEquals="<=";A.NotEquals="!=";A.Not="!";A.And="&&";A.Or="||";A.Min="MIN";A.Max="MAX";A.Pow="POW";A.Floor="FLOOR";A.Ceiling="CEILING";A.Int="INT";A.Float="FLOAT";A.Has="?";A.Hasnt="!?";A.Intersect="^";A.ListMin="LIST_MIN";A.ListMax="LIST_MAX";A.All="LIST_ALL";A.Count="LIST_COUNT";A.ValueOfList="LIST_VALUE";A.Invert="LIST_INVERT";A._nativeFunctions=null;});var li=C(oi=>{Object.defineProperty(oi,"__esModule",{value:true});oi.NumberExpression=void 0;var Ac=ye(),Ns=M(),Ic=R(),As=class s extends Ac.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 Ns.IntValue(this.value)):this.isFloat()?n.AddContent(new Ns.FloatValue(this.value)):this.isBool()&&n.AddContent(new Ns.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, Ic.asOrNull)(e,s);return t?t.subtype==this.subtype&&t.value==this.value:false}};oi.NumberExpression=As;});var Is=C(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.UnaryExpression=void 0;var Fc=ye(),Vc=Ie(),wt=li(),kc=R(),sn=class extends Fc.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(Vc.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};ui.UnaryExpression=sn;sn.WithInner=(s,e)=>{let t=(0, kc.asOrNull)(s,wt.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new wt.NumberExpression(-t.value,"int");if(t.isFloat())return new wt.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new wt.NumberExpression(t.value==0,"bool");if(t.isFloat())return new wt.NumberExpression(t.value==0,"bool");if(t.isBool())return new wt.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new sn(s,e)};});var Vs=C(hi=>{Object.defineProperty(hi,"__esModule",{value:true});hi.BinaryExpression=void 0;var Rc=ye(),Dc=Ie(),Lc=Is(),Wc=R(),Fs=class extends Rc.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(Dc.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, Wc.asOrNull)(this.leftExpression,Lc.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=Fs;});var on=C(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.CharacterSet=void 0;var an=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);}};ci.CharacterSet=an;an.FromRange=(s,e)=>new an().AddRange(s,e);});var yl=C(di=>{Object.defineProperty(di,"__esModule",{value:true});di.CharacterRange=void 0;var vl=on(),ln=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new vl.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 vl.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}};di.CharacterRange=ln;ln.Define=(s,e,t=[])=>new ln(s,e,t);});var pi=C(fi=>{Object.defineProperty(fi,"__esModule",{value:true});fi.ChoicePoint=void 0;var qc=ue(),jc=le(),ks=te(),Rs=class extends qc.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, ks.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, ks.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new jc.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, ks.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};fi.ChoicePoint=Rs;});var ot=C(gi=>{Object.defineProperty(gi,"__esModule",{value:true});gi.PushPopType=void 0;var Sl;(function(s){s[s.Tunnel=0]="Tunnel",s[s.Function=1]="Function",s[s.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Sl||(gi.PushPopType=Sl={}));});var un=C(mi=>{Object.defineProperty(mi,"__esModule",{value:true});mi.Pointer=void 0;var Mc=le(),Ds=class s{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new Mc.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new s(this.container,this.index)}static StartOf(e){return new s(e,0)}static get Null(){return new s(null,-1)}};mi.Pointer=Ds;});var Fe=C(vi=>{Object.defineProperty(vi,"__esModule",{value:true});vi.Divert=void 0;var Bc=le(),Gc=ot(),$c=rt(),Jc=ue(),Ls=un(),bl=J(),Ci=te(),Ws=class s extends Jc.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=Ls.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, Ci.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, Ci.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, Ci.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof bl.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Ls.Pointer.StartOf(e instanceof bl.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 Bc.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=Ls.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 s&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, Ci.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 $c.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==Gc.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};vi.Divert=Ws;});var je=C(yi=>{Object.defineProperty(yi,"__esModule",{value:true});yi.SymbolType=void 0;var _l;(function(s){s[s.Knot=0]="Knot",s[s.List=1]="List",s[s.ListItem=2]="ListItem",s[s.Var=3]="Var",s[s.SubFlowAndWeave=4]="SubFlowAndWeave",s[s.Arg=5]="Arg",s[s.Temp=6]="Temp";})(_l||(yi.SymbolType=_l={}));});var Je=C(Si=>{Object.defineProperty(Si,"__esModule",{value:true});Si.VariableAssignment=void 0;var Hc=ue(),qs=class extends Hc.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};Si.VariableAssignment=qs;});var xt=C(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.Choice=void 0;var Uc=pi(),bi=J(),He=ne(),js=Fe(),El=M(),Kc=j(),zc=je(),Tl=Je(),Ms=class extends Kc.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 bi.Container,this._runtimeChoice=new Uc.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(He.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new El.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Tl.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(He.ControlCommand.BeginString()),this._divertToStartContentOuter=new js.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new js.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new bi.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(He.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(He.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(He.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(He.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new bi.Container,this.startContent){this._returnToR2=new El.DivertTargetValue,this._innerContentContainer.AddContent(He.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(He.ControlCommand.EvalEnd());let i=new Tl.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new js.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new bi.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,zc.SymbolType.SubFlowAndWeave);}};_i.Choice=Ms;});var wl=C(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.StringParserElement=void 0;var Ei=class s{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{s._uniqueIdCounter++,this.uniqueId=s._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};Ti.StringParserElement=Ei;Ei._uniqueIdCounter=1e3;});var Pl=C(wi=>{Object.defineProperty(wi,"__esModule",{value:true});wi.StringParserState=void 0;var xl=wl(),Bs=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 xl.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 xl.StringParserElement;this._numElements=1;}};wi.StringParserState=Bs;});var $s=C(lt=>{Object.defineProperty(lt,"__esModule",{value:true});lt.StringParser=lt.ParseSuccess=void 0;var Gs=on(),Xc=Pl();lt.ParseSuccess=Symbol("ParseSuccessStruct");var hn=class s{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),r=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,r,a),this.state.Squash();let o=i;return o===null&&(o=s.ParseSuccess),o},this.Expect=(n,i=null,a=null)=>{let r=this.ParseObject(n);if(r===null){i===null&&(i=n.name);let o,l=this.LineRemainder();l===null||l.length===0?o="end of line":o=`'${l}'`,this.Error(`Expected ${i} but saw ${o}`),a!==null&&(r=a());}return r},this.Error=(n,i=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 r=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,i-1,a);else throw new Error(`${r} on line ${i}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
1
+ 'use strict';var pixiVn=require('@drincs/pixi-vn');var fh=Object.create;var fs=Object.defineProperty;var ph=Object.getOwnPropertyDescriptor;var gh=Object.getOwnPropertyNames;var mh=Object.getPrototypeOf,Ch=Object.prototype.hasOwnProperty;var vh=(s,e,t)=>e in s?fs(s,e,{enumerable:true,configurable:true,writable:true,value:t}):s[e]=t;var it=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var C=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var yh=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of gh(e))!Ch.call(s,i)&&i!==t&&fs(s,i,{get:()=>e[i],enumerable:!(n=ph(e,i))||n.enumerable});return s};var Sh=(s,e,t)=>(t=s!=null?fh(mh(s)):{},yh(fs(t,"default",{value:s,enumerable:true}),s));var qe=(s,e,t)=>vh(s,typeof e!="symbol"?e+"":e,t);var Cs=C(Mn=>{Object.defineProperty(Mn,"__esModule",{value:true});Mn.CompilerOptions=void 0;var ms=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;}};Mn.CompilerOptions=ms;});var al=C(Bn=>{Object.defineProperty(Bn,"__esModule",{value:true});Bn.DebugSourceRange=void 0;var vs=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};Bn.DebugSourceRange=vs;});var $n=C(Gn=>{Object.defineProperty(Gn,"__esModule",{value:true});Gn.ErrorType=void 0;var ol;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(ol||(Gn.ErrorType=ol={}));});var ll=C(Jn=>{Object.defineProperty(Jn,"__esModule",{value:true});Jn.Argument=void 0;var ys=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};Jn.Argument=ys;});var D=C(X=>{Object.defineProperty(X,"__esModule",{value:true});X.filterUndef=X.isEquatable=X.nullIfUndefined=X.asINamedContentOrNull=X.asBooleanOrThrows=X.asNumberOrThrows=X.asOrThrows=X.asOrNull=void 0;function lc(s,e){return s instanceof e?ul(s):null}X.asOrNull=lc;function uc(s,e){if(s instanceof e)return ul(s);throw new Error(`${s} is not of type ${e}`)}X.asOrThrows=uc;function hc(s){if(typeof s=="number")return s;throw new Error(`${s} is not a number`)}X.asNumberOrThrows=hc;function cc(s){if(typeof s=="boolean")return s;throw new Error(`${s} is not a boolean`)}X.asBooleanOrThrows=cc;function dc(s){return s.hasValidName&&s.name?s:null}X.asINamedContentOrNull=dc;function fc(s){return typeof s>"u"?null:s}X.nullIfUndefined=fc;function pc(s){return typeof s=="object"&&typeof s.Equals=="function"}X.isEquatable=pc;function ul(s,e){return s}function gc(s){return s!=null}X.filterUndef=gc;});var M=C(Hn=>{Object.defineProperty(Hn,"__esModule",{value:true});Hn.ParsedObject=void 0;var hl=D(),Ss=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, hl.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, hl.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&i.push(a),this.content===null)return [];for(let r of this.content)r.FindAll&&r.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,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;}}};Hn.ParsedObject=Ss;});var Kn=C(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.AuthorWarning=void 0;var mc=M(),bs=class extends mc.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Un.AuthorWarning=bs;});var ue=C(Xt=>{Object.defineProperty(Xt,"__esModule",{value:true});Xt.Path=void 0;var yt=class s{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 s.Component&&arguments[1]instanceof s){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new s(e)}else return s.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new s;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new s,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 s.Component(parseInt(n))):this._components.push(new s.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 s;return t._components.push(...this._components),t._components.push(e),t}};Xt.Path=yt;yt.parentId="^";(function(s){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==s.parentId}static ToParent(){return new e(s.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}s.Component=e;})(yt||(Xt.Path=yt={}));});var Yt=C(zn=>{Object.defineProperty(zn,"__esModule",{value:true});zn.Debug=void 0;var cl;(function(s){function e(n,i,a){t(n instanceof i,a);}s.AssertType=e;function t(n,i){if(!n)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}s.Assert=t;})(cl||(zn.Debug=cl={}));});var ne=C(St=>{Object.defineProperty(St,"__esModule",{value:true});St.throwNullException=St.NullException=void 0;var Xn=class extends Error{};St.NullException=Xn;function Cc(s){throw new Xn(`${s} is null or undefined`)}St.throwNullException=Cc;});var he=C(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.InkObject=void 0;var bt=ue(),Qt=H(),_s=Yt(),_t=D(),Yn=ne(),Es=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(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 bt.Path;else {let e=[],t=this,n=(0, _t.asOrNull)(t.parent,Qt.Container);for(;n!==null;){let i=(0, _t.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Yn.throwNullException)("namedChild.name");e.unshift(new bt.Path.Component(i.name));}else e.unshift(new bt.Path.Component(n.content.indexOf(t)));t=n,n=(0, _t.asOrNull)(n.parent,Qt.Container);}this._path=new bt.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Yn.throwNullException)("path");if(e.isRelative){let t=(0, _t.asOrNull)(this,Qt.Container);return t===null&&(_s.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, _t.asOrNull)(this.parent,Qt.Container),_s.Debug.Assert(t!==null,"Expected parent to be a container"),_s.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Yn.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Yn.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,r=[];for(let l=0;l<a;++l)r.push(bt.Path.Component.ToParent());for(let l=i+1;l<e.componentCount;++l)r.push(e.GetComponent(l));return new bt.Path(r,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, _t.asOrNull)(e,Qt.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}};Qn.InkObject=Es;});var at=C(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.StringBuilder=void 0;var Ts=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="";}};Zn.StringBuilder=Ts;});var de=C(Et=>{Object.defineProperty(Et,"__esModule",{value:true});Et.InkList=Et.InkListItem=void 0;var Oe=ne(),vc=at(),ce=class s{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new s(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(e){if(e instanceof s){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new s(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!s.isLikeInkListItem(t))return s.Null;let n=t;return new s(n.originName,n.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};Et.InkListItem=ce;var ws=class s extends Map{constructor(){if(super(arguments[0]instanceof s?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof s){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, Oe.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, Oe.throwNullException)("def.result");this.origins=[n.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var n;if(e==null||e=="")return new s;let i=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(i)return i.value===null?(0, Oe.throwNullException)("listValue.value"):new s(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof ce){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, Oe.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, Oe.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, Oe.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(i!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=s.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new ce(i.name,n),r=i.ValueForItem(a);this.Add(a,r);}}}ContainsItemNamed(e){for(let[t]of this)if(ce.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=ce.fromSerializedKey(e);if(t.originName===null)return (0, Oe.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:ce.Null,Value:0};for(let[t,n]of this){let i=ce.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:i,Value:n});}return e}get minItem(){let e={Key:ce.Null,Value:0};for(let[t,n]of this){let i=ce.fromSerializedKey(t);(e.Key.isNull||n<e.Value)&&(e={Key:i,Value:n});}return e}get inverse(){let e=new s;if(this.origins!=null)for(let t of this.origins)for(let[n,i]of t.items){let a=ce.fromSerializedKey(n);this.ContainsKey(a)||e.Add(a,i);}return e}get all(){let e=new s;if(this.origins!=null)for(let t of this.origins)for(let[n,i]of t.items){let a=ce.fromSerializedKey(n);e.set(a.serialized(),i);}return e}Union(e){let t=new s(this);for(let[n,i]of e)t.set(n,i);return t}Intersect(e){let t=new s;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 s(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 s(this.maxItem):new s}MinAsList(){return this.Count>0?new s(this.minItem):new s}ListWithSubRange(e,t){if(this.Count==0)return new s;let n=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof s&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof s&&t.Count>0&&(a=t.maxItem.Value);let r=new s;r.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=i&&o.Value<=a&&r.Add(o.Key,o.Value);return r}Equals(e){if(!(e instanceof s)||e.Count!=this.Count)return 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=ce.fromSerializedKey(t);e.push({Key:i,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, Oe.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, Oe.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 vc.StringBuilder;for(let n=0;n<e.length;n++){n>0&&t.Append(", ");let i=e[n].Key;if(i.itemName===null)return (0, Oe.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};Et.InkList=ws;});var Zt=C(ei=>{Object.defineProperty(ei,"__esModule",{value:true});ei.StoryException=void 0;var xs=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};ei.StoryException=xs;});var Tt=C(Je=>{Object.defineProperty(Je,"__esModule",{value:true});Je.tryParseFloat=Je.tryParseInt=Je.tryGetValueFromMap=void 0;function yc(s,e,t){if(s===null)return {result:t,exists:false};let n=s.get(e);return typeof n>"u"?{result:t,exists:false}:{result:n,exists:true}}Je.tryGetValueFromMap=yc;function Sc(s,e=0){let t=parseInt(s);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Je.tryParseInt=Sc;function bc(s,e=0){let t=parseFloat(s);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Je.tryParseFloat=bc;});var B=C(G=>{Object.defineProperty(G,"__esModule",{value:true});G.ValueType=G.ListValue=G.VariablePointerValue=G.DivertTargetValue=G.StringValue=G.FloatValue=G.IntValue=G.BoolValue=G.Value=G.AbstractValue=void 0;var dl=he(),fl=ue(),ot=de(),_c=Zt(),en=D(),pl=Tt(),ye=ne(),ti=class s extends dl.InkObject{static Create(e,t){if(t){if(t===q.Int&&Number.isInteger(Number(e)))return new Ae(Number(e));if(t===q.Float&&!isNaN(e))return new Ie(Number(e))}if(typeof e=="boolean")return new wt(!!e);if(typeof e=="string")return new Me(String(e));if(Number.isInteger(Number(e)))return new Ae(Number(e));if(isNaN(e)){if(e instanceof fl.Path)return new ni((0, en.asOrThrows)(e,fl.Path));if(e instanceof ot.InkList)return new ii((0, en.asOrThrows)(e,ot.InkList))}else return new Ie(Number(e));return null}Copy(){return (0, en.asOrThrows)(s.Create(this.valueObject),dl.InkObject)}BadCastException(e){return new _c.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};G.AbstractValue=ti;var Ne=class extends ti{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, ye.throwNullException)("Value.value"):this.value.toString()}};G.Value=Ne;var wt=class extends Ne{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return q.Bool}Cast(e){if(this.value===null)return (0, ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==q.Int)return new Ae(this.value?1:0);if(e==q.Float)return new Ie(this.value?1:0);if(e==q.String)return new Me(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};G.BoolValue=wt;var Ae=class extends Ne{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return q.Int}Cast(e){if(this.value===null)return (0, ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==q.Bool)return new wt(this.value!==0);if(e==q.Float)return new Ie(this.value);if(e==q.String)return new Me(""+this.value);throw this.BadCastException(e)}};G.IntValue=Ae;var Ie=class extends Ne{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return q.Float}Cast(e){if(this.value===null)return (0, ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==q.Bool)return new wt(this.value!==0);if(e==q.Int)return new Ae(this.value);if(e==q.String)return new Me(""+this.value);throw this.BadCastException(e)}};G.FloatValue=Ie;var Me=class extends Ne{constructor(e){if(super(e||""),this._isNewline=this.value==`
3
+ `,this._isInlineWhitespace=true,this.value===null)return (0, ye.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, ye.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, pl.tryParseInt)(this.value);if(t.exists)return new Ae(t.result);throw this.BadCastException(e)}if(e==q.Float){let t=(0, pl.tryParseFloat)(this.value);if(t.exists)return new Ie(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};G.StringValue=Me;var ni=class extends Ne{constructor(e=null){super(e);}get valueType(){return q.DivertTarget}get targetPath(){return this.value===null?(0, ye.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+")"}};G.DivertTargetValue=ni;var Ps=class s extends Ne{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, ye.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 s(this.variableName,this.contextIndex)}};G.VariablePointerValue=Ps;var ii=class s extends Ne{get isTruthy(){return this.value===null?(0, ye.throwNullException)("this.value"):this.value.Count>0}get valueType(){return q.List}Cast(e){if(this.value===null)return (0, ye.throwNullException)("Value.value");if(e==q.Int){let t=this.value.maxItem;return t.Key.isNull?new Ae(0):new Ae(t.Value)}else if(e==q.Float){let t=this.value.maxItem;return t.Key.isNull?new Ie(0):new Ie(t.Value)}else if(e==q.String){let t=this.value.maxItem;return t.Key.isNull?new Me(""):new Me(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new ot.InkList:e instanceof ot.InkList?this.value=new ot.InkList(e):e instanceof ot.InkListItem&&typeof t=="number"&&(this.value=new ot.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, en.asOrNull)(e,s),i=(0, en.asOrNull)(t,s);if(i&&i.value===null)return (0, ye.throwNullException)("newList.value");if(n&&n.value===null)return (0, ye.throwNullException)("oldList.value");n&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(n.value.originNames);}};G.ListValue=ii;var q;(function(s){s[s.Bool=-1]="Bool",s[s.Int=0]="Int",s[s.Float=1]="Float",s[s.List=2]="List",s[s.String=3]="String",s[s.DivertTarget=4]="DivertTarget",s[s.VariablePointer=5]="VariablePointer";})(q||(G.ValueType=q={}));});var gl=C(ri=>{Object.defineProperty(ri,"__esModule",{value:true});ri.SearchResult=void 0;var Ec=H(),Os=class s{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof Ec.Container?this.obj:null}copy(){let e=new s;return e.obj=this.obj,e.approximate=this.approximate,e}};ri.SearchResult=Os;});var H=C(nn=>{Object.defineProperty(nn,"__esModule",{value:true});nn.Container=void 0;var Tc=B(),ml=ne(),wc=at(),xt=he(),xc=gl(),Cl=ue(),vl=Yt(),Pc=Tt(),He=D(),tn=class s extends xt.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, He.asOrThrows)(n,xt.InkObject);e.set(t,i);}for(let t of this.content){let n=(0, He.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, He.asINamedContentOrNull)(n);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=s.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=s.CountFlags.Turns),this.countingAtStartOnly&&(e|=s.CountFlags.CountStartOnly),e==s.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&s.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&s.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&s.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof s;)t.content.length>0&&(e.push(new Cl.Path.Component(0)),t=t.content[0]);return new Cl.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let n of t)this.AddContent(n);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, He.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){vl.Debug.AssertType(e,xt.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, He.asOrThrows)(e,xt.InkObject);if(t.parent=this,e.name===null)return (0, ml.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let i=new xc.SearchResult;i.approximate=false;let a=this,r=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, He.asOrNull)(u,s);if(o<n-1&&h==null){i.approximate=true;break}r=u,a=h;}return i.obj=r,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, ml.throwNullException)("component.name");let t=(0, Pc.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, He.asOrThrows)(t.result,xt.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new wc.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 r=0;r<this.content.length;++r){let o=this.content[r];o instanceof s?o.BuildStringOfHierarchy(e,t,n):(i(),o instanceof Tc.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
4
+ `,"\\n")),e.Append('"')):e.Append(o.toString())),r!=this.content.length-1&&e.Append(","),!(o instanceof s)&&o==n&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[r,o]of this.namedContent)this.content.indexOf((0, He.asOrThrows)(o,xt.InkObject))>=0||a.set(r,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,r]of a)vl.Debug.AssertType(r,s,"Can only print out named Containers"),r.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,i(),e.Append("]");}};nn.Container=tn;(function(s){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(s.CountFlags||(s.CountFlags={}));})(tn||(nn.Container=tn={}));});var ie=C(sn=>{Object.defineProperty(sn,"__esModule",{value:true});sn.ControlCommand=void 0;var Oc=he(),rn=class s extends Oc.InkObject{get commandType(){return this._commandType}constructor(e=s.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new s(this.commandType)}static EvalStart(){return new s(s.CommandType.EvalStart)}static EvalOutput(){return new s(s.CommandType.EvalOutput)}static EvalEnd(){return new s(s.CommandType.EvalEnd)}static Duplicate(){return new s(s.CommandType.Duplicate)}static PopEvaluatedValue(){return new s(s.CommandType.PopEvaluatedValue)}static PopFunction(){return new s(s.CommandType.PopFunction)}static PopTunnel(){return new s(s.CommandType.PopTunnel)}static BeginString(){return new s(s.CommandType.BeginString)}static EndString(){return new s(s.CommandType.EndString)}static NoOp(){return new s(s.CommandType.NoOp)}static ChoiceCount(){return new s(s.CommandType.ChoiceCount)}static Turns(){return new s(s.CommandType.Turns)}static TurnsSince(){return new s(s.CommandType.TurnsSince)}static ReadCount(){return new s(s.CommandType.ReadCount)}static Random(){return new s(s.CommandType.Random)}static SeedRandom(){return new s(s.CommandType.SeedRandom)}static VisitIndex(){return new s(s.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new s(s.CommandType.SequenceShuffleIndex)}static StartThread(){return new s(s.CommandType.StartThread)}static Done(){return new s(s.CommandType.Done)}static End(){return new s(s.CommandType.End)}static ListFromInt(){return new s(s.CommandType.ListFromInt)}static ListRange(){return new s(s.CommandType.ListRange)}static ListRandom(){return new s(s.CommandType.ListRandom)}static BeginTag(){return new s(s.CommandType.BeginTag)}static EndTag(){return new s(s.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};sn.ControlCommand=rn;(function(s){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(s.CommandType||(s.CommandType={}));})(rn||(sn.ControlCommand=rn={}));});var Se=C(si=>{Object.defineProperty(si,"__esModule",{value:true});si.Expression=void 0;var yl=H(),Ns=ie(),Nc=M(),As=class extends Nc.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new yl.Container;return e.AddContent(Ns.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(Ns.ControlCommand.EvalOutput()),e.AddContent(Ns.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new yl.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let n=t.Copy();n&&e.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};si.Expression=As;});var lt=C(ai=>{Object.defineProperty(ai,"__esModule",{value:true});ai.Void=void 0;var Ac=he(),Is=class extends Ac.InkObject{toString(){return "Void"}};ai.Void=Is;});var Fe=C(li=>{Object.defineProperty(li,"__esModule",{value:true});li.NativeFunctionCall=void 0;var E=B(),an=Zt(),Ic=lt(),oi=de(),Fc=he(),be=D(),fe=ne(),I=class s extends Fc.InkObject{static CallWithName(e){return new s(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, fe.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(s._nativeFunctions===null?(0, fe.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=s._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof Ic.Void)throw new an.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');a instanceof E.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),i=n[0].valueType;return i==E.ValueType.Int?this.CallType(n):i==E.ValueType.Float?this.CallType(n):i==E.ValueType.String?this.CallType(n):i==E.ValueType.DivertTarget?this.CallType(n):i==E.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, be.asOrThrows)(e[0],E.Value),n=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, fe.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(n);if(!r){let o=E.ValueType[n];throw new an.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, be.asOrThrows)(e[1],E.Value),u=r;if(i.value===null||l.value===null)return (0, fe.throwNullException)("NativeFunctionCall.Call BinaryOp values");let h=u(i.value,l.value);return E.Value.Create(h)}else {let o=r;if(i.value===null)return (0, fe.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(i.value);return this.name===s.Int?E.Value.Create(l,E.ValueType.Int):this.name===s.Float?E.Value.Create(l,E.ValueType.Float):E.Value.Create(l,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof E.ListValue&&e[1]instanceof E.IntValue)return this.CallListIncrementOperation(e);let t=(0, be.asOrThrows)(e[0],E.Value),n=(0, be.asOrThrows)(e[1],E.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=E.ValueType.List||n.valueType!=E.ValueType.List)){if(this._operationFuncs===null)return (0, fe.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(E.ValueType.Int);if(i===null)return (0, fe.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, be.asBooleanOrThrows)(i(t.isTruthy?1:0,n.isTruthy?1:0));return new E.BoolValue(a)}if(t.valueType==E.ValueType.List&&n.valueType==E.ValueType.List)return this.CallType([t,n]);throw new an.StoryException("Can not call use "+this.name+" operation on "+E.ValueType[t.valueType]+" and "+E.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, be.asOrThrows)(e[0],E.ListValue),n=(0, be.asOrThrows)(e[1],E.IntValue),i=new oi.InkList;if(t.value===null)return (0, fe.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,r]of t.value){let o=oi.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, fe.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(E.ValueType.Int);if(n.value===null)return (0, fe.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(r,n.value),h=null;if(t.value.origins===null)return (0, fe.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,oi.InkListItem.Null);c.exists&&i.Add(c.result,u);}}return new E.ListValue(i)}CoerceValuesToSingleType(e){let t=E.ValueType.Int,n=null;for(let a of e){let r=(0, be.asOrThrows)(a,E.Value);r.valueType>t&&(t=r.valueType),r.valueType==E.ValueType.List&&(n=(0, be.asOrNull)(r,E.ListValue));}let i=[];if(E.ValueType[t]==E.ValueType[E.ValueType.List])for(let a of e){let r=(0, be.asOrThrows)(a,E.Value);if(r.valueType==E.ValueType.List)i.push(r);else if(r.valueType==E.ValueType.Int){let o=parseInt(r.valueObject);if(n=(0, be.asOrThrows)(n,E.ListValue),n.value===null)return (0, fe.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, fe.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,oi.InkListItem.Null);if(u.exists){let h=new E.ListValue(u.result,o);i.push(h);}else throw new an.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=E.ValueType[r.valueType];throw new an.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, be.asOrThrows)(a,E.Value).Cast(t);i.push(o);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)s.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];s.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=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,s.Identity),this.AddIntUnaryOp(this.Ceiling,s.Identity),this.AddIntUnaryOp(this.Int,s.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,i)=>n+i),this.AddFloatBinaryOp(this.Subtract,(n,i)=>n-i),this.AddFloatBinaryOp(this.Multiply,(n,i)=>n*i),this.AddFloatBinaryOp(this.Divide,(n,i)=>n/i),this.AddFloatBinaryOp(this.Mod,(n,i)=>n%i),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,i)=>n==i),this.AddFloatBinaryOp(this.Greater,(n,i)=>n>i),this.AddFloatBinaryOp(this.Less,(n,i)=>n<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,i)=>n>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,i)=>n<=i),this.AddFloatBinaryOp(this.NotEquals,(n,i)=>n!=i),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,i)=>n!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(n,i)=>n!=0||i!=0),this.AddFloatBinaryOp(this.Max,(n,i)=>Math.max(n,i)),this.AddFloatBinaryOp(this.Min,(n,i)=>Math.min(n,i)),this.AddFloatBinaryOp(this.Pow,(n,i)=>Math.pow(n,i)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,s.Identity),this.AddStringBinaryOp(this.Add,(n,i)=>n+i),this.AddStringBinaryOp(this.Equal,(n,i)=>n===i),this.AddStringBinaryOp(this.NotEquals,(n,i)=>n!==i),this.AddStringBinaryOp(this.Has,(n,i)=>n.includes(i)),this.AddStringBinaryOp(this.Hasnt,(n,i)=>!n.includes(i)),this.AddListBinaryOp(this.Add,(n,i)=>n.Union(i)),this.AddListBinaryOp(this.Subtract,(n,i)=>n.Without(i)),this.AddListBinaryOp(this.Has,(n,i)=>n.Contains(i)),this.AddListBinaryOp(this.Hasnt,(n,i)=>!n.Contains(i)),this.AddListBinaryOp(this.Intersect,(n,i)=>n.Intersect(i)),this.AddListBinaryOp(this.Equal,(n,i)=>n.Equals(i)),this.AddListBinaryOp(this.Greater,(n,i)=>n.GreaterThan(i)),this.AddListBinaryOp(this.Less,(n,i)=>n.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,i)=>n.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(n,i)=>n.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(n,i)=>!n.Equals(i)),this.AddListBinaryOp(this.And,(n,i)=>n.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(n,i)=>n.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let e=(n,i)=>n.Equals(i),t=(n,i)=>!n.Equals(i);this.AddOpToNativeFunc(this.Equal,2,E.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,E.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,n,i){if(this._nativeFunctions===null)return (0, fe.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new s(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,E.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,E.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,E.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,E.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,E.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,E.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,E.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};li.NativeFunctionCall=I;I.Add="+";I.Subtract="-";I.Divide="/";I.Multiply="*";I.Mod="%";I.Negate="_";I.Equal="==";I.Greater=">";I.Less="<";I.GreaterThanOrEquals=">=";I.LessThanOrEquals="<=";I.NotEquals="!=";I.Not="!";I.And="&&";I.Or="||";I.Min="MIN";I.Max="MAX";I.Pow="POW";I.Floor="FLOOR";I.Ceiling="CEILING";I.Int="INT";I.Float="FLOAT";I.Has="?";I.Hasnt="!?";I.Intersect="^";I.ListMin="LIST_MIN";I.ListMax="LIST_MAX";I.All="LIST_ALL";I.Count="LIST_COUNT";I.ValueOfList="LIST_VALUE";I.Invert="LIST_INVERT";I._nativeFunctions=null;});var hi=C(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.NumberExpression=void 0;var Vc=Se(),Fs=B(),kc=D(),Vs=class s extends Vc.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 Fs.IntValue(this.value)):this.isFloat()?n.AddContent(new Fs.FloatValue(this.value)):this.isBool()&&n.AddContent(new Fs.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, kc.asOrNull)(e,s);return t?t.subtype==this.subtype&&t.value==this.value:false}};ui.NumberExpression=Vs;});var ks=C(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.UnaryExpression=void 0;var Rc=Se(),Dc=Fe(),Pt=hi(),Lc=D(),on=class extends Rc.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(Dc.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};ci.UnaryExpression=on;on.WithInner=(s,e)=>{let t=(0, Lc.asOrNull)(s,Pt.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new Pt.NumberExpression(-t.value,"int");if(t.isFloat())return new Pt.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new Pt.NumberExpression(t.value==0,"bool");if(t.isFloat())return new Pt.NumberExpression(t.value==0,"bool");if(t.isBool())return new Pt.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new on(s,e)};});var Ds=C(di=>{Object.defineProperty(di,"__esModule",{value:true});di.BinaryExpression=void 0;var Wc=Se(),qc=Fe(),jc=ks(),Mc=D(),Rs=class extends Wc.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(qc.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, Mc.asOrNull)(this.leftExpression,jc.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.`);}}};di.BinaryExpression=Rs;});var un=C(fi=>{Object.defineProperty(fi,"__esModule",{value:true});fi.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);}};fi.CharacterSet=ln;ln.FromRange=(s,e)=>new ln().AddRange(s,e);});var bl=C(pi=>{Object.defineProperty(pi,"__esModule",{value:true});pi.CharacterRange=void 0;var Sl=un(),hn=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Sl.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),a;i<=this.end.charCodeAt(0);i+=1)a=String.fromCharCode(i),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},n instanceof Sl.CharacterSet)this._excludes=n.set;else for(let i of n)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};pi.CharacterRange=hn;hn.Define=(s,e,t=[])=>new hn(s,e,t);});var mi=C(gi=>{Object.defineProperty(gi,"__esModule",{value:true});gi.ChoicePoint=void 0;var Bc=he(),Gc=ue(),Ls=ne(),Ws=class extends Bc.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, Ls.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Ls.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new Gc.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, Ls.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};gi.ChoicePoint=Ws;});var ut=C(Ci=>{Object.defineProperty(Ci,"__esModule",{value:true});Ci.PushPopType=void 0;var _l;(function(s){s[s.Tunnel=0]="Tunnel",s[s.Function=1]="Function",s[s.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(_l||(Ci.PushPopType=_l={}));});var cn=C(vi=>{Object.defineProperty(vi,"__esModule",{value:true});vi.Pointer=void 0;var $c=ue(),qs=class s{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new $c.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new s(this.container,this.index)}static StartOf(e){return new s(e,0)}static get Null(){return new s(null,-1)}};vi.Pointer=qs;});var Ve=C(Si=>{Object.defineProperty(Si,"__esModule",{value:true});Si.Divert=void 0;var Jc=ue(),Hc=ut(),Uc=at(),Kc=he(),js=cn(),El=H(),yi=ne(),Ms=class s extends Kc.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=js.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, yi.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, yi.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, yi.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof El.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=js.Pointer.StartOf(e instanceof El.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new Jc.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=js.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 s&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, yi.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 Uc.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==Hc.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};Si.Divert=Ms;});var Be=C(bi=>{Object.defineProperty(bi,"__esModule",{value:true});bi.SymbolType=void 0;var Tl;(function(s){s[s.Knot=0]="Knot",s[s.List=1]="List",s[s.ListItem=2]="ListItem",s[s.Var=3]="Var",s[s.SubFlowAndWeave=4]="SubFlowAndWeave",s[s.Arg=5]="Arg",s[s.Temp=6]="Temp";})(Tl||(bi.SymbolType=Tl={}));});var Ue=C(_i=>{Object.defineProperty(_i,"__esModule",{value:true});_i.VariableAssignment=void 0;var zc=he(),Bs=class extends zc.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};_i.VariableAssignment=Bs;});var Ot=C(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.Choice=void 0;var Xc=mi(),Ei=H(),Ke=ie(),Gs=Ve(),wl=B(),Yc=M(),Qc=Be(),xl=Ue(),$s=class extends Yc.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 Ei.Container,this._runtimeChoice=new Xc.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Ke.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new wl.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new xl.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Ke.ControlCommand.BeginString()),this._divertToStartContentOuter=new Gs.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Gs.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Ei.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Ke.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Ke.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Ke.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(Ke.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Ei.Container,this.startContent){this._returnToR2=new wl.DivertTargetValue,this._innerContentContainer.AddContent(Ke.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Ke.ControlCommand.EvalEnd());let i=new xl.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Gs.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Ei.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,Qc.SymbolType.SubFlowAndWeave);}};Ti.Choice=$s;});var Pl=C(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.StringParserElement=void 0;var wi=class s{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{s._uniqueIdCounter++,this.uniqueId=s._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};xi.StringParserElement=wi;wi._uniqueIdCounter=1e3;});var Nl=C(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.StringParserState=void 0;var Ol=Pl(),Js=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let n=0;n<200;++n)this._stack[n]=new Ol.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(t),n.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],n=this._stack[this._numElements-1];t.SquashFrom(n),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new Ol.StringParserElement;this._numElements=1;}};Pi.StringParserState=Js;});var Us=C(ht=>{Object.defineProperty(ht,"__esModule",{value:true});ht.StringParser=ht.ParseSuccess=void 0;var Hs=un(),Zc=Nl();ht.ParseSuccess=Symbol("ParseSuccessStruct");var dn=class s{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),r=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,r,a),this.state.Squash();let o=i;return o===null&&(o=s.ParseSuccess),o},this.Expect=(n,i=null,a=null)=>{let r=this.ParseObject(n);if(r===null){i===null&&(i=n.name);let o,l=this.LineRemainder();l===null||l.length===0?o="end of line":o=`'${l}'`,this.Error(`Expected ${i} but saw ${o}`),a!==null&&(r=a());}return r},this.Error=(n,i=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 r=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,i-1,a);else throw new Error(`${r} on line ${i}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
5
5
  \r`)),this.SetFlag=(n,i)=>{i?this.state.customFlags|=n:this.state.customFlags&=~n;},this.GetFlag=n=>!!(this.state.customFlags&n),this.ParseObject=n=>{let i=this.BeginRule(),a=this.state.stackHeight,r=n();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return r===null?this.FailRule(i):(this.SucceedRule(i,r),r)},this.Parse=n=>{let i=this.BeginRule(),a=n();return a===null?(this.FailRule(i),null):(this.SucceedRule(i,a),a)},this.OneOf=n=>{for(let i of n){let a=this.ParseObject(i);if(a!==null)return a}return null},this.OneOrMore=n=>{let i=[],a=null;do a=this.ParseObject(n),a!==null&&i.push(a);while(a!==null);return i.length>0?i:null},this.Optional=n=>()=>{let i=this.ParseObject(n);return i===null?s.ParseSuccess:i},this.Exclude=n=>()=>this.ParseObject(n)&&s.ParseSuccess,this.OptionalExclude=n=>()=>(this.ParseObject(n),s.ParseSuccess),this.String=n=>()=>this.ParseString(n),this.TryAddResultToList=(n,i,a=true)=>{if(n!==s.ParseSuccess){if(a&&Array.isArray(n)){let r=n;if(r!==null){for(let o of r)i.push(o);return}}i.push(n);}},this.Interleave=(n,i,a=null,r=true)=>{let o=this.BeginRule(),l=[],u=this.ParseObject(n);if(u===null)return this.FailRule(o);this.TryAddResultToList(u,l,r);let h=null,c=null;do{if(a!==null&&this.Peek(a)!==null||(h=this.ParseObject(i),h===null))break;if(this.TryAddResultToList(h,l,r),c=null,h!==null){if(c=this.ParseObject(n),c===null)break;this.TryAddResultToList(c,l,r);}}while((h!==null||c!==null)&&!(h===s.ParseSuccess&&c==s.ParseSuccess)&&this.remainingLength>0);return l.length===0?this.FailRule(o):this.SucceedRule(o,l)},this.ParseString=n=>{if(n.length>this.remainingLength)return null;let i=this.BeginRule(),a=this.index,r=this.characterInLineIndex,o=this.lineIndex,l=true;for(let u=0;u<n.length;u+=1){let h=n[u];if(this._chars[a]!==h){l=false;break}h===`
6
6
  `&&(o++,r=-1),a++,r++;}return this.index=a,this.characterInLineIndex=r,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 r=new Gs.CharacterSet(n);return typeof i=="number"?this.ParseCharactersFromCharSet(r,true,i):this.ParseCharactersFromCharSet(r,i,a)},this.ParseCharactersFromCharSet=(n,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let r=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,h=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===i&&h<a;)this._chars[o]===`
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 r=new Hs.CharacterSet(n);return typeof i=="number"?this.ParseCharactersFromCharSet(r,true,i):this.ParseCharactersFromCharSet(r,i,a)},this.ParseCharactersFromCharSet=(n,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let r=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,h=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===i&&h<a;)this._chars[o]===`
8
8
  `&&(u+=1,l=-1),o+=1,l+=1,h+=1;return this.index=o,this.characterInLineIndex=l,this.lineIndex=u,this.index>r?this._chars.slice(r,this.index).join(""):null},this.Peek=n=>{let i=this.BeginRule(),a=n();return this.CancelRule(i),a},this.ParseInt=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");let r=this.ParseCharactersFromCharSet(s.numbersCharacterSet);if(r===null)return this.index=n,this.characterInLineIndex=i,null;let o;return Number.isNaN(Number(r))?(this.Error("Failed to read integer value: "+r+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(o=Number(r),a?-o:o)},this.ParseFloat=()=>{let n=this.index,i=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let r=this.ParseCharactersFromCharSet(s.numbersCharacterSet);return +`${a}.${r}`}return this.index=n,this.characterInLineIndex=i,null},this.ParseNewline=()=>{let n=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
9
9
  `)===null?this.FailRule(n):this.SucceedRule(n,`
10
- `)};let t=this.PreProcessInputString(e);this.state=new Xc.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 Gs.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let r="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(r+=l),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(t!==null&&t.set.has(u)){r+=u,u===`
11
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return r.length>0?this.SucceedRule(i,String(r)):this.FailRule(i)}};lt.StringParser=hn;hn.ParseSuccess=lt.ParseSuccess;hn.numbersCharacterSet=new Gs.CharacterSet("0123456789");});var Ol=C(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.CommentEliminator=void 0;var Js=on(),Yc=$s(),Hs=class extends Yc.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Js.CharacterSet(`/\r
12
- `),this._commentBlockEndCharacter=new Js.CharacterSet("*"),this._newlineCharacters=new Js.CharacterSet(`
10
+ `)};let t=this.PreProcessInputString(e);this.state=new Zc.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,n=null){let i=this.BeginRule(),a=new Hs.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let r="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(r+=l),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(t!==null&&t.set.has(u)){r+=u,u===`
11
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return r.length>0?this.SucceedRule(i,String(r)):this.FailRule(i)}};ht.StringParser=dn;dn.ParseSuccess=ht.ParseSuccess;dn.numbersCharacterSet=new Hs.CharacterSet("0123456789");});var Al=C(Oi=>{Object.defineProperty(Oi,"__esModule",{value:true});Oi.CommentEliminator=void 0;var Ks=un(),ed=Us(),zs=class extends ed.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Ks.CharacterSet(`/\r
12
+ `),this._commentBlockEndCharacter=new Ks.CharacterSet("*"),this._newlineCharacters=new Ks.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}};xi.CommentEliminator=Hs;});var Oi=C(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.Conditional=void 0;var Qc=J(),Nl=ne(),Zc=j(),Us=class extends Zc.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new Qc.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(Nl.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Nl.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);}};Pi.Conditional=Us;});var Ue=C(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.Text=void 0;var ed=j(),td=M(),Ks=class extends ed.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new td.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Ni.Text=Ks;});var Ii=C(Ai=>{Object.defineProperty(Ai,"__esModule",{value:true});Ai.ConstantDeclaration=void 0;var nd=j(),id=je(),zs=class extends nd.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,id.SymbolType.Var);}};Ai.ConstantDeclaration=zs;});var Pt=C(Fi=>{Object.defineProperty(Fi,"__esModule",{value:true});Fi.FlowLevel=void 0;var Al;(function(s){s[s.Story=0]="Story",s[s.Knot=1]="Knot",s[s.Stitch=2]="Stitch",s[s.WeavePoint=3]="WeavePoint";})(Al||(Fi.FlowLevel=Al={}));});var cn=C(Vi=>{Object.defineProperty(Vi,"__esModule",{value:true});Vi.Gather=void 0;var rd=J(),sd=j(),ad=je(),Xs=class extends sd.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 rd.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,ad.SymbolType.SubFlowAndWeave);}};Vi.Gather=Xs;});var ut=C(Ri=>{Object.defineProperty(Ri,"__esModule",{value:true});Ri.Path=void 0;var ki=R(),Il=Ve(),Ot=Pt(),od=ht(),Ys=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Ot.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(ki.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Ot.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 r=a===n,o=this.GetChildFromContext(a,i,null,r);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=n=>{let i=n;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let r=this.components[a].name,o,l=(0, ki.asOrNull)(i,Il.FlowBase);if(l!==null?o=l.flowLevel+1:o=Ot.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,r,o),i===null)break}return i},this.GetChildFromContext=(n,i,a,r=false)=>{let o=a===null,l=(0, ki.asOrNull)(n,od.Weave);if(i&&l!==null&&(o||a===Ot.FlowLevel.WeavePoint))return l.WeavePointNamed(i);let u=(0, ki.asOrNull)(n,Il.FlowBase);if(i&&u!==null){let h=r||u.flowLevel===Ot.FlowLevel.Knot;return u.ContentWithNameAtLevel(i,a,h)}return null},Object.values(Ot.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"}};Ri.Path=Ys;});var ea=C(Di=>{Object.defineProperty(Di,"__esModule",{value:true});Di.ReturnType=void 0;var ld=j(),ud=J(),Qs=ne(),hd=at(),Zs=class extends ld.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new ud.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(Qs.ControlCommand.EvalStart()),t.AddContent(new hd.Void),t.AddContent(Qs.ControlCommand.EvalEnd())),t.AddContent(Qs.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Di.ReturnType=Zs;});var dn=C(Li=>{Object.defineProperty(Li,"__esModule",{value:true});Li.ClosestFlowBase=void 0;function cd(s){let e=s.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}Li.ClosestFlowBase=cd;});var qi=C(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.Identifier=void 0;var ta=class s{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new s("DONE")}};Wi.Identifier=ta;});var Ve=C(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.FlowBase=void 0;var dd=xt(),na=At(),fd=Nt(),ke=Pt(),pd=cn(),gd=j(),md=ut(),Cd=ea(),vd=J(),yd=Fe(),Sd=Je(),ia=je(),bd=ht(),_d=dn(),Ed=qi(),Fl=R(),ra=class s extends gd.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var 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=(r,o)=>{var l,u;let h=[],c=[];this._subFlowsByName=new Map;for(let p of r){let m=(0, Fl.asOrNull)(p,s);m?(this._firstChildFlow===null&&(this._firstChildFlow=m),c.push(p),!((l=m.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=m.identifier)===null||u===void 0?void 0:u.name,m)):h.push(p);}o&&h.push(new pd.Gather(null,1),new na.Divert(new md.Path(Ed.Identifier.Done())));let f=[];return h.length>0&&(this._rootWeave=new bd.Weave(h,0),f.push(this._rootWeave)),c.length>0&&f.push(...c),f},this.ResolveVariableWithName=(r,o)=>{var l;let u={},h=o===null?this:(0, _d.ClosestFlowBase)(o);if(h){if(h.args!==null){for(let c of h.args)if(((l=c.identifier)===null||l===void 0?void 0:l.name)===r)return u.found=true,u.isArgument=true,u.ownerFlow=h,u}if(h!==this.story&&h.variableDeclarations.has(r))return u.found=true,u.ownerFlow=h,u.isTemporary=true,u}return this.story.variableDeclarations.has(r)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=r=>{let o=r.variableName;if(this.variableDeclarations.has(o)){let l=this.variableDeclarations.get(o),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${u}`,r,false);return}this.variableDeclarations.set(r.variableName,r);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,r]of this._subFlowsByName)r.hasOwnProperty("ResolveWeavePointNaming")&&r.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var r;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===ke.FlowLevel.Knot||this.flowLevel===ke.FlowLevel.Stitch)&&(o=this.Find(Cd.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 vd.Container;l.name=(r=this.identifier)===null||r===void 0?void 0:r.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 s){let c=h,f=c.runtimeObject;u===0&&!c.hasParameters&&this.flowLevel===ke.FlowLevel.Knot&&(this._startingSubFlowDivert=new yd.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let p=f,m=l.namedContent.get(p.name)||null;if(m){let y=`${this.GetType()} already contains flow named '${p.name}' (at ${m.debugMetadata})`;this.Error(y,c);}l.AddToNamedContentOnly(p);}else h&&l.AddContent(h.runtimeObject);u+=1;}return this.flowLevel!==ke.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=r=>{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 Sd.VariableAssignment(u,true);r.AddContent(h);}},this.ContentWithNameAtLevel=(r,o=null,l=false)=>{var u;if((o===this.flowLevel||o===null)&&r===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===ke.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(r),c))return c;if(o===ke.FlowLevel.WeavePoint)return l?this.DeepSearchForAnyLevelContent(r):null}if(o!==null&&o<this.flowLevel)return null;let h=this._subFlowsByName.get(r)||null;return h&&(o===null||o===h.flowLevel)?h:l?this.DeepSearchForAnyLevelContent(r):null},this.DeepSearchForAnyLevelContent=r=>{let o=this.ContentWithNameAtLevel(r,ke.FlowLevel.WeavePoint,false);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(r,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==ke.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[l,u]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${l}' within the function '${this.identifier}'`,u);if(!this._rootWeave)throw new Error;let r=this._rootWeave.FindAll(na.Divert)();for(let l of r)!l.isFunctionCall&&!(l.parent instanceof fd.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(dd.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},this.WarningInTermination=r=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";r.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let l=(0, Fl.asOrNull)(r,na.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,r);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,ia.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!==ke.FlowLevel.Story){let i=this.flowLevel===ke.FlowLevel.Knot?ia.SymbolType.Knot:ia.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};ji.FlowBase=ra;});var Bi=C(Mi=>{Object.defineProperty(Mi,"__esModule",{value:true});Mi.ContentList=void 0;var Td=J(),wd=j(),xd=Ue(),Pd=R(),sa=class extends wd.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, Pd.asOrNull)(this.content[n],xd.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new Td.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"}};Mi.ContentList=sa;});var It=C(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.VariableReference=void 0;var Od=ue(),Nd=le(),aa=class extends Od.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 Nd.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};Gi.VariableReference=aa;});var Ft=C($i=>{Object.defineProperty($i,"__esModule",{value:true});$i.VariableReference=void 0;var Ad=Bi(),Id=ye(),Vl=Ve(),Fd=ut(),Vd=It(),kd=ht(),Rd=qi(),kl=R(),oa=class extends Id.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(kl.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new Rd.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 Vd.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 Fd.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, kl.asOrNull)(n,Vl.FlowBase);i&&i.isFunction&&(this.parent instanceof kd.Weave||this.parent instanceof Ad.ContentList||this.parent instanceof Vl.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);}};$i.VariableReference=oa;});var fn=C(Ki=>{Object.defineProperty(Ki,"__esModule",{value:true});Ki.FunctionCall=void 0;var Re=ne(),Dd=At(),Ld=Nt(),Wd=ye(),qd=ce(),jd=M(),Hi=Ie(),Rl=li(),Md=ut(),Bd=M(),Gd=Ft(),Ji=R(),Ui=class s extends Wd.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(Re.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(Re.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let r=(0, Ji.asOrNull)(this.args[0],Ld.DivertTarget),o=(0, Ji.asOrNull)(this.args[0],Gd.VariableReference);if(this.args.length!==1||r===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}r?(this._divertTargetToCount=r,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(Re.ControlCommand.TurnsSince()):n.AddContent(Re.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let r=0;r<this.args.length;r+=1){let o=(0, Ji.asOrNull)(this.args[r],Rl.NumberExpression);if(o&&!o.isInt()){let l=r===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[r].GenerateIntoContainer(n);}n.AddContent(Re.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let r=(0, Ji.asOrNull)(this.args[0],Rl.NumberExpression);r&&!r.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(Re.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let r=0;r<this.args.length;r+=1)this.args[r].GenerateIntoContainer(n);n.AddContent(Re.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(Re.ControlCommand.ListRandom());else if(Hi.NativeFunctionCall.CallExistsWithName(this.name)){let r=Hi.NativeFunctionCall.CallWithName(this.name);if(r.numberOfParameters!==this.args.length){let o=`${s.name} should take ${r.numberOfParameters} parameter`;r.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(n);n.AddContent(Hi.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 Bd.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(Re.ControlCommand.ListFromInt());else {let r=new qd.InkList;r.SetInitialOriginName(this.name),n.AddContent(new jd.ListValue(r));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(Re.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new Dd.Divert(new Md.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 '${s.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Ki.FunctionCall=Ui;Ui.IsBuiltIn=s=>Hi.NativeFunctionCall.CallExistsWithName(s)?true:s==="CHOICE_COUNT"||s==="TURNS_SINCE"||s==="TURNS"||s==="RANDOM"||s==="SEED_RANDOM"||s==="LIST_VALUE"||s==="LIST_RANDOM"||s==="READ_COUNT";});var ua=C(zi=>{Object.defineProperty(zi,"__esModule",{value:true});zi.MultipleConditionExpression=void 0;var $d=ye(),Jd=Ie(),la=class extends $d.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(Jd.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};zi.MultipleConditionExpression=la;});var Nt=C(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.DivertTarget=void 0;var Hd=Vs(),Ud=xt(),Kd=Oi(),zd=fa(),Xd=M(),ha=ye(),Yd=Ve(),Dl=fn(),Qd=ua(),Ll=Ft(),ca=R(),da=class s extends ha.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new Xd.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, ca.asOrNull)(t,s);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 ha.Expression;){let i=false,a=false,r=t.parent;if(r instanceof Hd.BinaryExpression){let o=r;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof s||o.leftExpression instanceof Ll.VariableReference)&&(o.rightExpression instanceof s||o.rightExpression instanceof Ll.VariableReference)||(i=true),a=true;}else if(r instanceof Dl.FunctionCall){let o=r;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (r instanceof ha.Expression||r instanceof Qd.MultipleConditionExpression||r instanceof Ud.Choice&&r.condition===t||r instanceof Kd.Conditional||r instanceof zd.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=r;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let n=this.divert.targetContent;if(n!==null){let i=n.containerForCounting;if(i!==null){let r=(0, ca.asOrNull)(this.parent,Dl.FunctionCall);r&&r.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, ca.asOrNull)(n,Yd.FlowBase);if(a!=null&&a.args!==null)for(let r of a.args)r.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${r.identifier}').`);}}};Xi.DivertTarget=da;});var At=C(Yi=>{Object.defineProperty(Yi,"__esModule",{value:true});Yi.Divert=void 0;var Zd=J(),pn=ne(),ef=Fe(),pa=Nt(),ga=Ve(),tf=fn(),nf=j(),Wl=ut(),rf=le(),ql=ot(),sf=M(),jl=Ft(),af=dn(),gn=R(),ma=class extends nf.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 pn.ControlCommand.End();if(this.isDone)return pn.ControlCommand.Done();this.runtimeDivert=new ef.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 Zd.Container;if(n){this.isFunctionCall||i.AddContent(pn.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let r=0;r<this.args.length;++r){let o=this.args[r],l=null;if(a&&r<a.length&&(l=a[r]),l&&l.isByReference){let u=(0, gn.asOrNull)(o,jl.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let h=new Wl.Path(u.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let f=new sf.VariablePointerValue(u.name);i.AddContent(f);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(pn.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(pn.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?ql.PushPopType.Function:ql.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let i=(0, gn.asOrNull)((0, af.ClosestFlowBase)(this),ga.FlowBase);if(i){let a=i.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let r=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});r&&!r.isDivertTarget&&this.Error(`Since '${r.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${r.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let i=(0, gn.asOrNull)(this.targetContent,ga.FlowBase);if(n===0&&(i===null||!i.hasParameters))return;if(i===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&n>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof pa.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==n){let r;n===0?r="but there weren't any passed to it":n<a?r=`but only got ${n}`:r=`but got ${n}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${r}`);return}for(let r=0;r<a;++r){let o=i.args[r],l=this.args[r];if(o.isDivertTarget){let u=(0, gn.asOrNull)(l,jl.VariableReference);if(!(l instanceof pa.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 Wl.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let i=this.target?this.target.firstComponent:null,a=n.externals.get(i);if(!a)throw new Error("external not found");let r=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==r&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${r} but got ${o}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <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, gn.asOrNull)(this.targetContent,ga.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 pa.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=tf.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 rf.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);}};Yi.Divert=ma;});var Ml=C(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.GatherPointToResolve=void 0;var Ca=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};Qi.GatherPointToResolve=Ca;});var Bl=C(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.SequenceDivertToResolve=void 0;var va=class{constructor(e,t){this.divert=e,this.targetContent=t;}};Zi.SequenceDivertToResolve=va;});var ya=C(er=>{Object.defineProperty(er,"__esModule",{value:true});er.SequenceType=void 0;var Gl;(function(s){s[s.Stopping=1]="Stopping",s[s.Cycle=2]="Cycle",s[s.Shuffle=4]="Shuffle",s[s.Once=8]="Once";})(Gl||(er.SequenceType=Gl={}));});var _a=C(ir=>{Object.defineProperty(ir,"__esModule",{value:true});ir.Sequence=void 0;var $l=J(),we=ne(),Sa=Fe(),mn=M(),tr=Ie(),of=j(),lf=Bl(),nr=ya(),uf=ht(),ba=class extends of.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new $l.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(we.ControlCommand.EvalStart()),n.AddContent(we.ControlCommand.VisitIndex());let i=(this.sequenceType&nr.SequenceType.Once)>0,a=(this.sequenceType&nr.SequenceType.Cycle)>0,r=(this.sequenceType&nr.SequenceType.Stopping)>0,o=(this.sequenceType&nr.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(i&&(l+=1),r||i?(n.AddContent(new mn.IntValue(l-1)),n.AddContent(tr.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new mn.IntValue(this.sequenceElements.length)),n.AddContent(tr.NativeFunctionCall.CallWithName("%"))),o){let h=we.ControlCommand.NoOp();if(i||r){let f=r?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(we.ControlCommand.Duplicate()),n.AddContent(new mn.IntValue(f)),n.AddContent(tr.NativeFunctionCall.CallWithName("=="));let p=new Sa.Divert;p.isConditional=true,n.AddContent(p),this.AddDivertToResolve(p,h);}let c=this.sequenceElements.length;r&&(c-=1),n.AddContent(new mn.IntValue(c)),n.AddContent(we.ControlCommand.SequenceShuffleIndex()),(i||r)&&n.AddContent(h);}n.AddContent(we.ControlCommand.EvalEnd());let u=we.ControlCommand.NoOp();for(let h=0;h<l;h+=1){n.AddContent(we.ControlCommand.EvalStart()),n.AddContent(we.ControlCommand.Duplicate()),n.AddContent(new mn.IntValue(h)),n.AddContent(tr.NativeFunctionCall.CallWithName("==")),n.AddContent(we.ControlCommand.EvalEnd());let c=new Sa.Divert;c.isConditional=true,n.AddContent(c);let f;h<this.sequenceElements.length?f=this.sequenceElements[h].runtimeObject:f=new $l.Container,f.name=`s${h}`,f.InsertContent(we.ControlCommand.PopEvaluatedValue(),0);let p=new Sa.Divert;f.AddContent(p),n.AddToNamedContentOnly(f),this.AddDivertToResolve(c,f),this.AddDivertToResolve(p,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new lf.SequenceDivertToResolve(n,i));},this.sequenceType=t,this.sequenceElements=[];for(let n of e){let i=n.content,a=null;i===null||i.length===0?a=n:a=new uf.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;}};ir.Sequence=ba;});var Ta=C(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.TunnelOnwards=void 0;var hf=J(),Cn=ne(),cf=Fe(),df=M(),ff=j(),pf=at(),gf=R(),mf=It(),Ea=class extends ff.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new hf.Container;if(e.AddContent(Cn.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let r=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(r==-1&&u.commandType===Cn.ControlCommand.CommandType.EvalStart?r=l:u.commandType===Cn.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=r+1;l<o;l+=1){let u=n.content[l];u.parent=null,e.AddContent(n.content[l]);}}}let i=(0, gf.asOrNull)(t,cf.Divert);if(i!=null&&i.hasVariableTarget){let a=new mf.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new df.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new pf.Void);return e.AddContent(Cn.ControlCommand.EvalEnd()),e.AddContent(Cn.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);}};rr.TunnelOnwards=Ea;});var Pa=C(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.ListDefinition=void 0;var wa=ce(),xa=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 wa.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 wa.InkListItem(this.name,n),{result:t,exists:true};return t=wa.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}}};sr.ListDefinition=xa;});var or=C(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.ListDefinition=void 0;var Cf=ce(),vf=ce(),yf=Pa(),Sf=M(),bf=j(),_f=je(),Oa=class extends bf.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 yf.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 Cf.InkList;for(let r of this.itemDefinitions)if(r.inInitialList){let o=new vf.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,r.name||null);a.Add(o,r.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new Sf.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,_f.SymbolType.List);}};ar.ListDefinition=Oa;});var Aa=C(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.VariableAssignment=void 0;var Ef=J(),Tf=dn(),wf=or(),xf=j(),Jl=je(),Pf=Je(),Of=Ft(),Nf=R(),Na=class extends xf.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let r=null;if(this.isGlobalDeclaration?r=this.story:this.isNewTemporaryDeclaration&&(r=(0, Tf.ClosestFlowBase)(this)),r&&r.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new Ef.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Pf.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 wf.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?Jl.SymbolType.Var:Jl.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, Nf.asOrNull)(this.expression,Of.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);}}};lr.VariableAssignment=Na;});var ht=C(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.Weave=void 0;var Hl=Hn(),be=xt(),ur=Oi(),Af=Ii(),If=J(),hr=At(),Ff=Fe(),Vf=Nt(),kf=Ve(),De=cn(),Rf=Ml(),Df=j(),Ia=_a(),Lf=Ue(),Wf=Ta(),qf=Aa(),_e=R(),Fa=class s extends Df.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, _e.asOrNull)(e,Lf.Text);if(!(i&&i.text===`
15
- `)&&!this.IsGlobalDeclaration(e))break}let t=(0, _e.asOrNull)(e,s);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 r=[...this.FindAll(De.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(be.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of r){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof De.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 be.Choice||i instanceof De.Gather){let r=i.indentationDepth-1;if(r>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let c=(0, _e.asOrNull)(this.content[n],be.Choice)||(0, _e.asOrNull)(this.content[n],De.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 s(u,r);this.InsertContent(o,h),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let i of n)if(i instanceof be.Choice||i instanceof De.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new If.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof be.Choice||n instanceof De.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof s){let i=n;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let r of this.looseEnds){let o=r;if(o instanceof De.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof hr.Divert)l=o.runtimeObject;else {l=new Ff.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new Rf.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof De.Gather)this.AddRuntimeForGather(n);else if(n instanceof be.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof De.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, _e.asOrNull)(n,be.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 r=this.parent;r!==null;r=r.parent){let o=(0, _e.asOrNull)(r,s);o&&(!a&&n===null&&(n=o),a&&i===null&&(i=o)),(r instanceof Ia.Sequence||r instanceof ur.Conditional)&&(a=true);}if(!(n===null&&i===null))for(let r=this.looseEnds.length-1;r>=0;r-=1){let o=this.looseEnds[r],l=false;if(a){if(o instanceof be.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof be.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(r,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(n);return i||null},this.IsGlobalDeclaration=n=>{let i=(0, _e.asOrNull)(n,qf.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, _e.asOrNull)(n,Af.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let i=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||i.push(l);let r=(0, _e.asOrNull)(a.parent,s);if(r===null)throw new Error("Expected weave point parent to be weave?");let o=r.content.indexOf(a);for(let l=o+1;l<r.content.length;l+=1){let u=r.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof be.Choice||u instanceof De.Gather||u instanceof s)break;i.push(u);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof Hl.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let r=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(r,a,n);}else {for(let a of this.content)if(a instanceof be.Choice||a instanceof hr.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let i=null;for(let r=n.parent;r!==null;r=r.parent)if(r instanceof Ia.Sequence||r instanceof ur.Conditional){i=(0, _e.asOrNull)(r,ur.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(be.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,i,a)=>{let r=false,o=i;for(let l of n){if(l.Find(hr.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof Vf.DivertTarget))!==null&&(r=true),l.Find(Wf.TunnelOnwards)()!=null){r=true;break}o=l;}if(!r){if(o instanceof Hl.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, _e.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, _e.asOrNull)(i,kf.FlowBase);if(a)n.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let r of n){let o=r.ContentWithNameAtLevel(i);if(o&&o!==a){let l=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(l,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof Ia.Sequence||n instanceof ur.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};cr.Weave=Fa;});var fa=C(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.ConditionalSingleBranch=void 0;var Ul=J(),dr=ne(),Kl=Fe(),jf=j(),Mf=Ie(),Bf=M(),Gf=Ue(),$f=ht(),Jf=R(),Va=class extends jf.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, Jf.asOrNull)(i,Gf.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 Ul.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(dr.ControlCommand.Duplicate()),this._conditionalDivert=new Kl.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(dr.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(Mf.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(dr.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new Bf.StringValue(`
16
- `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(dr.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Kl.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new Ul.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new $f.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);}};fr.ConditionalSingleBranch=Va;});var Xl=C(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.CustomFlags=void 0;var zl;(function(s){s[s.ParsingString=1]="ParsingString",s[s.TagActive=2]="TagActive";})(zl||(pr.CustomFlags=zl={}));});var Yl=C(gr=>{Object.defineProperty(gr,"__esModule",{value:true});gr.DebugMetadata=void 0;var ka=class s{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new s;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}};gr.DebugMetadata=ka;});var Ql=C(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.ExternalDeclaration=void 0;var Hf=j(),Ra=class extends Hf.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}`}};mr.ExternalDeclaration=Ra;});var Zl=C(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.FlowDecl=void 0;var Da=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};Cr.FlowDecl=Da;});var Wa=C(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.Wrap=void 0;var Uf=j(),La=class extends Uf.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};vr.Wrap=La;});var eu=C(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.Glue=void 0;var Kf=Wa(),qa=class extends Kf.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};yr.Glue=qa;});var br=C(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.Glue=void 0;var zf=ue(),ja=class extends zf.InkObject{toString(){return "Glue"}};Sr.Glue=ja;});var nu=C(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.IncDecExpression=void 0;var Xf=Bi(),tu=ye(),Yf=Ve(),Qf=Ie(),Zf=M(),ep=Je(),tp=It(),np=ht(),Ma=class extends tu.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,r;i.AddContent(new tp.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new Zf.IntValue(1)),i.AddContent(Qf.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new ep.VariableAssignment(((r=this.varIdentifier)===null||r===void 0?void 0:r.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 tu.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 np.Weave)&&!(this.parent instanceof Yf.FlowBase)&&!(this.parent instanceof Xf.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};_r.IncDecExpression=Ma;});var Ga=C(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.IncludedFile=void 0;var ip=j(),Ba=class extends ip.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Er.IncludedFile=Ba;});var iu=C(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.InfixOperator=void 0;var $a=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};Tr.InfixOperator=$a;});var Ha=C(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.Knot=void 0;var rp=Ve(),ru=Pt(),Ja=class extends rp.FlowBase{get flowLevel(){return ru.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,ru.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(n),r=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(r,a);}}}};wr.Knot=Ja;});var su=C(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.List=void 0;var sp=ye(),ap=ce(),op=ce(),lp=M(),Ua=class extends sp.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,i;let a=new ap.InkList;if(this.itemIdentifierList!=null)for(let r of this.itemIdentifierList){let o=((n=r?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";o.length>1?(l=o[0],u=o[1]):u=o[0];let h=this.story.ResolveListItem(l,u,this);if(h===null)l===null?this.Error(`Could not find list definition that contains item '${r}'`):this.Error(`Could not find list item ${r}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${r}`);return}l||(l=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new op.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${r}' in list.`):a.Add(c,h.seriesValue);}}t.AddContent(new lp.ListValue(a));};}get typeName(){return "List"}};xr.List=Ua;});var za=C(Pr=>{Object.defineProperty(Pr,"__esModule",{value:true});Pr.ListElementDefinition=void 0;var up=j(),hp=je(),Ka=class extends up.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,hp.SymbolType.ListItem);}};Pr.ListElementDefinition=Ka;});var Xa=C(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.StatementLevel=void 0;var au;(function(s){s[s.InnerBlock=0]="InnerBlock",s[s.Stitch=1]="Stitch",s[s.Knot=2]="Knot",s[s.Top=3]="Top";})(au||(Or.StatementLevel=au={}));});var Qa=C(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.Stitch=void 0;var cp=Ve(),dp=Pt(),Ya=class extends cp.FlowBase{get flowLevel(){return dp.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"}};Nr.Stitch=Ya;});var Ir=C(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.Tag=void 0;var fp=ue(),Za=class extends fp.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Ar.Tag=Za;});var to=C(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.Choice=void 0;var pp=le(),gp=te(),mp=ue(),eo=class s extends mp.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, gp.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new pp.Path(e);}Clone(){let e=new s;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};Fr.Choice=eo;});var io=C(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.ListDefinitionsOrigin=void 0;var Cp=ce(),vp=M(),yp=te(),no=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=Cp.InkListItem.fromSerializedKey(n),r=new vp.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,r),this._allUnambiguousListValueCache.set(a.fullName,r);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let n=this._lists.get(e);return n?{result:n,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, yp.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Vr.ListDefinitionsOrigin=no;});var kt=C(Lr=>{Object.defineProperty(Lr,"__esModule",{value:true});Lr.JsonSerialisation=void 0;var kr=J(),fe=M(),ou=br(),F=ne(),Vt=ot(),lu=Fe(),uu=pi(),ro=It(),hu=Je(),so=Ie(),cu=at(),du=Ir(),Sp=le(),fu=to(),bp=Pa(),_p=io(),Rr=ce(),H=R(),ct=te(),Dr=class s{static JArrayToRuntimeObjList(e,t=false){let n=e.length;t&&n--;let i=[];for(let a=0;a<n;a++){let r=e[a],o=this.JTokenToRuntimeObject(r);if(o===null)return (0, ct.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, H.asOrNull)(t,kr.Container);if(n){this.WriteRuntimeContainer(e,n);return}let i=(0, H.asOrNull)(t,lu.Divert);if(i){let g="->";i.isExternal?g="x()":i.pushesToStack&&(i.stackPushType==Vt.PushPopType.Function?g="f()":i.stackPushType==Vt.PushPopType.Tunnel&&(g="->t->"));let E;i.hasVariableTarget?E=i.variableDivertName:E=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(g,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, H.asOrNull)(t,uu.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let r=(0, H.asOrNull)(t,fe.BoolValue);if(r){e.WriteBool(r.value);return}let o=(0, H.asOrNull)(t,fe.IntValue);if(o){e.WriteInt(o.value);return}let l=(0, H.asOrNull)(t,fe.FloatValue);if(l){e.WriteFloat(l.value);return}let u=(0, H.asOrNull)(t,fe.StringValue);if(u){u.isNewline?e.Write(`
17
- `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(u.value),e.WriteStringEnd());return}let h=(0, H.asOrNull)(t,fe.ListValue);if(h){this.WriteInkList(e,h);return}let c=(0, H.asOrNull)(t,fe.DivertTargetValue);if(c){if(e.WriteObjectStart(),c.value===null)return (0, ct.throwNullException)("divTargetVal.value");e.WriteProperty("^->",c.value.componentsString),e.WriteObjectEnd();return}let f=(0, H.asOrNull)(t,fe.VariablePointerValue);if(f){e.WriteObjectStart(),e.WriteProperty("^var",f.value),e.WriteIntProperty("ci",f.contextIndex),e.WriteObjectEnd();return}if((0, H.asOrNull)(t,ou.Glue)){e.Write("<>");return}let m=(0, H.asOrNull)(t,F.ControlCommand);if(m){e.Write(s._controlCommandNames[m.commandType]);return}let y=(0, H.asOrNull)(t,so.NativeFunctionCall);if(y){let g=y.name;g=="^"&&(g="L^"),e.Write(g);return}let b=(0, H.asOrNull)(t,ro.VariableReference);if(b){e.WriteObjectStart();let g=b.pathStringForCount;g!=null?e.WriteProperty("CNT?",g):e.WriteProperty("VAR?",b.name),e.WriteObjectEnd();return}let _=(0, H.asOrNull)(t,hu.VariableAssignment);if(_){e.WriteObjectStart();let g=_.isGlobal?"VAR=":"temp=";e.WriteProperty(g,_.variableName),_.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, H.asOrNull)(t,cu.Void)){e.Write("void");return}let S=(0, H.asOrNull)(t,du.Tag);if(S){e.WriteObjectStart(),e.WriteProperty("#",S.text),e.WriteObjectEnd();return}let v=(0, H.asOrNull)(t,fu.Choice);if(v){this.WriteChoice(e,v);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(e[n]);if(i===null)return (0, ct.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 fe.Value.Create(e);if(typeof e=="string"){let t=e.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(t);if(n)return new fe.FloatValue(parseFloat(n[0]));let i=t[0];if(i=="^")return new fe.StringValue(t.substring(1));if(i==`
18
- `&&t.length==1)return new fe.StringValue(`
19
- `);if(t=="<>")return new ou.Glue;for(let a=0;a<s._controlCommandNames.length;++a){let r=s._controlCommandNames[a];if(t==r)return new F.ControlCommand(a)}if(t=="L^"&&(t="^"),so.NativeFunctionCall.CallExistsWithName(t))return so.NativeFunctionCall.CallWithName(t);if(t=="->->")return F.ControlCommand.PopTunnel();if(t=="~ret")return F.ControlCommand.PopFunction();if(t=="void")return new cu.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new fe.DivertTargetValue(new Sp.Path(n.toString()));if(t["^var"]){n=t["^var"];let h=new fe.VariablePointerValue(n.toString());return "ci"in t&&(n=t.ci,h.contextIndex=parseInt(n)),h}let i=false,a=false,r=Vt.PushPopType.Function,o=false;if((n=t["->"])?i=true:(n=t["f()"])?(i=true,a=true,r=Vt.PushPopType.Function):(n=t["->t->"])?(i=true,a=true,r=Vt.PushPopType.Tunnel):(n=t["x()"])&&(i=true,o=true,a=false,r=Vt.PushPopType.Function),i){let h=new lu.Divert;h.pushesToStack=a,h.stackPushType=r,h.isExternal=o;let c=n.toString();return (n=t.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!t.c,o&&(n=t.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=t["*"]){let h=new uu.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=t.flg)&&(h.flags=parseInt(n)),h}if(n=t["VAR?"])return new ro.VariableReference(n.toString());if(n=t["CNT?"]){let h=new ro.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,f=new hu.VariableAssignment(h,c);return f.isGlobal=u,f}if(t["#"]!==void 0)return n=t["#"],new du.Tag(n.toString());if(n=t.list){let h=n,c=new Rr.InkList;if(n=t.origins){let f=n;c.SetInitialOriginNames(f);}for(let f in h)if(h.hasOwnProperty(f)){let p=h[f],m=new Rr.InkListItem(f),y=parseInt(p);c.Add(m,y);}return new fe.ListValue(c)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,n){return JSON.stringify(e,(i,a)=>t?.some(r=>r===i)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=false){if(e.WriteArrayStart(),t===null)return (0, ct.throwNullException)("container");for(let l of t.content)this.WriteRuntimeObject(e,l);let i=t.namedOnlyContent,a=t.countFlags,r=t.name!=null&&!n,o=i!=null||a>0||r;if(o&&e.WriteObjectStart(),i!=null)for(let[l,u]of i){let h=l,c=(0, H.asOrNull)(u,kr.Container);e.WritePropertyStart(h),this.WriteRuntimeContainer(e,c,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),r&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new kr.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 r=this.JTokenToRuntimeObject(n[a]),o=(0, H.asOrNull)(r,kr.Container);o&&(o.name=a),i.set(a,r);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new fu.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, ct.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of n){let r=Rr.InkListItem.fromSerializedKey(i),o=a;if(r.itemName===null)return (0, ct.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(r.originName?r.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(r.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of n.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let i={};for(let[a,r]of n.items){let o=Rr.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, ct.throwNullException)("item.itemName");i[o.itemName]=r;}t[n.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),r=t[i],o=new Map;for(let u in r)if(t.hasOwnProperty(i)){let h=r[u];o.set(u,parseInt(h));}let l=new bp.ListDefinition(a,o);n.push(l);}return new _p.ListDefinitionsOrigin(n)}};Lr.JsonSerialisation=Dr;Dr._controlCommandNames=(()=>{let s=[];s[F.ControlCommand.CommandType.EvalStart]="ev",s[F.ControlCommand.CommandType.EvalOutput]="out",s[F.ControlCommand.CommandType.EvalEnd]="/ev",s[F.ControlCommand.CommandType.Duplicate]="du",s[F.ControlCommand.CommandType.PopEvaluatedValue]="pop",s[F.ControlCommand.CommandType.PopFunction]="~ret",s[F.ControlCommand.CommandType.PopTunnel]="->->",s[F.ControlCommand.CommandType.BeginString]="str",s[F.ControlCommand.CommandType.EndString]="/str",s[F.ControlCommand.CommandType.NoOp]="nop",s[F.ControlCommand.CommandType.ChoiceCount]="choiceCnt",s[F.ControlCommand.CommandType.Turns]="turn",s[F.ControlCommand.CommandType.TurnsSince]="turns",s[F.ControlCommand.CommandType.ReadCount]="readc",s[F.ControlCommand.CommandType.Random]="rnd",s[F.ControlCommand.CommandType.SeedRandom]="srnd",s[F.ControlCommand.CommandType.VisitIndex]="visit",s[F.ControlCommand.CommandType.SequenceShuffleIndex]="seq",s[F.ControlCommand.CommandType.StartThread]="thread",s[F.ControlCommand.CommandType.Done]="done",s[F.ControlCommand.CommandType.End]="end",s[F.ControlCommand.CommandType.ListFromInt]="listInt",s[F.ControlCommand.CommandType.ListRange]="range",s[F.ControlCommand.CommandType.ListRandom]="lrnd",s[F.ControlCommand.CommandType.BeginTag]="#",s[F.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<F.ControlCommand.CommandType.TOTAL_VALUES;++e)if(s[e]==null)throw new Error("Control command not accounted for in serialisation");return s})();});var lo=C(Sn=>{Object.defineProperty(Sn,"__esModule",{value:true});Sn.CallStack=void 0;var ao=ot(),pu=le(),Ep=bn(),gu=kt(),Tp=M(),wp=rt(),vn=un(),xp=zt(),mu=_t(),oo=te(),yn=class s{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){xp.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=vn.Pointer.Null,arguments[0]instanceof Ep.Story){let e=arguments[0];this._startOfRoot=vn.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new s.Thread),this._threads[0].callstack.push(new s.Element(ao.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let i of n){let a=i,r=new s.Thread(a,t);this._threads.push(r);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=vn.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==ao.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let i=new s.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, mu.tryGetValueFromMap)(n.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let r=(0, mu.tryGetValueFromMap)(a.temporaryVariables,e,null);r.exists&&Tp.ListValue.RetainListOriginsForAssignment(r.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new wp.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==ao.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let r=n.callstack[a].currentPointer;if(!r.isNull){if(e.Append("<SOMEWHERE IN "),r.container===null)return (0, oo.throwNullException)("pointer.container");e.Append(r.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Sn.CallStack=yn;(function(s){class e{constructor(i,a,r=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=r,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}s.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=vn.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let r=i.callstack;for(let l of r){let u=l,h=parseInt(u.type),c=vn.Pointer.Null,f,p=u.cPath;if(typeof p<"u"){f=p.toString();let _=a.ContentAtPath(new pu.Path(f));if(c.container=_.container,c.index=parseInt(u.idx),_.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+f+". Has the story changed since this save data was created?");_.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let m=!!u.exp,y=new e(h,c,m),b=u.temp;typeof b<"u"?y.temporaryVariables=gu.JsonSerialisation.JObjectToDictionaryRuntimeObjs(b):y.temporaryVariables.clear(),this.callstack.push(y);}let o=i.previousContentObject;if(typeof o<"u"){let l=new pu.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let i=new 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, oo.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"),gu.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, oo.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}s.Thread=t;})(yn||(Sn.CallStack=yn={}));});var vu=C(qr=>{Object.defineProperty(qr,"__esModule",{value:true});qr.VariablesState=void 0;var Z=M(),Pp=Yt(),Cu=kt(),ie=R(),_n=_t(),Ke=te();function Op(){return class{}}var Wr=class s extends Op(){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 Pp.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=Z.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,r){return a in i?i[a]=r:i.$(a,r),!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, Ke.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=Cu.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Ke.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let i=t,a=n;if(s.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let r=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,r))continue}e.WritePropertyStart(i),Cu.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Ke.throwNullException)("obj1");if(t===null)return (0, Ke.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let n=(0, ie.asOrNull)(e,Z.BoolValue);if(n!==null)return n.value===(0, ie.asOrThrows)(t,Z.BoolValue).value;let i=(0, ie.asOrNull)(e,Z.IntValue);if(i!==null)return i.value===(0, ie.asOrThrows)(t,Z.IntValue).value;let a=(0, ie.asOrNull)(e,Z.FloatValue);if(a!==null)return a.value===(0, ie.asOrThrows)(t,Z.FloatValue).value;let r=(0, ie.asOrNull)(e,Z.Value),o=(0, ie.asOrNull)(t,Z.Value);if(r!==null&&o!==null)return (0, ie.isEquatable)(r.valueObject)&&(0, ie.isEquatable)(o.valueObject)?r.valueObject.Equals(o.valueObject):r.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let n=this.GetRawVariableWithName(e,t),i=(0, ie.asOrNull)(n,Z.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(e){let t=(0, _n.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, _n.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, _n.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Ke.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, Ke.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let r=(0, ie.asOrNull)(t,Z.VariablePointerValue);r!==null&&(t=this.ResolveVariablePointer(r));}else {let r=null;do r=(0, ie.asOrNull)(this.GetRawVariableWithName(n,i),Z.VariablePointerValue),r!=null&&(n=r.variableName,i=r.contextIndex,a=i==0);while(r!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, ie.asOrThrows)(e,Z.ListValue),i=(0, ie.asOrThrows)(t,Z.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, _n.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, _n.tryGetValueFromMap)(this._globalVariables,e,null))),Z.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, Ke.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, Ke.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, ie.asOrNull)(n,Z.VariablePointerValue);return i??new Z.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};qr.VariablesState=Wr;Wr.dontSaveDefaultValues=true;});var ho=C(jr=>{Object.defineProperty(jr,"__esModule",{value:true});jr.PRNG=void 0;var uo=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}};jr.PRNG=uo;});var yu=C(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.StatePatch=void 0;var co=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let 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}}};Mr.StatePatch=co;});var fo=C(Tn=>{Object.defineProperty(Tn,"__esModule",{value:true});Tn.SimpleJson=void 0;var En=class s{static TextToDictionary(e){return new s.Reader(e).ToDictionary()}static TextToArray(e){return new s.Reader(e).ToArray()}};Tn.SimpleJson=En;(function(s){class e{constructor(i){if(JSON.parse("0",(r,o,l)=>l!=null)){let r=(o,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(i,r);}else {let r=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(r);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}s.Reader=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===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===s.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let r=arguments[1];r(this);}else {let r=arguments[1];this.Write(r);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===s.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===s.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===s.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property)),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===s.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==s.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===s.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===s.Writer.State.None||this.state===s.Writer.State.Property||this.state===s.Writer.State.Array):this.Assert(this.state===s.Writer.State.Property||this.state===s.Writer.State.Array),this.state===s.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===s.Writer.State.Array||this.state===s.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:s.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===s.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===s.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}s.Writer=t,function(n){(function(r){r[r.None=0]="None",r[r.Object=1]="Object",r[r.Array=2]="Array",r[r.Property=3]="Property",r[r.PropertyName=4]="PropertyName",r[r.String=5]="String";})(n.State||(n.State={}));class a{constructor(o){this.type=s.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;}(t=s.Writer||(s.Writer={}));})(En||(Tn.SimpleJson=En={}));});var bu=C(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.Flow=void 0;var Su=lo(),Br=kt(),Np=te(),po=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new Su.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=Br.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=Br.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=>Br.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, Np.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)Br.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 Su.CallStack.Thread(a,t);}}}};Gr.Flow=po;});var Tu=C(Jr=>{Object.defineProperty(Jr,"__esModule",{value:true});Jr.StoryState=void 0;var Ap=lo(),Ip=vu(),X=M(),ze=ot(),Fp=Ir(),go=br(),_u=le(),ae=ne(),mo=rt(),Xe=kt(),Vp=ho(),kp=at(),Rt=un(),wn=_t(),U=R(),Rp=zt(),Ee=te(),Dp=bn(),Lp=yu(),Eu=fo(),$r=bu(),Wp=ce(),Co=class s{ToJson(e=false){let t=new Eu.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=Eu.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 _u.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, wn.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, Ee.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, wn.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, wn.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, wn.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, Ee.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, Ee.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 mo.StringBuilder,t=false;for(let n of this.outputStream){let i=(0, U.asOrNull)(n,X.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, U.asOrNull)(n,ae.ControlCommand);a!==null&&(a.commandType==ae.ControlCommand.CommandType.BeginTag?t=true:a.commandType==ae.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new mo.StringBuilder,n=-1,i=0;for(let a=0;a<e.length;a++){let r=e.charAt(a),o=r==" "||r==" ";o&&n==-1&&(n=a),o||(r!=`
14
+ `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};Oi.CommentEliminator=zs;});var Ai=C(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.Conditional=void 0;var td=H(),Il=ie(),nd=M(),Xs=class extends nd.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new td.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let a=i.runtimeObject;n.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(Il.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Il.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=t;}super.ResolveReferences(e);}};Ni.Conditional=Xs;});var ze=C(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.Text=void 0;var id=M(),rd=B(),Ys=class extends id.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new rd.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Ii.Text=Ys;});var Vi=C(Fi=>{Object.defineProperty(Fi,"__esModule",{value:true});Fi.ConstantDeclaration=void 0;var sd=M(),ad=Be(),Qs=class extends sd.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,ad.SymbolType.Var);}};Fi.ConstantDeclaration=Qs;});var Nt=C(ki=>{Object.defineProperty(ki,"__esModule",{value:true});ki.FlowLevel=void 0;var Fl;(function(s){s[s.Story=0]="Story",s[s.Knot=1]="Knot",s[s.Stitch=2]="Stitch",s[s.WeavePoint=3]="WeavePoint";})(Fl||(ki.FlowLevel=Fl={}));});var fn=C(Ri=>{Object.defineProperty(Ri,"__esModule",{value:true});Ri.Gather=void 0;var od=H(),ld=M(),ud=Be(),Zs=class extends ld.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 od.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,ud.SymbolType.SubFlowAndWeave);}};Ri.Gather=Zs;});var ct=C(Li=>{Object.defineProperty(Li,"__esModule",{value:true});Li.Path=void 0;var Di=D(),Vl=ke(),At=Nt(),hd=dt(),ea=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?At.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(Di.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===At.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 r=a===n,o=this.GetChildFromContext(a,i,null,r);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=n=>{let i=n;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let r=this.components[a].name,o,l=(0, Di.asOrNull)(i,Vl.FlowBase);if(l!==null?o=l.flowLevel+1:o=At.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,r,o),i===null)break}return i},this.GetChildFromContext=(n,i,a,r=false)=>{let o=a===null,l=(0, Di.asOrNull)(n,hd.Weave);if(i&&l!==null&&(o||a===At.FlowLevel.WeavePoint))return l.WeavePointNamed(i);let u=(0, Di.asOrNull)(n,Vl.FlowBase);if(i&&u!==null){let h=r||u.flowLevel===At.FlowLevel.Knot;return u.ContentWithNameAtLevel(i,a,h)}return null},Object.values(At.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"}};Li.Path=ea;});var ia=C(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.ReturnType=void 0;var cd=M(),dd=H(),ta=ie(),fd=lt(),na=class extends cd.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new dd.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(ta.ControlCommand.EvalStart()),t.AddContent(new fd.Void),t.AddContent(ta.ControlCommand.EvalEnd())),t.AddContent(ta.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Wi.ReturnType=na;});var pn=C(qi=>{Object.defineProperty(qi,"__esModule",{value:true});qi.ClosestFlowBase=void 0;function pd(s){let e=s.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}qi.ClosestFlowBase=pd;});var Mi=C(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.Identifier=void 0;var ra=class s{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new s("DONE")}};ji.Identifier=ra;});var ke=C(Bi=>{Object.defineProperty(Bi,"__esModule",{value:true});Bi.FlowBase=void 0;var gd=Ot(),sa=Ft(),md=It(),Re=Nt(),Cd=fn(),vd=M(),yd=ct(),Sd=ia(),bd=H(),_d=Ve(),Ed=Ue(),aa=Be(),Td=dt(),wd=pn(),xd=Mi(),kl=D(),oa=class s extends vd.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=(r,o)=>{var l,u;let h=[],c=[];this._subFlowsByName=new Map;for(let p of r){let g=(0, kl.asOrNull)(p,s);g?(this._firstChildFlow===null&&(this._firstChildFlow=g),c.push(p),!((l=g.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=g.identifier)===null||u===void 0?void 0:u.name,g)):h.push(p);}o&&h.push(new Cd.Gather(null,1),new sa.Divert(new yd.Path(xd.Identifier.Done())));let f=[];return h.length>0&&(this._rootWeave=new Td.Weave(h,0),f.push(this._rootWeave)),c.length>0&&f.push(...c),f},this.ResolveVariableWithName=(r,o)=>{var l;let u={},h=o===null?this:(0, wd.ClosestFlowBase)(o);if(h){if(h.args!==null){for(let c of h.args)if(((l=c.identifier)===null||l===void 0?void 0:l.name)===r)return u.found=true,u.isArgument=true,u.ownerFlow=h,u}if(h!==this.story&&h.variableDeclarations.has(r))return u.found=true,u.ownerFlow=h,u.isTemporary=true,u}return this.story.variableDeclarations.has(r)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=r=>{let o=r.variableName;if(this.variableDeclarations.has(o)){let l=this.variableDeclarations.get(o),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${u}`,r,false);return}this.variableDeclarations.set(r.variableName,r);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,r]of this._subFlowsByName)r.hasOwnProperty("ResolveWeavePointNaming")&&r.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var r;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===Re.FlowLevel.Knot||this.flowLevel===Re.FlowLevel.Stitch)&&(o=this.Find(Sd.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 bd.Container;l.name=(r=this.identifier)===null||r===void 0?void 0:r.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 s){let c=h,f=c.runtimeObject;u===0&&!c.hasParameters&&this.flowLevel===Re.FlowLevel.Knot&&(this._startingSubFlowDivert=new _d.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let p=f,g=l.namedContent.get(p.name)||null;if(g){let y=`${this.GetType()} already contains flow named '${p.name}' (at ${g.debugMetadata})`;this.Error(y,c);}l.AddToNamedContentOnly(p);}else h&&l.AddContent(h.runtimeObject);u+=1;}return this.flowLevel!==Re.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=r=>{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 Ed.VariableAssignment(u,true);r.AddContent(h);}},this.ContentWithNameAtLevel=(r,o=null,l=false)=>{var u;if((o===this.flowLevel||o===null)&&r===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===Re.FlowLevel.WeavePoint||o===null){let c=null;if(this._rootWeave&&(c=this._rootWeave.WeavePointNamed(r),c))return c;if(o===Re.FlowLevel.WeavePoint)return l?this.DeepSearchForAnyLevelContent(r):null}if(o!==null&&o<this.flowLevel)return null;let h=this._subFlowsByName.get(r)||null;return h&&(o===null||o===h.flowLevel)?h:l?this.DeepSearchForAnyLevelContent(r):null},this.DeepSearchForAnyLevelContent=r=>{let o=this.ContentWithNameAtLevel(r,Re.FlowLevel.WeavePoint,false);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(r,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==Re.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[l,u]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${l}' within the function '${this.identifier}'`,u);if(!this._rootWeave)throw new Error;let r=this._rootWeave.FindAll(sa.Divert)();for(let l of r)!l.isFunctionCall&&!(l.parent instanceof md.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(gd.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},this.WarningInTermination=r=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";r.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let l=(0, kl.asOrNull)(r,sa.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,r);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,aa.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!==Re.FlowLevel.Story){let i=this.flowLevel===Re.FlowLevel.Knot?aa.SymbolType.Knot:aa.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};Bi.FlowBase=oa;});var $i=C(Gi=>{Object.defineProperty(Gi,"__esModule",{value:true});Gi.ContentList=void 0;var Pd=H(),Od=M(),Nd=ze(),Ad=D(),la=class extends Od.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, Ad.asOrNull)(this.content[n],Nd.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 Pd.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"}};Gi.ContentList=la;});var Vt=C(Ji=>{Object.defineProperty(Ji,"__esModule",{value:true});Ji.VariableReference=void 0;var Id=he(),Fd=ue(),ua=class extends Id.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 Fd.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};Ji.VariableReference=ua;});var kt=C(Hi=>{Object.defineProperty(Hi,"__esModule",{value:true});Hi.VariableReference=void 0;var Vd=$i(),kd=Se(),Rl=ke(),Rd=ct(),Dd=Vt(),Ld=dt(),Wd=Mi(),Dl=D(),ha=class extends kd.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(Dl.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new Wd.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 Dd.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 Rd.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, Dl.asOrNull)(n,Rl.FlowBase);i&&i.isFunction&&(this.parent instanceof Ld.Weave||this.parent instanceof Vd.ContentList||this.parent instanceof Rl.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${t}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};Hi.VariableReference=ha;});var gn=C(Xi=>{Object.defineProperty(Xi,"__esModule",{value:true});Xi.FunctionCall=void 0;var De=ie(),qd=Ft(),jd=It(),Md=Se(),Bd=de(),Gd=B(),Ki=Fe(),Ll=hi(),$d=ct(),Jd=B(),Hd=kt(),Ui=D(),zi=class s extends Md.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(De.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(De.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let r=(0, Ui.asOrNull)(this.args[0],jd.DivertTarget),o=(0, Ui.asOrNull)(this.args[0],Hd.VariableReference);if(this.args.length!==1||r===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}r?(this._divertTargetToCount=r,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(De.ControlCommand.TurnsSince()):n.AddContent(De.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let r=0;r<this.args.length;r+=1){let o=(0, Ui.asOrNull)(this.args[r],Ll.NumberExpression);if(o&&!o.isInt()){let l=r===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[r].GenerateIntoContainer(n);}n.AddContent(De.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let r=(0, Ui.asOrNull)(this.args[0],Ll.NumberExpression);r&&!r.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(De.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let r=0;r<this.args.length;r+=1)this.args[r].GenerateIntoContainer(n);n.AddContent(De.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(De.ControlCommand.ListRandom());else if(Ki.NativeFunctionCall.CallExistsWithName(this.name)){let r=Ki.NativeFunctionCall.CallWithName(this.name);if(r.numberOfParameters!==this.args.length){let o=`${s.name} should take ${r.numberOfParameters} parameter`;r.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(n);n.AddContent(Ki.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 Jd.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(De.ControlCommand.ListFromInt());else {let r=new Bd.InkList;r.SetInitialOriginName(this.name),n.AddContent(new Gd.ListValue(r));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(De.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new qd.Divert(new $d.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 '${s.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};Xi.FunctionCall=zi;zi.IsBuiltIn=s=>Ki.NativeFunctionCall.CallExistsWithName(s)?true:s==="CHOICE_COUNT"||s==="TURNS_SINCE"||s==="TURNS"||s==="RANDOM"||s==="SEED_RANDOM"||s==="LIST_VALUE"||s==="LIST_RANDOM"||s==="READ_COUNT";});var da=C(Yi=>{Object.defineProperty(Yi,"__esModule",{value:true});Yi.MultipleConditionExpression=void 0;var Ud=Se(),Kd=Fe(),ca=class extends Ud.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(Kd.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Yi.MultipleConditionExpression=ca;});var It=C(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.DivertTarget=void 0;var zd=Ds(),Xd=Ot(),Yd=Ai(),Qd=ma(),Zd=B(),fa=Se(),ef=ke(),Wl=gn(),tf=da(),ql=kt(),pa=D(),ga=class s extends fa.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new Zd.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, pa.asOrNull)(t,s);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 fa.Expression;){let i=false,a=false,r=t.parent;if(r instanceof zd.BinaryExpression){let o=r;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof s||o.leftExpression instanceof ql.VariableReference)&&(o.rightExpression instanceof s||o.rightExpression instanceof ql.VariableReference)||(i=true),a=true;}else if(r instanceof Wl.FunctionCall){let o=r;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (r instanceof fa.Expression||r instanceof tf.MultipleConditionExpression||r instanceof Xd.Choice&&r.condition===t||r instanceof Yd.Conditional||r instanceof Qd.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=r;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let n=this.divert.targetContent;if(n!==null){let i=n.containerForCounting;if(i!==null){let r=(0, pa.asOrNull)(this.parent,Wl.FunctionCall);r&&r.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, pa.asOrNull)(n,ef.FlowBase);if(a!=null&&a.args!==null)for(let r of a.args)r.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${r.identifier}').`);}}};Qi.DivertTarget=ga;});var Ft=C(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.Divert=void 0;var nf=H(),mn=ie(),rf=Ve(),Ca=It(),va=ke(),sf=gn(),af=M(),jl=ct(),of=ue(),Ml=ut(),lf=B(),Bl=kt(),uf=pn(),Cn=D(),ya=class extends af.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 mn.ControlCommand.End();if(this.isDone)return mn.ControlCommand.Done();this.runtimeDivert=new rf.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 nf.Container;if(n){this.isFunctionCall||i.AddContent(mn.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let r=0;r<this.args.length;++r){let o=this.args[r],l=null;if(a&&r<a.length&&(l=a[r]),l&&l.isByReference){let u=(0, Cn.asOrNull)(o,Bl.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let h=new jl.Path(u.pathIdentifiers);if(h.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${h.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let f=new lf.VariablePointerValue(u.name);i.AddContent(f);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(mn.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(mn.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Ml.PushPopType.Function:Ml.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, Cn.asOrNull)((0, uf.ClosestFlowBase)(this),va.FlowBase);if(i){let a=i.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let r=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});r&&!r.isDivertTarget&&this.Error(`Since '${r.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${r.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let i=(0, Cn.asOrNull)(this.targetContent,va.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 Ca.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==n){let r;n===0?r="but there weren't any passed to it":n<a?r=`but only got ${n}`:r=`but got ${n}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${r}`);return}for(let r=0;r<a;++r){let o=i.args[r],l=this.args[r];if(o.isDivertTarget){let u=(0, Cn.asOrNull)(l,Bl.VariableReference);if(!(l instanceof Ca.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 jl.Path(u.pathIdentifiers);h.ResolveFromContext(u)&&this.Error(`Passing read count of '${h.dotSeparatedComponents}' instead of a divert target. You probably meant '${h}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let i=this.target?this.target.firstComponent:null,a=n.externals.get(i);if(!a)throw new Error("external not found");let r=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==r&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${r} but got ${o}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <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, Cn.asOrNull)(this.targetContent,va.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 Ca.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=sf.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 of.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);}};Zi.Divert=ya;});var Gl=C(er=>{Object.defineProperty(er,"__esModule",{value:true});er.GatherPointToResolve=void 0;var Sa=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};er.GatherPointToResolve=Sa;});var $l=C(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.SequenceDivertToResolve=void 0;var ba=class{constructor(e,t){this.divert=e,this.targetContent=t;}};tr.SequenceDivertToResolve=ba;});var _a=C(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.SequenceType=void 0;var Jl;(function(s){s[s.Stopping=1]="Stopping",s[s.Cycle=2]="Cycle",s[s.Shuffle=4]="Shuffle",s[s.Once=8]="Once";})(Jl||(nr.SequenceType=Jl={}));});var wa=C(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.Sequence=void 0;var Hl=H(),xe=ie(),Ea=Ve(),vn=B(),ir=Fe(),hf=M(),cf=$l(),rr=_a(),df=dt(),Ta=class extends hf.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new Hl.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(xe.ControlCommand.EvalStart()),n.AddContent(xe.ControlCommand.VisitIndex());let i=(this.sequenceType&rr.SequenceType.Once)>0,a=(this.sequenceType&rr.SequenceType.Cycle)>0,r=(this.sequenceType&rr.SequenceType.Stopping)>0,o=(this.sequenceType&rr.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(i&&(l+=1),r||i?(n.AddContent(new vn.IntValue(l-1)),n.AddContent(ir.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new vn.IntValue(this.sequenceElements.length)),n.AddContent(ir.NativeFunctionCall.CallWithName("%"))),o){let h=xe.ControlCommand.NoOp();if(i||r){let f=r?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(xe.ControlCommand.Duplicate()),n.AddContent(new vn.IntValue(f)),n.AddContent(ir.NativeFunctionCall.CallWithName("=="));let p=new Ea.Divert;p.isConditional=true,n.AddContent(p),this.AddDivertToResolve(p,h);}let c=this.sequenceElements.length;r&&(c-=1),n.AddContent(new vn.IntValue(c)),n.AddContent(xe.ControlCommand.SequenceShuffleIndex()),(i||r)&&n.AddContent(h);}n.AddContent(xe.ControlCommand.EvalEnd());let u=xe.ControlCommand.NoOp();for(let h=0;h<l;h+=1){n.AddContent(xe.ControlCommand.EvalStart()),n.AddContent(xe.ControlCommand.Duplicate()),n.AddContent(new vn.IntValue(h)),n.AddContent(ir.NativeFunctionCall.CallWithName("==")),n.AddContent(xe.ControlCommand.EvalEnd());let c=new Ea.Divert;c.isConditional=true,n.AddContent(c);let f;h<this.sequenceElements.length?f=this.sequenceElements[h].runtimeObject:f=new Hl.Container,f.name=`s${h}`,f.InsertContent(xe.ControlCommand.PopEvaluatedValue(),0);let p=new Ea.Divert;f.AddContent(p),n.AddToNamedContentOnly(f),this.AddDivertToResolve(c,f),this.AddDivertToResolve(p,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,i)=>{this._sequenceDivertsToResolve.push(new cf.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 df.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;}};sr.Sequence=Ta;});var Pa=C(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.TunnelOnwards=void 0;var ff=H(),yn=ie(),pf=Ve(),gf=B(),mf=M(),Cf=lt(),vf=D(),yf=Vt(),xa=class extends mf.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new ff.Container;if(e.AddContent(yn.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let r=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(r==-1&&u.commandType===yn.ControlCommand.CommandType.EvalStart?r=l:u.commandType===yn.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=r+1;l<o;l+=1){let u=n.content[l];u.parent=null,e.AddContent(n.content[l]);}}}let i=(0, vf.asOrNull)(t,pf.Divert);if(i!=null&&i.hasVariableTarget){let a=new yf.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new gf.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new Cf.Void);return e.AddContent(yn.ControlCommand.EvalEnd()),e.AddContent(yn.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);}};ar.TunnelOnwards=xa;});var Aa=C(or=>{Object.defineProperty(or,"__esModule",{value:true});or.ListDefinition=void 0;var Oa=de(),Na=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 Oa.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 Oa.InkListItem(this.name,n),{result:t,exists:true};return t=Oa.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}}};or.ListDefinition=Na;});var ur=C(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.ListDefinition=void 0;var Sf=de(),bf=de(),_f=Aa(),Ef=B(),Tf=M(),wf=Be(),Ia=class extends Tf.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 _f.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 Sf.InkList;for(let r of this.itemDefinitions)if(r.inInitialList){let o=new bf.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,r.name||null);a.Add(o,r.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new Ef.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,wf.SymbolType.List);}};lr.ListDefinition=Ia;});var Va=C(hr=>{Object.defineProperty(hr,"__esModule",{value:true});hr.VariableAssignment=void 0;var xf=H(),Pf=pn(),Of=ur(),Nf=M(),Ul=Be(),Af=Ue(),If=kt(),Ff=D(),Fa=class extends Nf.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:n,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let r=null;if(this.isGlobalDeclaration?r=this.story:this.isNewTemporaryDeclaration&&(r=(0, Pf.ClosestFlowBase)(this)),r&&r.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new xf.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Af.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 Of.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?Ul.SymbolType.Var:Ul.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, Ff.asOrNull)(this.expression,If.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);}}};hr.VariableAssignment=Fa;});var dt=C(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.Weave=void 0;var Kl=Kn(),_e=Ot(),cr=Ai(),Vf=Vi(),kf=H(),dr=Ft(),Rf=Ve(),Df=It(),Lf=ke(),Le=fn(),Wf=Gl(),qf=M(),ka=wa(),jf=ze(),Mf=Pa(),Bf=Va(),Ee=D(),Ra=class s extends qf.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, Ee.asOrNull)(e,jf.Text);if(!(i&&i.text===`
15
+ `)&&!this.IsGlobalDeclaration(e))break}let t=(0, Ee.asOrNull)(e,s);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 r=[...this.FindAll(Le.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(_e.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of r){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof Le.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 _e.Choice||i instanceof Le.Gather){let r=i.indentationDepth-1;if(r>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let c=(0, Ee.asOrNull)(this.content[n],_e.Choice)||(0, Ee.asOrNull)(this.content[n],Le.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 s(u,r);this.InsertContent(o,h),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let i of n)if(i instanceof _e.Choice||i instanceof Le.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new kf.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof _e.Choice||n instanceof Le.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof s){let i=n;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let r of this.looseEnds){let o=r;if(o instanceof Le.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof dr.Divert)l=o.runtimeObject;else {l=new Rf.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new Wf.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof Le.Gather)this.AddRuntimeForGather(n);else if(n instanceof _e.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Le.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, Ee.asOrNull)(n,_e.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 r=this.parent;r!==null;r=r.parent){let o=(0, Ee.asOrNull)(r,s);o&&(!a&&n===null&&(n=o),a&&i===null&&(i=o)),(r instanceof ka.Sequence||r instanceof cr.Conditional)&&(a=true);}if(!(n===null&&i===null))for(let r=this.looseEnds.length-1;r>=0;r-=1){let o=this.looseEnds[r],l=false;if(a){if(o instanceof _e.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof _e.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(r,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(n);return i||null},this.IsGlobalDeclaration=n=>{let i=(0, Ee.asOrNull)(n,Bf.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, Ee.asOrNull)(n,Vf.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let i=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||i.push(l);let r=(0, Ee.asOrNull)(a.parent,s);if(r===null)throw new Error("Expected weave point parent to be weave?");let o=r.content.indexOf(a);for(let l=o+1;l<r.content.length;l+=1){let u=r.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof _e.Choice||u instanceof Le.Gather||u instanceof s)break;i.push(u);}}return i},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof Kl.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let r=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(r,a,n);}else {for(let a of this.content)if(a instanceof _e.Choice||a instanceof dr.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let i=null;for(let r=n.parent;r!==null;r=r.parent)if(r instanceof ka.Sequence||r instanceof cr.Conditional){i=(0, Ee.asOrNull)(r,cr.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(_e.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,i,a)=>{let r=false,o=i;for(let l of n){if(l.Find(dr.Divert)(h=>!h.isThread&&!h.isTunnel&&!h.isFunctionCall&&!(h.parent instanceof Df.DivertTarget))!==null&&(r=true),l.Find(Mf.TunnelOnwards)()!=null){r=true;break}o=l;}if(!r){if(o instanceof Kl.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, Ee.asOrNull)(n.content[i],dr.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, Ee.asOrNull)(i,Lf.FlowBase);if(a)n.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let r of n){let o=r.ContentWithNameAtLevel(i);if(o&&o!==a){let l=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(l,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let n=this.parent;n!==null;n=n.parent)if(n instanceof ka.Sequence||n instanceof cr.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};fr.Weave=Ra;});var ma=C(gr=>{Object.defineProperty(gr,"__esModule",{value:true});gr.ConditionalSingleBranch=void 0;var zl=H(),pr=ie(),Xl=Ve(),Gf=M(),$f=Fe(),Jf=B(),Hf=ze(),Uf=dt(),Kf=D(),Da=class extends Gf.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, Kf.asOrNull)(i,Hf.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new zl.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(pr.ControlCommand.Duplicate()),this._conditionalDivert=new Xl.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(pr.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent($f.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(pr.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new Jf.StringValue(`
16
+ `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(pr.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Xl.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new zl.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new Uf.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);}};gr.ConditionalSingleBranch=Da;});var Ql=C(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.CustomFlags=void 0;var Yl;(function(s){s[s.ParsingString=1]="ParsingString",s[s.TagActive=2]="TagActive";})(Yl||(mr.CustomFlags=Yl={}));});var Zl=C(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.DebugMetadata=void 0;var La=class s{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new s;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.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}};Cr.DebugMetadata=La;});var eu=C(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.ExternalDeclaration=void 0;var zf=M(),Wa=class extends zf.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}`}};vr.ExternalDeclaration=Wa;});var tu=C(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.FlowDecl=void 0;var qa=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};yr.FlowDecl=qa;});var Ma=C(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.Wrap=void 0;var Xf=M(),ja=class extends Xf.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};Sr.Wrap=ja;});var nu=C(br=>{Object.defineProperty(br,"__esModule",{value:true});br.Glue=void 0;var Yf=Ma(),Ba=class extends Yf.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};br.Glue=Ba;});var Er=C(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.Glue=void 0;var Qf=he(),Ga=class extends Qf.InkObject{toString(){return "Glue"}};_r.Glue=Ga;});var ru=C(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.IncDecExpression=void 0;var Zf=$i(),iu=Se(),ep=ke(),tp=Fe(),np=B(),ip=Ue(),rp=Vt(),sp=dt(),$a=class extends iu.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,r;i.AddContent(new rp.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new np.IntValue(1)),i.AddContent(tp.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new ip.VariableAssignment(((r=this.varIdentifier)===null||r===void 0?void 0:r.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 iu.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!n):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let n=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(n.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=n.isGlobal,!(this.parent instanceof sp.Weave)&&!(this.parent instanceof ep.FlowBase)&&!(this.parent instanceof Zf.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Tr.IncDecExpression=$a;});var Ha=C(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.IncludedFile=void 0;var ap=M(),Ja=class extends ap.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};wr.IncludedFile=Ja;});var su=C(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.InfixOperator=void 0;var Ua=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};xr.InfixOperator=Ua;});var za=C(Pr=>{Object.defineProperty(Pr,"__esModule",{value:true});Pr.Knot=void 0;var op=ke(),au=Nt(),Ka=class extends op.FlowBase{get flowLevel(){return au.FlowLevel.Knot}constructor(e,t,n,i){super(e,t,n,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let n in this.subFlowsByName){let i=t.ContentWithNameAtLevel(n,au.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(n),r=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(r,a);}}}};Pr.Knot=Ka;});var ou=C(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.List=void 0;var lp=Se(),up=de(),hp=de(),cp=B(),Xa=class extends lp.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,i;let a=new up.InkList;if(this.itemIdentifierList!=null)for(let r of this.itemIdentifierList){let o=((n=r?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";o.length>1?(l=o[0],u=o[1]):u=o[0];let h=this.story.ResolveListItem(l,u,this);if(h===null)l===null?this.Error(`Could not find list definition that contains item '${r}'`):this.Error(`Could not find list item ${r}`);else {if(h.parent==null){this.Error(`Could not find list definition for item ${r}`);return}l||(l=((i=h.parent.identifier)===null||i===void 0?void 0:i.name)||null);let c=new hp.InkListItem(l,h.name||null);a.has(c.serialized())?this.Warning(`Duplicate of item '${r}' in list.`):a.Add(c,h.seriesValue);}}t.AddContent(new cp.ListValue(a));};}get typeName(){return "List"}};Or.List=Xa;});var Qa=C(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.ListElementDefinition=void 0;var dp=M(),fp=Be(),Ya=class extends dp.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,fp.SymbolType.ListItem);}};Nr.ListElementDefinition=Ya;});var Za=C(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.StatementLevel=void 0;var lu;(function(s){s[s.InnerBlock=0]="InnerBlock",s[s.Stitch=1]="Stitch",s[s.Knot=2]="Knot",s[s.Top=3]="Top";})(lu||(Ar.StatementLevel=lu={}));});var to=C(Ir=>{Object.defineProperty(Ir,"__esModule",{value:true});Ir.Stitch=void 0;var pp=ke(),gp=Nt(),eo=class extends pp.FlowBase{get flowLevel(){return gp.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"}};Ir.Stitch=eo;});var Vr=C(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.Tag=void 0;var mp=he(),no=class extends mp.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Fr.Tag=no;});var ro=C(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.Choice=void 0;var Cp=ue(),vp=ne(),yp=he(),io=class s extends yp.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, vp.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new Cp.Path(e);}Clone(){let e=new s;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};kr.Choice=io;});var ao=C(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.ListDefinitionsOrigin=void 0;var Sp=de(),bp=B(),_p=ne(),so=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=Sp.InkListItem.fromSerializedKey(n),r=new bp.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,r),this._allUnambiguousListValueCache.set(a.fullName,r);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let n=this._lists.get(e);return n?{result:n,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, _p.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Rr.ListDefinitionsOrigin=so;});var Dt=C(qr=>{Object.defineProperty(qr,"__esModule",{value:true});qr.JsonSerialisation=void 0;var Dr=H(),pe=B(),uu=Er(),k=ie(),Rt=ut(),hu=Ve(),cu=mi(),oo=Vt(),du=Ue(),lo=Fe(),fu=lt(),pu=Vr(),Ep=ue(),gu=ro(),Tp=Aa(),wp=ao(),Lr=de(),U=D(),ft=ne(),Wr=class s{static JArrayToRuntimeObjList(e,t=false){let n=e.length;t&&n--;let i=[];for(let a=0;a<n;a++){let r=e[a],o=this.JTokenToRuntimeObject(r);if(o===null)return (0, ft.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, U.asOrNull)(t,Dr.Container);if(n){this.WriteRuntimeContainer(e,n);return}let i=(0, U.asOrNull)(t,hu.Divert);if(i){let m="->";i.isExternal?m="x()":i.pushesToStack&&(i.stackPushType==Rt.PushPopType.Function?m="f()":i.stackPushType==Rt.PushPopType.Tunnel&&(m="->t->"));let _;i.hasVariableTarget?_=i.variableDivertName:_=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(m,_),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, U.asOrNull)(t,cu.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let r=(0, U.asOrNull)(t,pe.BoolValue);if(r){e.WriteBool(r.value);return}let o=(0, U.asOrNull)(t,pe.IntValue);if(o){e.WriteInt(o.value);return}let l=(0, U.asOrNull)(t,pe.FloatValue);if(l){e.WriteFloat(l.value);return}let u=(0, U.asOrNull)(t,pe.StringValue);if(u){u.isNewline?e.Write(`
17
+ `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(u.value),e.WriteStringEnd());return}let h=(0, U.asOrNull)(t,pe.ListValue);if(h){this.WriteInkList(e,h);return}let c=(0, U.asOrNull)(t,pe.DivertTargetValue);if(c){if(e.WriteObjectStart(),c.value===null)return (0, ft.throwNullException)("divTargetVal.value");e.WriteProperty("^->",c.value.componentsString),e.WriteObjectEnd();return}let f=(0, U.asOrNull)(t,pe.VariablePointerValue);if(f){e.WriteObjectStart(),e.WriteProperty("^var",f.value),e.WriteIntProperty("ci",f.contextIndex),e.WriteObjectEnd();return}if((0, U.asOrNull)(t,uu.Glue)){e.Write("<>");return}let g=(0, U.asOrNull)(t,k.ControlCommand);if(g){e.Write(s._controlCommandNames[g.commandType]);return}let y=(0, U.asOrNull)(t,lo.NativeFunctionCall);if(y){let m=y.name;m=="^"&&(m="L^"),e.Write(m);return}let b=(0, U.asOrNull)(t,oo.VariableReference);if(b){e.WriteObjectStart();let m=b.pathStringForCount;m!=null?e.WriteProperty("CNT?",m):e.WriteProperty("VAR?",b.name),e.WriteObjectEnd();return}let T=(0, U.asOrNull)(t,du.VariableAssignment);if(T){e.WriteObjectStart();let m=T.isGlobal?"VAR=":"temp=";e.WriteProperty(m,T.variableName),T.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, U.asOrNull)(t,fu.Void)){e.Write("void");return}let S=(0, U.asOrNull)(t,pu.Tag);if(S){e.WriteObjectStart(),e.WriteProperty("#",S.text),e.WriteObjectEnd();return}let v=(0, U.asOrNull)(t,gu.Choice);if(v){this.WriteChoice(e,v);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let i=this.JTokenToRuntimeObject(e[n]);if(i===null)return (0, ft.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 uu.Glue;for(let a=0;a<s._controlCommandNames.length;++a){let r=s._controlCommandNames[a];if(t==r)return new k.ControlCommand(a)}if(t=="L^"&&(t="^"),lo.NativeFunctionCall.CallExistsWithName(t))return lo.NativeFunctionCall.CallWithName(t);if(t=="->->")return k.ControlCommand.PopTunnel();if(t=="~ret")return k.ControlCommand.PopFunction();if(t=="void")return new fu.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new pe.DivertTargetValue(new Ep.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,r=Rt.PushPopType.Function,o=false;if((n=t["->"])?i=true:(n=t["f()"])?(i=true,a=true,r=Rt.PushPopType.Function):(n=t["->t->"])?(i=true,a=true,r=Rt.PushPopType.Tunnel):(n=t["x()"])&&(i=true,o=true,a=false,r=Rt.PushPopType.Function),i){let h=new hu.Divert;h.pushesToStack=a,h.stackPushType=r,h.isExternal=o;let c=n.toString();return (n=t.var)?h.variableDivertName=c:h.targetPathString=c,h.isConditional=!!t.c,o&&(n=t.exArgs)&&(h.externalArgs=parseInt(n)),h}if(n=t["*"]){let h=new cu.ChoicePoint;return h.pathStringOnChoice=n.toString(),(n=t.flg)&&(h.flags=parseInt(n)),h}if(n=t["VAR?"])return new oo.VariableReference(n.toString());if(n=t["CNT?"]){let h=new oo.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,f=new du.VariableAssignment(h,c);return f.isGlobal=u,f}if(t["#"]!==void 0)return n=t["#"],new pu.Tag(n.toString());if(n=t.list){let h=n,c=new Lr.InkList;if(n=t.origins){let f=n;c.SetInitialOriginNames(f);}for(let f in h)if(h.hasOwnProperty(f)){let p=h[f],g=new Lr.InkListItem(f),y=parseInt(p);c.Add(g,y);}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(r=>r===i)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=false){if(e.WriteArrayStart(),t===null)return (0, ft.throwNullException)("container");for(let l of t.content)this.WriteRuntimeObject(e,l);let i=t.namedOnlyContent,a=t.countFlags,r=t.name!=null&&!n,o=i!=null||a>0||r;if(o&&e.WriteObjectStart(),i!=null)for(let[l,u]of i){let h=l,c=(0, U.asOrNull)(u,Dr.Container);e.WritePropertyStart(h),this.WriteRuntimeContainer(e,c,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),r&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new Dr.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 r=this.JTokenToRuntimeObject(n[a]),o=(0, U.asOrNull)(r,Dr.Container);o&&(o.name=a),i.set(a,r);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new gu.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, ft.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of n){let r=Lr.InkListItem.fromSerializedKey(i),o=a;if(r.itemName===null)return (0, ft.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(r.originName?r.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(r.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of n.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let i={};for(let[a,r]of n.items){let o=Lr.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, ft.throwNullException)("item.itemName");i[o.itemName]=r;}t[n.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),r=t[i],o=new Map;for(let u in r)if(t.hasOwnProperty(i)){let h=r[u];o.set(u,parseInt(h));}let l=new Tp.ListDefinition(a,o);n.push(l);}return new wp.ListDefinitionsOrigin(n)}};qr.JsonSerialisation=Wr;Wr._controlCommandNames=(()=>{let s=[];s[k.ControlCommand.CommandType.EvalStart]="ev",s[k.ControlCommand.CommandType.EvalOutput]="out",s[k.ControlCommand.CommandType.EvalEnd]="/ev",s[k.ControlCommand.CommandType.Duplicate]="du",s[k.ControlCommand.CommandType.PopEvaluatedValue]="pop",s[k.ControlCommand.CommandType.PopFunction]="~ret",s[k.ControlCommand.CommandType.PopTunnel]="->->",s[k.ControlCommand.CommandType.BeginString]="str",s[k.ControlCommand.CommandType.EndString]="/str",s[k.ControlCommand.CommandType.NoOp]="nop",s[k.ControlCommand.CommandType.ChoiceCount]="choiceCnt",s[k.ControlCommand.CommandType.Turns]="turn",s[k.ControlCommand.CommandType.TurnsSince]="turns",s[k.ControlCommand.CommandType.ReadCount]="readc",s[k.ControlCommand.CommandType.Random]="rnd",s[k.ControlCommand.CommandType.SeedRandom]="srnd",s[k.ControlCommand.CommandType.VisitIndex]="visit",s[k.ControlCommand.CommandType.SequenceShuffleIndex]="seq",s[k.ControlCommand.CommandType.StartThread]="thread",s[k.ControlCommand.CommandType.Done]="done",s[k.ControlCommand.CommandType.End]="end",s[k.ControlCommand.CommandType.ListFromInt]="listInt",s[k.ControlCommand.CommandType.ListRange]="range",s[k.ControlCommand.CommandType.ListRandom]="lrnd",s[k.ControlCommand.CommandType.BeginTag]="#",s[k.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<k.ControlCommand.CommandType.TOTAL_VALUES;++e)if(s[e]==null)throw new Error("Control command not accounted for in serialisation");return s})();});var co=C(_n=>{Object.defineProperty(_n,"__esModule",{value:true});_n.CallStack=void 0;var uo=ut(),mu=ue(),xp=En(),Cu=Dt(),Pp=B(),Op=at(),Sn=cn(),Np=Yt(),vu=Tt(),ho=ne(),bn=class s{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){Np.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=Sn.Pointer.Null,arguments[0]instanceof xp.Story){let e=arguments[0];this._startOfRoot=Sn.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new s.Thread),this._threads[0].callstack.push(new s.Element(uo.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let i of n){let a=i,r=new s.Thread(a,t);this._threads.push(r);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=Sn.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==uo.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let i=new s.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, vu.tryGetValueFromMap)(n.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,n,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let r=(0, vu.tryGetValueFromMap)(a.temporaryVariables,e,null);r.exists&&Pp.ListValue.RetainListOriginsForAssignment(r.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new Op.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==uo.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let r=n.callstack[a].currentPointer;if(!r.isNull){if(e.Append("<SOMEWHERE IN "),r.container===null)return (0, ho.throwNullException)("pointer.container");e.Append(r.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};_n.CallStack=bn;(function(s){class e{constructor(i,a,r=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=r,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}s.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=Sn.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let r=i.callstack;for(let l of r){let u=l,h=parseInt(u.type),c=Sn.Pointer.Null,f,p=u.cPath;if(typeof p<"u"){f=p.toString();let T=a.ContentAtPath(new mu.Path(f));if(c.container=T.container,c.index=parseInt(u.idx),T.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+f+". Has the story changed since this save data was created?");T.approximate&&(c.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"', so it was approximated to '"+c.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let g=!!u.exp,y=new e(h,c,g),b=u.temp;typeof b<"u"?y.temporaryVariables=Cu.JsonSerialisation.JObjectToDictionaryRuntimeObjs(b):y.temporaryVariables.clear(),this.callstack.push(y);}let o=i.previousContentObject;if(typeof o<"u"){let l=new mu.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let i=new t;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, ho.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",a.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",a.currentPointer.index);}i.WriteProperty("exp",a.inExpressionEvaluation),i.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),Cu.JsonSerialisation.WriteDictionaryRuntimeObjs(i,a.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, ho.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}s.Thread=t;})(bn||(_n.CallStack=bn={}));});var Su=C(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.VariablesState=void 0;var ee=B(),Ap=Zt(),yu=Dt(),re=D(),Tn=Tt(),Xe=ne();function Ip(){return class{}}var jr=class s extends Ip(){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 Ap.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=ee.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,r){return a in i?i[a]=r:i.$(a,r),!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, Xe.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,n]of this._defaultGlobalVariables){let i=e[t];if(typeof i<"u"){let a=yu.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Xe.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let i=t,a=n;if(s.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let r=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,r))continue}e.WritePropertyStart(i),yu.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Xe.throwNullException)("obj1");if(t===null)return (0, Xe.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let n=(0, re.asOrNull)(e,ee.BoolValue);if(n!==null)return n.value===(0, re.asOrThrows)(t,ee.BoolValue).value;let i=(0, re.asOrNull)(e,ee.IntValue);if(i!==null)return i.value===(0, re.asOrThrows)(t,ee.IntValue).value;let a=(0, re.asOrNull)(e,ee.FloatValue);if(a!==null)return a.value===(0, re.asOrThrows)(t,ee.FloatValue).value;let r=(0, re.asOrNull)(e,ee.Value),o=(0, re.asOrNull)(t,ee.Value);if(r!==null&&o!==null)return (0, re.isEquatable)(r.valueObject)&&(0, re.isEquatable)(o.valueObject)?r.valueObject.Equals(o.valueObject):r.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let n=this.GetRawVariableWithName(e,t),i=(0, re.asOrNull)(n,ee.VariablePointerValue);return i!==null&&(n=this.ValueAtVariablePointer(i)),n}TryGetDefaultVariableValue(e){let t=(0, Tn.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, Tn.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Tn.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Xe.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, Xe.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let r=(0, re.asOrNull)(t,ee.VariablePointerValue);r!==null&&(t=this.ResolveVariablePointer(r));}else {let r=null;do r=(0, re.asOrNull)(this.GetRawVariableWithName(n,i),ee.VariablePointerValue),r!=null&&(n=r.variableName,i=r.contextIndex,a=i==0);while(r!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, re.asOrThrows)(e,ee.ListValue),i=(0, re.asOrThrows)(t,ee.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, Tn.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, Tn.tryGetValueFromMap)(this._globalVariables,e,null))),ee.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, Xe.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, Xe.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, re.asOrNull)(n,ee.VariablePointerValue);return i??new ee.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Mr.VariablesState=jr;jr.dontSaveDefaultValues=true;});var po=C(Br=>{Object.defineProperty(Br,"__esModule",{value:true});Br.PRNG=void 0;var fo=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}};Br.PRNG=fo;});var bu=C(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.StatePatch=void 0;var go=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}}};Gr.StatePatch=go;});var mo=C(xn=>{Object.defineProperty(xn,"__esModule",{value:true});xn.SimpleJson=void 0;var wn=class s{static TextToDictionary(e){return new s.Reader(e).ToDictionary()}static TextToArray(e){return new s.Reader(e).ToArray()}};xn.SimpleJson=wn;(function(s){class e{constructor(i){if(JSON.parse("0",(r,o,l)=>l!=null)){let r=(o,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(i,r);}else {let r=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(r);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}s.Reader=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===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===s.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let r=arguments[1];r(this);}else {let r=arguments[1];this.Write(r);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===s.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===s.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===s.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Property)),this._stateStack.push(new s.Writer.StateElement(s.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===s.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===s.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===s.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===s.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new s.Writer.StateElement(s.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===s.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new s.Writer.StateElement(s.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==s.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===s.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===s.Writer.State.None||this.state===s.Writer.State.Property||this.state===s.Writer.State.Array):this.Assert(this.state===s.Writer.State.Property||this.state===s.Writer.State.Array),this.state===s.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===s.Writer.State.Array||this.state===s.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:s.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===s.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===s.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}s.Writer=t,(function(n){(function(r){r[r.None=0]="None",r[r.Object=1]="Object",r[r.Array=2]="Array",r[r.Property=3]="Property",r[r.PropertyName=4]="PropertyName",r[r.String=5]="String";})(n.State||(n.State={}));class a{constructor(o){this.type=s.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;})(t=s.Writer||(s.Writer={}));})(wn||(xn.SimpleJson=wn={}));});var Eu=C(Jr=>{Object.defineProperty(Jr,"__esModule",{value:true});Jr.Flow=void 0;var _u=co(),$r=Dt(),Fp=ne(),Co=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new _u.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=$r.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=$r.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=>$r.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, Fp.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)$r.JsonSerialisation.WriteChoice(n,i);n.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let n of this.currentChoices){let i=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(i!==null)n.threadAtGeneration=i.Copy();else {let a=e[`${n.originalThreadIndex}`];n.threadAtGeneration=new _u.CallStack.Thread(a,t);}}}};Jr.Flow=Co;});var xu=C(Ur=>{Object.defineProperty(Ur,"__esModule",{value:true});Ur.StoryState=void 0;var Vp=co(),kp=Su(),Y=B(),Ye=ut(),Rp=Vr(),vo=Er(),Tu=ue(),oe=ie(),yo=at(),Qe=Dt(),Dp=po(),Lp=lt(),Lt=cn(),Pn=Tt(),K=D(),Wp=Yt(),Te=ne(),qp=En(),jp=bu(),wu=mo(),Hr=Eu(),Mp=de(),So=class s{ToJson(e=false){let t=new wu.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=wu.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let n=this.story.ContentAtPath(new Tu.Path(e)).container;if(n===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(n,0),t.exists)return t.result}return t=(0, Pn.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, Te.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, Pn.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, Pn.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, Pn.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, Te.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, Te.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 yo.StringBuilder,t=false;for(let n of this.outputStream){let i=(0, K.asOrNull)(n,Y.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, K.asOrNull)(n,oe.ControlCommand);a!==null&&(a.commandType==oe.ControlCommand.CommandType.BeginTag?t=true:a.commandType==oe.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new yo.StringBuilder,n=-1,i=0;for(let a=0;a<e.length;a++){let r=e.charAt(a),o=r==" "||r==" ";o&&n==-1&&(n=a),o||(r!=`
21
21
  `&&n>0&&n!=i&&t.Append(" "),n=-1),r==`
22
- `&&(i=a+1),o||t.Append(r);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new mo.StringBuilder;for(let n of this.outputStream){let i=(0, U.asOrNull)(n,ae.ControlCommand);if(i!=null){if(i.commandType==ae.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==ae.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, U.asOrNull)(n,X.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, U.asOrNull)(n,Fp.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=Rt.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 $r.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new Ip.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new Vp.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Rt.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, wn.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new $r.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, Ee.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new s(this.story);if(t._patch=new Lp.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new Ap.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=>Xe.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, Ee.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Xe.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Xe.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",Dp.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 r=i;Object.keys(r).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(r);for(let[l,u]of o){let h=l,c=u,f=new $r.Flow(h,this.story,c);if(Object.keys(r).length===1)this._currentFlow=new $r.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, Ee.throwNullException)("this._namedFlows");this._namedFlows.set(h,f);}}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=Xe.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Xe.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let r=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(r,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Xe.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let r=new _u.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(r);}this._visitCounts=Xe.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Xe.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, U.asOrNull)(e,X.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, Ee.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(r);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new yo.StringBuilder;for(let n of this.outputStream){let i=(0, K.asOrNull)(n,oe.ControlCommand);if(i!=null){if(i.commandType==oe.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==oe.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, K.asOrNull)(n,Y.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, K.asOrNull)(n,Rp.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=Lt.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 Hr.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new kp.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new Dp.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Lt.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, Pn.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new Hr.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, Te.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new s(this.story);if(t._patch=new jp.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new Vp.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=>Qe.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, Te.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Qe.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Qe.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",qp.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 r=i;Object.keys(r).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(r);for(let[l,u]of o){let h=l,c=u,f=new Hr.Flow(h,this.story,c);if(Object.keys(r).length===1)this._currentFlow=new Hr.Flow(h,this.story,c);else {if(this._namedFlows===null)return (0, Te.throwNullException)("this._namedFlows");this._namedFlows.set(h,f);}}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=Qe.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Qe.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let r=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(r,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Qe.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let r=new Tu.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(r);}this._visitCounts=Qe.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Qe.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, K.asOrNull)(e,Y.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, Te.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,r=-1;for(let h=t.length-1;h>=0;h--){let c=t[h];if(c==`
24
- `)a==-1&&(a=h),r=h;else {if(c==" "||c==" ")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=t.length;if(n!=-1){if(n>0){let h=new X.StringValue(t.substring(0,n));o.push(h);}o.push(new X.StringValue(`
25
- `)),l=i+1;}if(a!=-1&&(u=r),u>l){let h=t.substring(l,u);o.push(new X.StringValue(h));}if(a!=-1&&r>i&&(o.push(new X.StringValue(`
26
- `)),a<t.length-1)){let h=t.length-a-1,c=new X.StringValue(t.substring(a+1,a+1+h));o.push(c);}return o}PushToOutputStreamIndividual(e){let t=(0, U.asOrNull)(e,go.Glue),n=(0, U.asOrNull)(e,X.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let a=-1,r=this.callStack.currentElement;r.type==ze.PushPopType.Function&&(a=r.functionStartInOutputStream);let o=-1;for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u],c=h instanceof ae.ControlCommand?h:null;if((h instanceof go.Glue?h:null)!=null){o=u;break}else if(c!=null&&c.commandType==ae.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==ze.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, Ee.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let n=this.outputStream[t],i=(0, U.asOrNull)(n,ae.ControlCommand),a=(0, U.asOrNull)(n,X.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, U.asOrNull)(this.outputStream[t],X.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 go.Glue)this.outputStream.splice(e,1);else if(t instanceof ae.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof ae.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof X.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof X.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, U.asOrNull)(this.outputStream[e],ae.ControlCommand);if(t instanceof ae.ControlCommand&&t.commandType==ae.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, U.asOrNull)(e,X.ListValue);if(t){let n=t.value;if(n===null)return (0, Ee.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, Ee.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, Ee.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, Ee.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, U.nullIfUndefined)(t)}else {if(e>this.evaluationStack.length)throw new Error("trying to pop too many objects");let t=this.evaluationStack.splice(this.evaluationStack.length-e,e);return (0, U.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Rt.Pointer.Null,this.previousPointer=Rt.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){Rp.Debug.Assert(this.callStack.currentElement.type==ze.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let n=this.outputStream[t],i=(0, U.asOrNull)(n,X.StringValue),a=(0, U.asOrNull)(n,ae.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==ze.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(ze.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Rt.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 Wp.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, U.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(X.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==ze.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Rt.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=ze.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(ze.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof kp.Void)return null;let n=(0, U.asOrThrows)(t,X.Value);return n.valueType==X.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;}};Jr.StoryState=Co;});var wu=C(Hr=>{Object.defineProperty(Hr,"__esModule",{value:true});Hr.Stopwatch=void 0;var vo=class{constructor(){this.startTime=void 0;}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime();}Stop(){this.startTime=void 0;}};Hr.Stopwatch=vo;});var Pu=C(Ur=>{Object.defineProperty(Ur,"__esModule",{value:true});Ur.ErrorType=void 0;var xu;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(xu||(Ur.ErrorType=xu={}));});var bn=C(pt=>{Object.defineProperty(pt,"__esModule",{value:true});pt.Story=pt.InkList=void 0;var re=J(),yo=ue(),So=kt(),qp=Tu(),O=ne(),Te=ot(),jp=pi(),Mp=to(),Ou=Fe(),w=M(),bo=le(),xn=at(),Kr=Ir(),Bp=Je(),Gp=It(),$p=Ie(),dt=Yt(),_o=ho(),ft=rt(),Jp=io(),Hp=wu(),Ye=un(),Pn=ce(),N=R(),k=te(),Nu=fo(),Au=Pu(),Up=ce();Object.defineProperty(pt,"InkList",{enumerable:true,get:function(){return Up.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var Dt=class s extends yo.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, k.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 re.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=Nu.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new Jp.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let i=n,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let r=parseInt(a);if(r>s.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(r<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");r!=s.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${s.inkVersionCurrent} used to build story doesn't match current version of engine (${r}). Non-critical, but recommend synchronising.`);let 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=So.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, N.asOrThrows)(So.JsonSerialisation.JTokenToRuntimeObject(o),re.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new Nu.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",s.inkVersionCurrent),e.WriteProperty("root",n=>So.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[i,a]of n.items){let r=Pn.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(r.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new qp.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, k.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, k.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new bo.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 Hp.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(r){if(!(r instanceof dt.StoryException))throw r;this.AddError(r.message,void 0,r.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(Te.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(Te.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 r of this.state.currentErrors)this.onError(r,Au.ErrorType.Error);if(this.state.hasWarning)for(let r of this.state.currentWarnings)this.onError(r,Au.ErrorType.Warning);this.ResetErrors();}else {let r=new ft.StringBuilder;throw r.Append("Ink had "),this.state.hasError&&(r.Append(`${this.state.currentErrors.length}`),r.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&r.Append(" and ")),this.state.hasWarning&&(r.Append(`${this.state.currentWarnings.length}`),r.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&r.Append(" and ")),r.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),r.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new dt.StoryException(r.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, k.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, k.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==s.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==s.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(e,t,n,i){if(e===null)return (0, k.throwNullException)("prevText");if(t===null)return (0, k.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 s.OutputStateChange.NoChange;if(!a)return s.OutputStateChange.NewlineRemoved;if(i>n)return s.OutputStateChange.ExtendedBeyondNewline;for(let r=e.length;r<t.length;r++){let o=t.charAt(r);if(o!=" "&&o!=" ")return s.OutputStateChange.ExtendedBeyondNewline}return s.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new ft.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 re.Container?t:null}PointerAtPath(e){if(e.length==0)return Ye.Pointer.Null;let t=new Ye.Pointer,n=e.length,i=null;return e.lastComponent===null?(0, k.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, k.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, N.asOrNull)(t.Resolve(),re.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)t=Ye.Pointer.StartOf(n),n=(0, N.asOrNull)(t.Resolve(),re.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 r=(0, N.asOrNull)(i,jp.ChoicePoint);if(r){let l=this.ProcessChoice(r);l&&this.state.generatedChoices.push(l),i=null,e=false;}if(i instanceof re.Container&&(e=false),e){let l=(0, N.asOrNull)(i,w.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);i=new w.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, N.asOrNull)(i,O.ControlCommand);o&&o.commandType==O.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let r=e.Resolve(),o=(0, N.asOrNull)(r,re.Container)||(0, N.asOrNull)(e.container,re.Container);for(;o;)this._prevContainers.push(o),o=(0, N.asOrNull)(o.parent,re.Container);}let n=t.Resolve();if(n==null)return;let i=(0, N.asOrNull)(n.parent,re.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let r=i.content.length>0&&n==i.content[0]&&a;r||(a=false),this.VisitContainer(i,r),n=i,i=(0, N.asOrNull)(i.parent,re.Container);}}PopChoiceStringAndTags(e){let t=(0, N.asOrThrows)(this.state.PopEvaluationStack(),w.StringValue);for(;this.state.evaluationStack.length>0&&(0, N.asOrNull)(this.state.PeekEvaluationStack(),Kr.Tag)!=null;){let n=(0, N.asOrNull)(this.state.PopEvaluationStack(),Kr.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 r=new Mp.Choice;return r.targetPath=e.pathOnChoice,r.sourcePath=e.path.toString(),r.isInvisibleDefault=e.isInvisibleDefault,r.threadAtGeneration=this.state.callStack.ForkThread(),r.tags=a.reverse(),r.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),r}IsTruthy(e){let t=false;if(e instanceof w.Value){let n=e;if(n instanceof w.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 Ou.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 w.DivertTargetValue)){let r=(0, N.asOrNull)(i,w.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";r instanceof w.IntValue&&r.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, N.asOrThrows)(i,w.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 O.ControlCommand){let t=e;switch(t.commandType){case O.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case O.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case O.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let g=this.state.PopEvaluationStack();if(!(g instanceof xn.Void)){let E=new w.StringValue(g.toString());this.state.PushToOutputStream(E);}}break;case O.ControlCommand.CommandType.NoOp:break;case O.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case O.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case O.ControlCommand.CommandType.PopFunction:case O.ControlCommand.CommandType.PopTunnel:let n=t.commandType==O.ControlCommand.CommandType.PopFunction?Te.PushPopType.Function:Te.PushPopType.Tunnel,i=null;if(n==Te.PushPopType.Tunnel){let g=this.state.PopEvaluationStack();i=(0, N.asOrNull)(g,w.DivertTargetValue),i===null&&this.Assert(g instanceof xn.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let g=new Map;g.set(Te.PushPopType.Function,"function return statement (~ return)"),g.set(Te.PushPopType.Tunnel,"tunnel onwards statement (->->)");let E=g.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(E="end of flow (-> END or choice)");let I="Found "+g.get(n)+", when expected "+E;this.Error(I);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case O.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(t),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case O.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case O.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let g=[],E=0;for(let D=this.state.outputStream.length-1;D>=0;--D){let G=this.state.outputStream[D];E++;let me=(0, N.asOrNull)(G,O.ControlCommand);if(me!=null){if(me.commandType==O.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}G instanceof w.StringValue&&g.push(G);}this.state.PopFromOutputStream(E);let I=new ft.StringBuilder;for(let D of g.reverse())I.Append(D.toString());let ge=new Kr.Tag(this.state.CleanOutputWhitespace(I.toString()));this.state.PushEvaluationStack(ge);}else this.state.PushToOutputStream(t);break}case O.ControlCommand.CommandType.EndString:{let g=[],E=[],I=0;for(let D=this.state.outputStream.length-1;D>=0;--D){let G=this.state.outputStream[D];I++;let me=(0, N.asOrNull)(G,O.ControlCommand);if(me&&me.commandType==O.ControlCommand.CommandType.BeginString)break;G instanceof Kr.Tag&&E.push(G),G instanceof w.StringValue&&g.push(G);}this.state.PopFromOutputStream(I);for(let D of E)this.state.PushToOutputStream(D);g=g.reverse();let ge=new ft.StringBuilder;for(let D of g)ge.Append(D.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new w.StringValue(ge.toString()));break}case O.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new w.IntValue(a));break;case O.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new w.IntValue(this.state.currentTurnIndex+1));break;case O.ControlCommand.CommandType.TurnsSince:case O.ControlCommand.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof w.DivertTargetValue)){let g="";r instanceof w.IntValue&&(g=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+r+g);break}let o=(0, N.asOrThrows)(r,w.DivertTargetValue),l=(0, N.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,re.Container),u;l!=null?t.commandType==O.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(t.commandType==O.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new w.IntValue(u));break;case O.ControlCommand.CommandType.Random:{let g=(0, N.asOrNull)(this.state.PopEvaluationStack(),w.IntValue),E=(0, N.asOrNull)(this.state.PopEvaluationStack(),w.IntValue);if(E==null||!(E instanceof w.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(g==null||!(g instanceof w.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(g.value===null)return (0, k.throwNullException)("maxInt.value");if(E.value===null)return (0, k.throwNullException)("minInt.value");let I=g.value-E.value+1;(!isFinite(I)||I>Number.MAX_SAFE_INTEGER)&&(I=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),I<=0&&this.Error("RANDOM was called with minimum as "+E.value+" and maximum as "+g.value+". The maximum must be larger");let ge=this.state.storySeed+this.state.previousRandom,G=new _o.PRNG(ge).next(),me=G%I+E.value;this.state.PushEvaluationStack(new w.IntValue(me)),this.state.previousRandom=G;break}case O.ControlCommand.CommandType.SeedRandom:let h=(0, N.asOrNull)(this.state.PopEvaluationStack(),w.IntValue);if(h==null||!(h instanceof w.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, k.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new xn.Void);break;case O.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new w.IntValue(c));break;case O.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new w.IntValue(f));break;case O.ControlCommand.CommandType.StartThread:break;case O.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Ye.Pointer.Null);break;case O.ControlCommand.CommandType.End:this.state.ForceEnd();break;case O.ControlCommand.CommandType.ListFromInt:let p=(0, N.asOrNull)(this.state.PopEvaluationStack(),w.IntValue),m=(0, N.asOrThrows)(this.state.PopEvaluationStack(),w.StringValue);if(p===null)throw new dt.StoryException("Passed non-integer when creating a list element from a numerical value.");let y=null;if(this.listDefinitions===null)return (0, k.throwNullException)("this.listDefinitions");let b=this.listDefinitions.TryListGetDefinition(m.value,null);if(b.exists){if(p.value===null)return (0, k.throwNullException)("minInt.value");let g=b.result.TryGetItemWithValue(p.value,Pn.InkListItem.Null);g.exists&&(y=new w.ListValue(g.result,p.value));}else throw new dt.StoryException("Failed to find LIST called "+m.value);y==null&&(y=new w.ListValue),this.state.PushEvaluationStack(y);break;case O.ControlCommand.CommandType.ListRange:let _=(0, N.asOrNull)(this.state.PopEvaluationStack(),w.Value),d=(0, N.asOrNull)(this.state.PopEvaluationStack(),w.Value),S=(0, N.asOrNull)(this.state.PopEvaluationStack(),w.ListValue);if(S===null||d===null||_===null)throw new dt.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(S.value===null)return (0, k.throwNullException)("targetList.value");let v=S.value.ListWithSubRange(d.valueObject,_.valueObject);this.state.PushEvaluationStack(new w.ListValue(v));break;case O.ControlCommand.CommandType.ListRandom:{let g=this.state.PopEvaluationStack();if(g===null)throw new dt.StoryException("Expected list for LIST_RANDOM");let E=g.value,I=null;if(E===null)throw (0, k.throwNullException)("list");if(E.Count==0)I=new Pn.InkList;else {let ge=this.state.storySeed+this.state.previousRandom,G=new _o.PRNG(ge).next(),me=G%E.Count,mt=E.entries();for(let $o=0;$o<=me-1;$o++)mt.next();let Go=mt.next().value,kn={Key:Pn.InkListItem.fromSerializedKey(Go[0]),Value:Go[1]};if(kn.Key.originName===null)return (0, k.throwNullException)("randomItem.Key.originName");I=new Pn.InkList(kn.Key.originName,this),I.Add(kn.Key,kn.Value),this.state.previousRandom=G;}this.state.PushEvaluationStack(new w.ListValue(I));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof Bp.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),true}else if(e instanceof Gp.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);n=new w.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 w.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(e instanceof $p.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==Te.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 bo.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, k.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, k.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 r=new ft.StringBuilder;for(;this.canContinue;)r.Append(this.Continue());let o=r.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(Te.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, k.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(Te.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Ye.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let r=[];for(let u=0;u<t;++u){let c=(0, N.asOrThrows)(this.state.PopEvaluationStack(),w.Value).valueObject;r.push(c);}r.reverse();let o=n.function(r),l=null;o!=null?(l=w.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new xn.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 r=0,o=i.length;r<o;r++)a[r]=this.TryCoerce(i[r]);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 re.Container&&(e=arguments[0]),arguments[0]instanceof yo.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, N.asOrNull)(i,yo.InkObject),n);}else if(t!=null){let i=(0, N.asOrNull)(t,Ou.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, k.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 w.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, N.asOrThrows)(t,w.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 bo.Path(e),n=this.ContentAtPath(t).container;if(n===null)return (0, k.throwNullException)("flowContainer");for(;;){let r=n.content[0];if(r instanceof re.Container)n=r;else break}let i=false,a=null;for(let r of n.content){let o=(0, N.asOrNull)(r,O.ControlCommand);if(o!=null)o.commandType==O.ControlCommand.CommandType.BeginTag?i=true:o.commandType==O.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let l=(0, N.asOrNull)(r,w.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 ft.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new ft.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=Ye.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(Te.PushPopType.Function)?(this.state.PopCallStack(Te.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new xn.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, k.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let n=(0, N.asOrNull)(t.container.parent,re.Container);if(!(n instanceof re.Container))break;let i=n.content.indexOf(t.container);if(i==-1)break;if(t=new Ye.Pointer(n,i),t.index++,e=true,t.container===null)return (0, k.throwNullException)("pointer.container")}return e||(t=Ye.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, k.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, k.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, N.asOrNull)(this.state.PopEvaluationStack(),w.IntValue);if(!(e instanceof w.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, k.throwNullException)("seqContainer");if(e.value===null)return (0, k.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, N.asOrThrows)(this.state.PopEvaluationStack(),w.IntValue).value;if(a===null)return (0, k.throwNullException)("seqCount");let r=a/n,o=a%n,l=t.path.toString(),u=0;for(let p=0,m=l.length;p<m;p++)u+=l.charCodeAt(p)||0;let h=u+r+this.state.storySeed,c=new _o.PRNG(Math.floor(h)),f=[];for(let p=0;p<n;++p)f.push(p);for(let p=0;p<=o;++p){let m=c.next()%f.length,y=f[m];if(f.splice(m,1),p==o)return y}throw new Error("Should never reach here")}Error(e,t=false){let n=new dt.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 r=n?i.endLineNumber:i.startLineNumber;e="RUNTIME "+a+": '"+i.fileName+"' line "+r+": "+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}};pt.Story=Dt;Dt.inkVersionCurrent=21;(function(s){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(s.OutputStateChange||(s.OutputStateChange={}));})(Dt||(pt.Story=Dt={}));});var Fu=C(Zr=>{Object.defineProperty(Zr,"__esModule",{value:true});Zr.Story=void 0;var Kp=Hn(),zp=Ii(),zr=J(),Xr=ne(),On=Bn(),Yr=Ve(),Iu=Pt(),Xp=Ga(),Yp=or(),Qp=za(),Zp=bn(),Lt=je(),eg=Ue(),tg=Je(),Nn=R(),ng=dn(),ig=fn(),rg=ut(),Qr=class s extends Yr.FlowBase{get flowLevel(){return Iu.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(zp.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let f=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(f,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(Yp.ListDefinition)())!((i=h.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=h.identifier)===null||a===void 0?void 0:a.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let r=this.runtimeObject,o=new zr.Container;o.AddContent(Xr.ControlCommand.EvalStart());let l=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),o.AddContent(c.listDefinition.runtimeObject),l.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(o);}let f=new tg.VariableAssignment(h,true);f.isGlobal=true,o.AddContent(f);}o.AddContent(Xr.ControlCommand.EvalEnd()),o.AddContent(Xr.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",r.AddToNamedContentOnly(o)),r.AddContent(Xr.ControlCommand.Done());let u=new Zp.Story(r,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(r),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,a=null)=>{let r=null;if(n)return (r=this._listDefs.get(n))?r.ItemNamed(i):null;{let o=null,l=null;for(let[,u]of this._listDefs.entries()){let h=u.ItemNamed(i);h&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,false):(o=h,l=u));}return o}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let a of n.content){let r=(0, Nn.asOrNull)(a,zr.Container);r&&i.add(r);}if(n.namedContent)for(let[,a]of n.namedContent){let r=(0, Nn.asOrNull)(a,zr.Container);r&&i.add(r);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let i=(0, Nn.asOrNull)(n.parent,zr.Container);if(i){let a=i.content.indexOf(n);i.content.splice(a,1);let r=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,r!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=r),i.InsertContent(o,a),a+=1;}},this.Error=(n,i,a)=>{let r=a?On.ErrorType.Warning:On.ErrorType.Error,o="";if(i instanceof Kp.AuthorWarning?(o+="TODO: ",r=On.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(o+=`'${i.debugMetadata.fileName}' `),o+=`line ${i.debugMetadata.startLineNumber}: `),o+=n,n=o,this._errorHandler!==null)this._errorHandler(n,r);else throw new Error(n);this._hadError=r===On.ErrorType.Error,this._hadWarning=r===On.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,r)=>{n.Error(`${r} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,i,a,r="")=>{var o;let l=r||n.typeName;if(s.IsReservedKeyword(i?.name)){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(ig.FunctionCall.IsBuiltIn(i?.name||"")){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(i?.name||"",Iu.FlowLevel.Knot),h=(0, Nn.asOrNull)(u,Yr.FlowBase);if(h&&(h!==n||a===Lt.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,l);return}if(a<Lt.SymbolType.List)return;for(let[m,y]of this._listDefs)if(i?.name===m&&n!==y&&y.variableAssignment!==n&&this.NameConflictError(n,i?.name,y,l),!(n instanceof Qp.ListElementDefinition))for(let b of y.itemDefinitions)i?.name===b.name&&this.NameConflictError(n,i?.name||"",b,l);if(a<=Lt.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<Lt.SymbolType.SubFlowAndWeave)return;let p=new rg.Path(i).ResolveFromContext(n);if(p&&p!==n){this.NameConflictError(n,i?.name||"",p,l);return}if(!(a<Lt.SymbolType.Arg)&&a!==Lt.SymbolType.Arg){let m=(0, Nn.asOrNull)(n,Yr.FlowBase);if(m||(m=(0, ng.ClosestFlowBase)(n)),m&&m.hasParameters&&m.args){for(let y of m.args)if(((o=y.identifier)===null||o===void 0?void 0:o.name)===i?.name){n.Error(`${l} '${i}': name has already been used for a argument to ${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 Xp.IncludedFile){let i=n,a=e.indexOf(n);if(e.splice(a,1),i.includedStory){let r=[],o=i.includedStory;if(o.content!=null){for(let l of o.content)l instanceof Yr.FlowBase?t.push(l):r.push(l);r.push(new eg.Text(`
29
- `)),e.splice(a,0,...r);}}continue}e.splice(0,0,...t);}};Zr.Story=Qr;Qr.IsReservedKeyword=s=>{switch(s){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var ku=C(es=>{Object.defineProperty(es,"__esModule",{value:true});es.StringExpression=void 0;var Vu=ne(),sg=ye(),ag=Ue(),og=R(),Eo=class s extends sg.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof ag.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(Vu.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(Vu.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, og.asOrNull)(e,s);if(t===null||!this.isSingleString||!t.isSingleString)return false;let n=this.toString(),i=t.toString();return n===i}};es.StringExpression=Eo;});var Du=C(Wt=>{Object.defineProperty(Wt,"__esModule",{value:true});Wt.LegacyTag=Wt.Tag=void 0;var lg=j(),Ru=ne(),To=class extends lg.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?Ru.ControlCommand.BeginTag():Ru.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};Wt.Tag=To;var ug=Wa(),wo=class extends ug.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};Wt.LegacyTag=wo;});var Lu=C(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.DefaultFileHandler=void 0;var xo=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.")};}};ts.DefaultFileHandler=xo;});var Ao=C(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.InkParser=void 0;var hg=al(),cg=Hn(),dg=Vs(),xe=yl(),Q=on(),fg=xt(),pg=Ol(),gg=Oi(),An=fa(),pe=Bi(),mg=Ii(),ns=Xl(),Cg=Yl(),gt=At(),Po=Nt(),vg=ye(),yg=Ql(),Wu=Zl(),is=fn(),Sg=cn(),bg=eu(),_g=br(),rs=nu(),qu=Ga(),Eg=iu(),Tg=Ha(),ju=su(),wg=or(),xg=za(),Pg=ua(),Mu=j(),Og=ut(),Bu=ea(),Gu=_a(),Y=ya(),oe=Xa(),Ng=Qa(),$u=Fu(),In=ku(),Me=$s(),qt=Du(),Be=Ue(),Ju=Ta(),Oo=Aa(),No=Ft(),Ag=Is(),Qe=R(),Fn=qi(),jt=li(),Hu=Bn(),Ig=Lu(),L=class s extends Me.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,n=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let r=this.StatementsAtLevel(oe.StatementLevel.Top);return new $u.Story(r,this._rootParser!==this)},this.SeparatedList=(r,o)=>{let l=this.Parse(r);if(l===null)return null;let u=[];u.push(l);do{let h=this.BeginRule();if(o()===null){this.FailRule(h);break}let f=this.Parse(r);if(f===null){this.FailRule(h);break}this.SucceedRule(h),u.push(f);}while(true);return u},this.CreateDebugMetadata=(r,o)=>{let l=new Cg.DebugMetadata;return l.startLineNumber=(r?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(r?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(r,o,l)=>{let u=(0, Qe.asOrNull)(r,Mu.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let h=Array.isArray(r)?r:null;if(h!==null)for(let f of h)(0, Qe.asOrNull)(f,Mu.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,l)));let c=(0, Qe.asOrNull)(r,Fn.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(r,o,l=0,u=false)=>{let c=u?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${l+1}: ${r}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,u?Hu.ErrorType.Warning:Hu.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
30
- \r`);return o?new cg.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=r=>{let o=s.ListAllCharacterRanges();for(let l of o)r.AddCharacters(l.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let r=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;r=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 pe.ContentList(c));let f=null,p=null,m=this.ParseString("[")!==null;if(m){this.EndTagIfNecessary(h);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(f=new pe.ContentList(d)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let S=this.Parse(this.MixedTextAndLogic);S!==null&&(p=new pe.ContentList(S));}this.Whitespace(),this.EndTagIfNecessary(p??h);let y=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let b=!h&&!p&&!f;if(b&&y===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&m&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),p||(p=new pe.ContentList),this.EndTagIfNecessary(p),y!==null)for(let d of y){let S=(0, Qe.asOrNull)(d,gt.Divert);S&&S.isEmpty||p.AddContent(d);}p.AddContent(new Be.Text(`
31
- `));let _=new fg.Choice(h,f,p);return l&&(_.identifier=l),_.indentationDepth=o.length,_.hasWeaveStyleInlineBrackets=m,_.condition=u,_.onceOnly=r,_.isInvisibleDefault=b,_},this.ChoiceCondition=()=>{let r=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return r===null?null:r.length===1?r[0]:new Pg.MultipleConditionExpression(r)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Me.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let r=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(r),this.Expect(this.String("}"),"closing '}' for choice condition"),r},this.Gather=()=>{let r=this.Parse(this.GatherDashes);if(r===null)return null;let o=Number(r),l=this.Parse(this.BracketedName),u=new Sg.Gather(l,o);return this.Newline(),u},this.GatherDashes=()=>{this.Whitespace();let r=0;for(;this.ParseDashNotArrow()!==null;)r+=1,this.Whitespace();return r===0?null:r},this.ParseDashNotArrow=()=>{let r=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(r):this.FailRule(r)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),r)},this.InnerConditionalContent=r=>{if(r===void 0){let c=this.Parse(this.ConditionExpression),f=this.Parse(()=>this.InnerConditionalContent(c));return f===null?null:f}let o,l=r!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(r){let c=this.StatementsAtLevel(oe.StatementLevel.InnerBlock);if(c!==null){o=[new An.ConditionalSingleBranch(c)];let p=this.Parse(this.SingleMultilineCondition);p&&(p.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",p),p.isElse=true),o.push(p));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&r){let c=new An.ConditionalSingleBranch(null);c.isTrueBranch=true,o.unshift(c);}if(r){let c=false;for(let f=0;f<o.length;++f){let p=o[f],m=f===o.length-1;p.ownExpression?(p.matchingEquality=true,c=true):c&&m?(p.matchingEquality=true,p.isElse=true):!m&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",p):f===0?p.isTrueBranch=true:p.isElse=true;}}else {for(let c=0;c<o.length;++c){let f=o[c],p=c===o.length-1;if(f.ownExpression===null)if(p)f.isElse=true;else if(f.isElse){let 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",f);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",f);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let c of o)c.isInline=u;return new gg.Conditional(r,o)},this.InlineConditionalBranches=()=>{let r=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(r===null||r.length===0)return null;let o=[];if(r.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let l=new An.ConditionalSingleBranch(r[0]);if(l.isTrueBranch=true,o.push(l),r.length>1){let u=new An.ConditionalSingleBranch(r[1]);u.isElse=true,o.push(u);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineCondition);return r===null?null:(this.MultilineWhitespace(),r)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=null,o=this.Parse(this.ElseExpression)!==null;o||(r=this.Parse(this.ConditionExpression));let l=this.StatementsAtLevel(oe.StatementLevel.InnerBlock);r===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new Be.Text("")]),this.MultilineWhitespace();let u=new An.ConditionalSingleBranch(l);return u.ownExpression=r,u.isElse=o,u},this.ConditionExpression=()=>{let r=this.Parse(this.Expression);return r===null||(this.DisallowIncrement(r),this.Whitespace(),this.ParseString(":")===null)?null:r},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:Me.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(r,o)=>{if(r.length>0){let l=r.length-1,u=r[l];if(u instanceof Be.Text){let h=u;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),o?h.text+=" ":h.text.length===0&&(r.splice(l,1),this.TrimEndWhitespace(r,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let r=this.Parse(this.MixedTextAndLogic);if(!r||!r.length)return null;let o=r[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),r.length===0?null:(r[r.length-1]instanceof gt.Divert||this.TrimEndWhitespace(r,false),this.EndTagIfNecessary(r),r.length>0&&r[0]instanceof qt.Tag&&r[0].isStart||r.push(new Be.Text(`
32
- `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),r)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let 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 r=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(r===null&&(r=""),o!==null&&(r+=String(o)),l){let u=this.ParseSingleCharacter();r+=u;}}else break}while(true);return r!==null?new Be.Text(r):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new Q.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new Q.CharacterSet(`{}|
33
- \r\\#`),this._notTextEndCharactersChoice=new Q.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new Q.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let r=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let l=this.ParseUntil(r,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let r=[],o=this.Parse(this.StartThread);if(o)return r=[o],r;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;r=[],this.EndTagIfNecessary(r);for(let u=0;u<l.length;++u)if(u%2===0){if(l[u]==="->->"){u===0||u===l.length-1||u===l.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let f=new Ju.TunnelOnwards;if(u<l.length-1){let p=(0, Qe.asOrNull)(l[u+1],gt.Divert);f.divertAfter=p;}r.push(f);break}}else {let c=l[u];u<l.length-1&&(c.isTunnel=true),r.push(c);}if(r.length===0&&l.length===1){let u=new gt.Divert(null);u.isEmpty=true,r.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return r},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let r=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new gt.Divert(null));return r.isThread=true,r},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let r=this.Parse(this.DotSeparatedDivertPathComponents);if(!r)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new Og.Path(r);return new gt.Divert(l,o)},this.SingleDivert=()=>{let r=this.Parse(this.MultiDivert);if(!r||r.length!==1||r[0]instanceof Ju.TunnelOnwards)return null;let l=r[0];return l.isTunnel?null:l},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let r=0;for(;this.ParseString("->")!==null;)r+=1;return r===0?null:r===1?"->":(r===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let r=this.ParseTempKeyword();this.Whitespace();let o=null;if(r?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let l=this.ParseString("+")!==null,u=this.ParseString("-")!==null;if(l&&u&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return r&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return l||u?new rs.IncDecExpression(o,h,l):new Oo.VariableAssignment({variableIdentifier:o,assignedExpression:h,isTemporaryNewDeclaration:r})},this.DisallowIncrement=r=>{r instanceof rs.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let r=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(r),true):(this.FailRule(r),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new Bu.ReturnType(o)},this.Expression=(r=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>r){let h=`right side of '${u.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(o,u),h);if(c===null)return this.FailRule(l),null;o=this.SucceedRule(l,c);continue}this.FailRule(l);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let r=this.Parse(this.ExpressionDivertTarget);if(r!==null)return r;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&o!==null&&(l=this.ExpressionUnary()),l===null)return null;o!==null&&(l=Ag.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof No.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new rs.IncDecExpression(c.identifier,h);}}return l},this.ExpressionNot=()=>{let r=this.Identifier();return r==="not"?r:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let r=this.Parse(this.SingleDivert);return !r||r&&r.isThread?null:(this.Whitespace(),new Po.DivertTarget(r))},this.ExpressionInt=()=>{let r=this.ParseInt();return r===null?null:new jt.NumberExpression(r,"int")},this.ExpressionFloat=()=>{let r=this.ParseFloat();return r===null?null:new jt.NumberExpression(r,"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 Be.Text("")]:o.find(l=>l instanceof gt.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new In.StringExpression(o)},this.ExpressionBool=()=>{let r=this.Parse(this.Identifier);return r==="true"?new jt.NumberExpression(true,"bool"):r==="false"?new jt.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new is.FunctionCall(r,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,r);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let r=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return r===null||$u.Story.IsReservedKeyword(r[0].name)?null:new No.VariableReference(r)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let r=this.Parse(this.Expression);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),r)},this.ExpressionInfixRight=(r,o)=>{if(!r)return null;this.Whitespace();let l=this.Parse(()=>this.Expression(o.precedence));return l?new dg.BinaryExpression(r,l,o.type):null},this.ParseInfixOperator=()=>{for(let r of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(r.type)!==null){if(r.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,r)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let r=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new ju.List(r)},this.ListMember=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${r}`);r.name+=`.${l?.name}`;}return this.Whitespace(),r},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(r,o,l=false)=>{let u=new Eg.InfixOperator(r,o,l);this._binaryOperators.push(u),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,r.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let r=this.Expect(()=>this.ParseUntilCharactersFromString(`
24
+ `)a==-1&&(a=h),r=h;else {if(c==" "||c==" ")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=t.length;if(n!=-1){if(n>0){let h=new Y.StringValue(t.substring(0,n));o.push(h);}o.push(new Y.StringValue(`
25
+ `)),l=i+1;}if(a!=-1&&(u=r),u>l){let h=t.substring(l,u);o.push(new Y.StringValue(h));}if(a!=-1&&r>i&&(o.push(new Y.StringValue(`
26
+ `)),a<t.length-1)){let h=t.length-a-1,c=new Y.StringValue(t.substring(a+1,a+1+h));o.push(c);}return o}PushToOutputStreamIndividual(e){let t=(0, K.asOrNull)(e,vo.Glue),n=(0, K.asOrNull)(e,Y.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(n){let a=-1,r=this.callStack.currentElement;r.type==Ye.PushPopType.Function&&(a=r.functionStartInOutputStream);let o=-1;for(let u=this.outputStream.length-1;u>=0;u--){let h=this.outputStream[u],c=h instanceof oe.ControlCommand?h:null;if((h instanceof vo.Glue?h:null)!=null){o=u;break}else if(c!=null&&c.commandType==oe.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==Ye.PushPopType.Function)c.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, Te.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, K.asOrNull)(n,oe.ControlCommand),a=(0, K.asOrNull)(n,Y.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, K.asOrNull)(this.outputStream[t],Y.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 vo.Glue)this.outputStream.splice(e,1);else if(t instanceof oe.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof oe.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof Y.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof Y.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, K.asOrNull)(this.outputStream[e],oe.ControlCommand);if(t instanceof oe.ControlCommand&&t.commandType==oe.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, K.asOrNull)(e,Y.ListValue);if(t){let n=t.value;if(n===null)return (0, Te.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, Te.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, Te.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, Te.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, K.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, K.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Lt.Pointer.Null,this.previousPointer=Lt.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){Wp.Debug.Assert(this.callStack.currentElement.type==Ye.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, K.asOrNull)(n,Y.StringValue),a=(0, K.asOrNull)(n,oe.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==Ye.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(Ye.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Lt.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 Mp.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, K.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(Y.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Ye.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Lt.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Ye.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(Ye.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof Lp.Void)return null;let n=(0, K.asOrThrows)(t,Y.Value);return n.valueType==Y.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;}};Ur.StoryState=So;});var Pu=C(Kr=>{Object.defineProperty(Kr,"__esModule",{value:true});Kr.Stopwatch=void 0;var bo=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;}};Kr.Stopwatch=bo;});var Nu=C(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.ErrorType=void 0;var Ou;(function(s){s[s.Author=0]="Author",s[s.Warning=1]="Warning",s[s.Error=2]="Error";})(Ou||(zr.ErrorType=Ou={}));});var En=C(mt=>{Object.defineProperty(mt,"__esModule",{value:true});mt.Story=mt.InkList=void 0;var se=H(),_o=he(),Eo=Dt(),Bp=xu(),N=ie(),we=ut(),Gp=mi(),$p=ro(),Au=Ve(),w=B(),To=ue(),On=lt(),Xr=Vr(),Jp=Ue(),Hp=Vt(),Up=Fe(),pt=Zt(),wo=po(),gt=at(),Kp=ao(),zp=Pu(),Ze=cn(),Nn=de(),A=D(),R=ne(),Iu=mo(),Fu=Nu(),Xp=de();Object.defineProperty(mt,"InkList",{enumerable:true,get:function(){return Xp.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var Wt=class s extends _o.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, R.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 se.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let i=arguments[0];n=Iu.SimpleJson.TextToDictionary(i);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new Kp.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let i=n,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let r=parseInt(a);if(r>s.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(r<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");r!=s.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${s.inkVersionCurrent} used to build story doesn't match current version of engine (${r}). Non-critical, but recommend synchronising.`);let 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=Eo.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, A.asOrThrows)(Eo.JsonSerialisation.JTokenToRuntimeObject(o),se.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new Iu.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",s.inkVersionCurrent),e.WriteProperty("root",n=>Eo.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[i,a]of n.items){let r=Nn.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(r.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new Bp.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, R.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, R.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new To.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 zp.Stopwatch;n.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(r){if(!(r instanceof pt.StoryException))throw r;this.AddError(r.message,void 0,r.useEndLineNumber);break}if(i||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(we.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(we.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 r of this.state.currentErrors)this.onError(r,Fu.ErrorType.Error);if(this.state.hasWarning)for(let r of this.state.currentWarnings)this.onError(r,Fu.ErrorType.Warning);this.ResetErrors();}else {let r=new gt.StringBuilder;throw r.Append("Ink had "),this.state.hasError&&(r.Append(`${this.state.currentErrors.length}`),r.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&r.Append(" and ")),this.state.hasWarning&&(r.Append(`${this.state.currentWarnings.length}`),r.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&r.Append(" and ")),r.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),r.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new pt.StoryException(r.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, R.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, R.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==s.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==s.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(e,t,n,i){if(e===null)return (0, R.throwNullException)("prevText");if(t===null)return (0, R.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 s.OutputStateChange.NoChange;if(!a)return s.OutputStateChange.NewlineRemoved;if(i>n)return s.OutputStateChange.ExtendedBeyondNewline;for(let r=e.length;r<t.length;r++){let o=t.charAt(r);if(o!=" "&&o!=" ")return s.OutputStateChange.ExtendedBeyondNewline}return s.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new gt.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 se.Container?t:null}PointerAtPath(e){if(e.length==0)return Ze.Pointer.Null;let t=new Ze.Pointer,n=e.length,i=null;return e.lastComponent===null?(0, R.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, R.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, A.asOrNull)(t.Resolve(),se.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)t=Ze.Pointer.StartOf(n),n=(0, A.asOrNull)(t.Resolve(),se.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 r=(0, A.asOrNull)(i,Gp.ChoicePoint);if(r){let l=this.ProcessChoice(r);l&&this.state.generatedChoices.push(l),i=null,e=false;}if(i instanceof se.Container&&(e=false),e){let l=(0, A.asOrNull)(i,w.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);i=new w.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, A.asOrNull)(i,N.ControlCommand);o&&o.commandType==N.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let r=e.Resolve(),o=(0, A.asOrNull)(r,se.Container)||(0, A.asOrNull)(e.container,se.Container);for(;o;)this._prevContainers.push(o),o=(0, A.asOrNull)(o.parent,se.Container);}let n=t.Resolve();if(n==null)return;let i=(0, A.asOrNull)(n.parent,se.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let r=i.content.length>0&&n==i.content[0]&&a;r||(a=false),this.VisitContainer(i,r),n=i,i=(0, A.asOrNull)(i.parent,se.Container);}}PopChoiceStringAndTags(e){let t=(0, A.asOrThrows)(this.state.PopEvaluationStack(),w.StringValue);for(;this.state.evaluationStack.length>0&&(0, A.asOrNull)(this.state.PeekEvaluationStack(),Xr.Tag)!=null;){let n=(0, A.asOrNull)(this.state.PopEvaluationStack(),Xr.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 r=new $p.Choice;return r.targetPath=e.pathOnChoice,r.sourcePath=e.path.toString(),r.isInvisibleDefault=e.isInvisibleDefault,r.threadAtGeneration=this.state.callStack.ForkThread(),r.tags=a.reverse(),r.text=(n+i).replace(/^[ \t]+|[ \t]+$/g,""),r}IsTruthy(e){let t=false;if(e instanceof w.Value){let n=e;if(n instanceof w.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 Au.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 w.DivertTargetValue)){let r=(0, A.asOrNull)(i,w.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";r instanceof w.IntValue&&r.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, A.asOrThrows)(i,w.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 N.ControlCommand){let t=e;switch(t.commandType){case N.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case N.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case N.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let m=this.state.PopEvaluationStack();if(!(m instanceof On.Void)){let _=new w.StringValue(m.toString());this.state.PushToOutputStream(_);}}break;case N.ControlCommand.CommandType.NoOp:break;case N.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case N.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case N.ControlCommand.CommandType.PopFunction:case N.ControlCommand.CommandType.PopTunnel:let n=t.commandType==N.ControlCommand.CommandType.PopFunction?we.PushPopType.Function:we.PushPopType.Tunnel,i=null;if(n==we.PushPopType.Tunnel){let m=this.state.PopEvaluationStack();i=(0, A.asOrNull)(m,w.DivertTargetValue),i===null&&this.Assert(m instanceof On.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let m=new Map;m.set(we.PushPopType.Function,"function return statement (~ return)"),m.set(we.PushPopType.Tunnel,"tunnel onwards statement (->->)");let _=m.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(_="end of flow (-> END or choice)");let F="Found "+m.get(n)+", when expected "+_;this.Error(F);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case N.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 N.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case N.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let m=[],_=0;for(let L=this.state.outputStream.length-1;L>=0;--L){let $=this.state.outputStream[L];_++;let Ce=(0, A.asOrNull)($,N.ControlCommand);if(Ce!=null){if(Ce.commandType==N.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}$ instanceof w.StringValue&&m.push($);}this.state.PopFromOutputStream(_);let F=new gt.StringBuilder;for(let L of m.reverse())F.Append(L.toString());let me=new Xr.Tag(this.state.CleanOutputWhitespace(F.toString()));this.state.PushEvaluationStack(me);}else this.state.PushToOutputStream(t);break}case N.ControlCommand.CommandType.EndString:{let m=[],_=[],F=0;for(let L=this.state.outputStream.length-1;L>=0;--L){let $=this.state.outputStream[L];F++;let Ce=(0, A.asOrNull)($,N.ControlCommand);if(Ce&&Ce.commandType==N.ControlCommand.CommandType.BeginString)break;$ instanceof Xr.Tag&&_.push($),$ instanceof w.StringValue&&m.push($);}this.state.PopFromOutputStream(F);for(let L of _)this.state.PushToOutputStream(L);m=m.reverse();let me=new gt.StringBuilder;for(let L of m)me.Append(L.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new w.StringValue(me.toString()));break}case N.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new w.IntValue(a));break;case N.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new w.IntValue(this.state.currentTurnIndex+1));break;case N.ControlCommand.CommandType.TurnsSince:case N.ControlCommand.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof w.DivertTargetValue)){let m="";r instanceof w.IntValue&&(m=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+r+m);break}let o=(0, A.asOrThrows)(r,w.DivertTargetValue),l=(0, A.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,se.Container),u;l!=null?t.commandType==N.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(t.commandType==N.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 w.IntValue(u));break;case N.ControlCommand.CommandType.Random:{let m=(0, A.asOrNull)(this.state.PopEvaluationStack(),w.IntValue),_=(0, A.asOrNull)(this.state.PopEvaluationStack(),w.IntValue);if(_==null||!(_ instanceof w.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(m==null||!(m instanceof w.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(m.value===null)return (0, R.throwNullException)("maxInt.value");if(_.value===null)return (0, R.throwNullException)("minInt.value");let F=m.value-_.value+1;(!isFinite(F)||F>Number.MAX_SAFE_INTEGER)&&(F=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),F<=0&&this.Error("RANDOM was called with minimum as "+_.value+" and maximum as "+m.value+". The maximum must be larger");let me=this.state.storySeed+this.state.previousRandom,$=new wo.PRNG(me).next(),Ce=$%F+_.value;this.state.PushEvaluationStack(new w.IntValue(Ce)),this.state.previousRandom=$;break}case N.ControlCommand.CommandType.SeedRandom:let h=(0, A.asOrNull)(this.state.PopEvaluationStack(),w.IntValue);if(h==null||!(h instanceof w.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, R.throwNullException)("minInt.value");this.state.storySeed=h.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new On.Void);break;case N.ControlCommand.CommandType.VisitIndex:let c=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new w.IntValue(c));break;case N.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new w.IntValue(f));break;case N.ControlCommand.CommandType.StartThread:break;case N.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Ze.Pointer.Null);break;case N.ControlCommand.CommandType.End:this.state.ForceEnd();break;case N.ControlCommand.CommandType.ListFromInt:let p=(0, A.asOrNull)(this.state.PopEvaluationStack(),w.IntValue),g=(0, A.asOrThrows)(this.state.PopEvaluationStack(),w.StringValue);if(p===null)throw new pt.StoryException("Passed non-integer when creating a list element from a numerical value.");let y=null;if(this.listDefinitions===null)return (0, R.throwNullException)("this.listDefinitions");let b=this.listDefinitions.TryListGetDefinition(g.value,null);if(b.exists){if(p.value===null)return (0, R.throwNullException)("minInt.value");let m=b.result.TryGetItemWithValue(p.value,Nn.InkListItem.Null);m.exists&&(y=new w.ListValue(m.result,p.value));}else throw new pt.StoryException("Failed to find LIST called "+g.value);y==null&&(y=new w.ListValue),this.state.PushEvaluationStack(y);break;case N.ControlCommand.CommandType.ListRange:let T=(0, A.asOrNull)(this.state.PopEvaluationStack(),w.Value),d=(0, A.asOrNull)(this.state.PopEvaluationStack(),w.Value),S=(0, A.asOrNull)(this.state.PopEvaluationStack(),w.ListValue);if(S===null||d===null||T===null)throw new pt.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(S.value===null)return (0, R.throwNullException)("targetList.value");let v=S.value.ListWithSubRange(d.valueObject,T.valueObject);this.state.PushEvaluationStack(new w.ListValue(v));break;case N.ControlCommand.CommandType.ListRandom:{let m=this.state.PopEvaluationStack();if(m===null)throw new pt.StoryException("Expected list for LIST_RANDOM");let _=m.value,F=null;if(_===null)throw (0, R.throwNullException)("list");if(_.Count==0)F=new Nn.InkList;else {let me=this.state.storySeed+this.state.previousRandom,$=new wo.PRNG(me).next(),Ce=$%_.Count,vt=_.entries();for(let Uo=0;Uo<=Ce-1;Uo++)vt.next();let Ho=vt.next().value,Dn={Key:Nn.InkListItem.fromSerializedKey(Ho[0]),Value:Ho[1]};if(Dn.Key.originName===null)return (0, R.throwNullException)("randomItem.Key.originName");F=new Nn.InkList(Dn.Key.originName,this),F.Add(Dn.Key,Dn.Value),this.state.previousRandom=$;}this.state.PushEvaluationStack(new w.ListValue(F));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof Jp.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),true}else if(e instanceof Hp.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);n=new w.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 w.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(e instanceof Up.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==we.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 To.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, R.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, R.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 r=new gt.StringBuilder;for(;this.canContinue;)r.Append(this.Continue());let o=r.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(we.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, R.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(we.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Ze.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let r=[];for(let u=0;u<t;++u){let c=(0, A.asOrThrows)(this.state.PopEvaluationStack(),w.Value).valueObject;r.push(c);}r.reverse();let o=n.function(r),l=null;o!=null?(l=w.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new On.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 r=0,o=i.length;r<o;r++)a[r]=this.TryCoerce(i[r]);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 se.Container&&(e=arguments[0]),arguments[0]instanceof _o.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, A.asOrNull)(i,_o.InkObject),n);}else if(t!=null){let i=(0, A.asOrNull)(t,Au.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, R.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 w.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, A.asOrThrows)(t,w.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 To.Path(e),n=this.ContentAtPath(t).container;if(n===null)return (0, R.throwNullException)("flowContainer");for(;;){let r=n.content[0];if(r instanceof se.Container)n=r;else break}let i=false,a=null;for(let r of n.content){let o=(0, A.asOrNull)(r,N.ControlCommand);if(o!=null)o.commandType==N.ControlCommand.CommandType.BeginTag?i=true:o.commandType==N.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let l=(0, A.asOrNull)(r,w.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 gt.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new gt.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=Ze.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(we.PushPopType.Function)?(this.state.PopCallStack(we.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new On.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, R.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let n=(0, A.asOrNull)(t.container.parent,se.Container);if(!(n instanceof se.Container))break;let i=n.content.indexOf(t.container);if(i==-1)break;if(t=new Ze.Pointer(n,i),t.index++,e=true,t.container===null)return (0, R.throwNullException)("pointer.container")}return e||(t=Ze.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(i=>i.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let n=t[0];return n.targetPath===null?(0, R.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, R.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, A.asOrNull)(this.state.PopEvaluationStack(),w.IntValue);if(!(e instanceof w.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, R.throwNullException)("seqContainer");if(e.value===null)return (0, R.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, A.asOrThrows)(this.state.PopEvaluationStack(),w.IntValue).value;if(a===null)return (0, R.throwNullException)("seqCount");let r=a/n,o=a%n,l=t.path.toString(),u=0;for(let p=0,g=l.length;p<g;p++)u+=l.charCodeAt(p)||0;let h=u+r+this.state.storySeed,c=new wo.PRNG(Math.floor(h)),f=[];for(let p=0;p<n;++p)f.push(p);for(let p=0;p<=o;++p){let g=c.next()%f.length,y=f[g];if(f.splice(g,1),p==o)return y}throw new Error("Should never reach here")}Error(e,t=false){let n=new pt.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 r=n?i.endLineNumber:i.startLineNumber;e="RUNTIME "+a+": '"+i.fileName+"' line "+r+": "+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=Wt;Wt.inkVersionCurrent=21;(function(s){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(s.OutputStateChange||(s.OutputStateChange={}));})(Wt||(mt.Story=Wt={}));});var ku=C(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.Story=void 0;var Yp=Kn(),Qp=Vi(),Yr=H(),Qr=ie(),An=$n(),Zr=ke(),Vu=Nt(),Zp=Ha(),eg=ur(),tg=Qa(),ng=En(),qt=Be(),ig=ze(),rg=Ue(),In=D(),sg=pn(),ag=gn(),og=ct(),es=class s extends Zr.FlowBase{get flowLevel(){return Vu.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(Qp.ConstantDeclaration)()){let c=this.constants.get(h.constantName);if(c&&!c.Equals(h.expression)){let f=`CONST '${h.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${c.debugMetadata}.`;this.Error(f,h,false);}this.constants.set(h.constantName,h.expression);}this._listDefs=new Map;for(let h of this.FindAll(eg.ListDefinition)())!((i=h.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=h.identifier)===null||a===void 0?void 0:a.name,h);this.externals=new Map,this.ResolveWeavePointNaming();let r=this.runtimeObject,o=new Yr.Container;o.AddContent(Qr.ControlCommand.EvalStart());let l=[];for(let[h,c]of this.variableDeclarations)if(c.isGlobalDeclaration){if(c.listDefinition)this._listDefs.set(h,c.listDefinition),o.AddContent(c.listDefinition.runtimeObject),l.push(c.listDefinition.runtimeListDefinition);else {if(!c.expression)throw new Error;c.expression.GenerateIntoContainer(o);}let f=new rg.VariableAssignment(h,true);f.isGlobal=true,o.AddContent(f);}o.AddContent(Qr.ControlCommand.EvalEnd()),o.AddContent(Qr.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",r.AddToNamedContentOnly(o)),r.AddContent(Qr.ControlCommand.Done());let u=new ng.Story(r,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(r),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let i=this._listDefs.get(n);return i||null},this.ResolveListItem=(n,i,a=null)=>{let r=null;if(n)return (r=this._listDefs.get(n))?r.ItemNamed(i):null;{let o=null,l=null;for(let[,u]of this._listDefs.entries()){let h=u.ItemNamed(i);h&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,false):(o=h,l=u));}return o}},this.FlattenContainersIn=n=>{let i=new Set;if(n.content)for(let a of n.content){let r=(0, In.asOrNull)(a,Yr.Container);r&&i.add(r);}if(n.namedContent)for(let[,a]of n.namedContent){let r=(0, In.asOrNull)(a,Yr.Container);r&&i.add(r);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let i=(0, In.asOrNull)(n.parent,Yr.Container);if(i){let a=i.content.indexOf(n);i.content.splice(a,1);let r=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,r!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=r),i.InsertContent(o,a),a+=1;}},this.Error=(n,i,a)=>{let r=a?An.ErrorType.Warning:An.ErrorType.Error,o="";if(i instanceof Yp.AuthorWarning?(o+="TODO: ",r=An.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(o+=`'${i.debugMetadata.fileName}' `),o+=`line ${i.debugMetadata.startLineNumber}: `),o+=n,n=o,this._errorHandler!==null)this._errorHandler(n,r);else throw new Error(n);this._hadError=r===An.ErrorType.Error,this._hadWarning=r===An.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,r)=>{n.Error(`${r} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,i,a,r="")=>{var o;let l=r||n.typeName;if(s.IsReservedKeyword(i?.name)){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(ag.FunctionCall.IsBuiltIn(i?.name||"")){n.Error(`'${i}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(i?.name||"",Vu.FlowLevel.Knot),h=(0, In.asOrNull)(u,Zr.FlowBase);if(h&&(h!==n||a===qt.SymbolType.Arg)){this.NameConflictError(n,i?.name||"",h,l);return}if(a<qt.SymbolType.List)return;for(let[g,y]of this._listDefs)if(i?.name===g&&n!==y&&y.variableAssignment!==n&&this.NameConflictError(n,i?.name,y,l),!(n instanceof tg.ListElementDefinition))for(let b of y.itemDefinitions)i?.name===b.name&&this.NameConflictError(n,i?.name||"",b,l);if(a<=qt.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<qt.SymbolType.SubFlowAndWeave)return;let p=new og.Path(i).ResolveFromContext(n);if(p&&p!==n){this.NameConflictError(n,i?.name||"",p,l);return}if(!(a<qt.SymbolType.Arg)&&a!==qt.SymbolType.Arg){let g=(0, In.asOrNull)(n,Zr.FlowBase);if(g||(g=(0, sg.ClosestFlowBase)(n)),g&&g.hasParameters&&g.args){for(let y of g.args)if(((o=y.identifier)===null||o===void 0?void 0:o.name)===i?.name){n.Error(`${l} '${i}': name has already been used for a argument to ${g.identifier} on ${g.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let n of e)if(n instanceof Zp.IncludedFile){let i=n,a=e.indexOf(n);if(e.splice(a,1),i.includedStory){let r=[],o=i.includedStory;if(o.content!=null){for(let l of o.content)l instanceof Zr.FlowBase?t.push(l):r.push(l);r.push(new ig.Text(`
29
+ `)),e.splice(a,0,...r);}}continue}e.splice(0,0,...t);}};ts.Story=es;es.IsReservedKeyword=s=>{switch(s){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var Du=C(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.StringExpression=void 0;var Ru=ie(),lg=Se(),ug=ze(),hg=D(),xo=class s extends lg.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof ug.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(Ru.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(Ru.ControlCommand.EndString());},this.toString=()=>{let t="";for(let n of this.content)t+=n;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, hg.asOrNull)(e,s);if(t===null||!this.isSingleString||!t.isSingleString)return false;let n=this.toString(),i=t.toString();return n===i}};ns.StringExpression=xo;});var Wu=C(jt=>{Object.defineProperty(jt,"__esModule",{value:true});jt.LegacyTag=jt.Tag=void 0;var cg=M(),Lu=ie(),Po=class extends cg.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?Lu.ControlCommand.BeginTag():Lu.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};jt.Tag=Po;var dg=Ma(),Oo=class extends dg.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};jt.LegacyTag=Oo;});var qu=C(is=>{Object.defineProperty(is,"__esModule",{value:true});is.DefaultFileHandler=void 0;var No=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.")};}};is.DefaultFileHandler=No;});var Vo=C(os=>{Object.defineProperty(os,"__esModule",{value:true});os.InkParser=void 0;var fg=ll(),pg=Kn(),gg=Ds(),Pe=bl(),Z=un(),mg=Ot(),Cg=Al(),vg=Ai(),Fn=ma(),ge=$i(),yg=Vi(),rs=Ql(),Sg=Zl(),Ct=Ft(),Ao=It(),bg=Se(),_g=eu(),ju=tu(),ss=gn(),Eg=fn(),Tg=nu(),wg=Er(),as=ru(),Mu=Ha(),xg=su(),Pg=za(),Bu=ou(),Og=ur(),Ng=Qa(),Ag=da(),Gu=M(),Ig=ct(),$u=ia(),Ju=wa(),Q=_a(),le=Za(),Fg=to(),Hu=ku(),Vn=Du(),Ge=Us(),Mt=Wu(),$e=ze(),Uu=Pa(),Io=Va(),Fo=kt(),Vg=ks(),et=D(),kn=Mi(),Bt=hi(),Ku=$n(),kg=qu(),W=class s extends Ge.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,n=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let r=this.StatementsAtLevel(le.StatementLevel.Top);return new Hu.Story(r,this._rootParser!==this)},this.SeparatedList=(r,o)=>{let l=this.Parse(r);if(l===null)return null;let u=[];u.push(l);do{let h=this.BeginRule();if(o()===null){this.FailRule(h);break}let f=this.Parse(r);if(f===null){this.FailRule(h);break}this.SucceedRule(h),u.push(f);}while(true);return u},this.CreateDebugMetadata=(r,o)=>{let l=new Sg.DebugMetadata;return l.startLineNumber=(r?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(r?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(r,o,l)=>{let u=(0, et.asOrNull)(r,Gu.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let h=Array.isArray(r)?r:null;if(h!==null)for(let f of h)(0, et.asOrNull)(f,Gu.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,l)));let c=(0, et.asOrNull)(r,kn.Identifier);c!=null&&(c.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(r,o,l=0,u=false)=>{let c=u?"WARNING:":"ERROR:";if(this._filename!==null&&(c+=` '${this._filename}'`),c+=` line ${l+1}: ${r}`,this._externalErrorHandler!==null)this._externalErrorHandler(c,u?Ku.ErrorType.Warning:Ku.ErrorType.Error);else throw new Error(c)},this.AuthorWarning=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
30
+ \r`);return o?new pg.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=r=>{let o=s.ListAllCharacterRanges();for(let l of o)r.AddCharacters(l.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let r=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;r=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 ge.ContentList(c));let f=null,p=null,g=this.ParseString("[")!==null;if(g){this.EndTagIfNecessary(h);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(f=new ge.ContentList(d)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let S=this.Parse(this.MixedTextAndLogic);S!==null&&(p=new ge.ContentList(S));}this.Whitespace(),this.EndTagIfNecessary(p??h);let y=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let b=!h&&!p&&!f;if(b&&y===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!h&&g&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),p||(p=new ge.ContentList),this.EndTagIfNecessary(p),y!==null)for(let d of y){let S=(0, et.asOrNull)(d,Ct.Divert);S&&S.isEmpty||p.AddContent(d);}p.AddContent(new $e.Text(`
31
+ `));let T=new mg.Choice(h,f,p);return l&&(T.identifier=l),T.indentationDepth=o.length,T.hasWeaveStyleInlineBrackets=g,T.condition=u,T.onceOnly=r,T.isInvisibleDefault=b,T},this.ChoiceCondition=()=>{let r=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return r===null?null:r.length===1?r[0]:new Ag.MultipleConditionExpression(r)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Ge.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let r=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(r),this.Expect(this.String("}"),"closing '}' for choice condition"),r},this.Gather=()=>{let r=this.Parse(this.GatherDashes);if(r===null)return null;let o=Number(r),l=this.Parse(this.BracketedName),u=new Eg.Gather(l,o);return this.Newline(),u},this.GatherDashes=()=>{this.Whitespace();let r=0;for(;this.ParseDashNotArrow()!==null;)r+=1,this.Whitespace();return r===0?null:r},this.ParseDashNotArrow=()=>{let r=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(r):this.FailRule(r)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),r)},this.InnerConditionalContent=r=>{if(r===void 0){let c=this.Parse(this.ConditionExpression),f=this.Parse(()=>this.InnerConditionalContent(c));return f===null?null:f}let o,l=r!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(r){let c=this.StatementsAtLevel(le.StatementLevel.InnerBlock);if(c!==null){o=[new Fn.ConditionalSingleBranch(c)];let p=this.Parse(this.SingleMultilineCondition);p&&(p.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",p),p.isElse=true),o.push(p));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&r){let c=new Fn.ConditionalSingleBranch(null);c.isTrueBranch=true,o.unshift(c);}if(r){let c=false;for(let f=0;f<o.length;++f){let p=o[f],g=f===o.length-1;p.ownExpression?(p.matchingEquality=true,c=true):c&&g?(p.matchingEquality=true,p.isElse=true):!g&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",p):f===0?p.isTrueBranch=true:p.isElse=true;}}else {for(let c=0;c<o.length;++c){let f=o[c],p=c===o.length-1;if(f.ownExpression===null)if(p)f.isElse=true;else if(f.isElse){let g=o[o.length-1];g.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",g):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",f);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",f);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let c of o)c.isInline=u;return new vg.Conditional(r,o)},this.InlineConditionalBranches=()=>{let r=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(r===null||r.length===0)return null;let o=[];if(r.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let l=new Fn.ConditionalSingleBranch(r[0]);if(l.isTrueBranch=true,o.push(l),r.length>1){let u=new Fn.ConditionalSingleBranch(r[1]);u.isElse=true,o.push(u);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineCondition);return r===null?null:(this.MultilineWhitespace(),r)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=null,o=this.Parse(this.ElseExpression)!==null;o||(r=this.Parse(this.ConditionExpression));let l=this.StatementsAtLevel(le.StatementLevel.InnerBlock);r===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new $e.Text("")]),this.MultilineWhitespace();let u=new Fn.ConditionalSingleBranch(l);return u.ownExpression=r,u.isElse=o,u},this.ConditionExpression=()=>{let r=this.Parse(this.Expression);return r===null||(this.DisallowIncrement(r),this.Whitespace(),this.ParseString(":")===null)?null:r},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:Ge.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(r,o)=>{if(r.length>0){let l=r.length-1,u=r[l];if(u instanceof $e.Text){let h=u;h.text=h.text.replace(new RegExp(/[ \t]+$/g),""),o?h.text+=" ":h.text.length===0&&(r.splice(l,1),this.TrimEndWhitespace(r,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let r=this.Parse(this.MixedTextAndLogic);if(!r||!r.length)return null;let o=r[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),r.length===0?null:(r[r.length-1]instanceof Ct.Divert||this.TrimEndWhitespace(r,false),this.EndTagIfNecessary(r),r.length>0&&r[0]instanceof Mt.Tag&&r[0].isStart||r.push(new $e.Text(`
32
+ `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),r)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let 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 r=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(r===null&&(r=""),o!==null&&(r+=String(o)),l){let u=this.ParseSingleCharacter();r+=u;}}else break}while(true);return r!==null?new $e.Text(r):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new Z.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new Z.CharacterSet(`{}|
33
+ \r\\#`),this._notTextEndCharactersChoice=new Z.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new Z.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let r=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let l=this.ParseUntil(r,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let r=[],o=this.Parse(this.StartThread);if(o)return r=[o],r;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;r=[],this.EndTagIfNecessary(r);for(let u=0;u<l.length;++u)if(u%2===0){if(l[u]==="->->"){u===0||u===l.length-1||u===l.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let f=new Uu.TunnelOnwards;if(u<l.length-1){let p=(0, et.asOrNull)(l[u+1],Ct.Divert);f.divertAfter=p;}r.push(f);break}}else {let c=l[u];u<l.length-1&&(c.isTunnel=true),r.push(c);}if(r.length===0&&l.length===1){let u=new Ct.Divert(null);u.isEmpty=true,r.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return r},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let r=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new Ct.Divert(null));return r.isThread=true,r},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let r=this.Parse(this.DotSeparatedDivertPathComponents);if(!r)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new Ig.Path(r);return new Ct.Divert(l,o)},this.SingleDivert=()=>{let r=this.Parse(this.MultiDivert);if(!r||r.length!==1||r[0]instanceof Uu.TunnelOnwards)return null;let l=r[0];return l.isTunnel?null:l},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let r=0;for(;this.ParseString("->")!==null;)r+=1;return r===0?null:r===1?"->":(r===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let r=this.ParseTempKeyword();this.Whitespace();let o=null;if(r?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let l=this.ParseString("+")!==null,u=this.ParseString("-")!==null;if(l&&u&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return r&&this.Error("Expected '='"),null;let h=this.Expect(this.Expression,"value expression to be assigned");return l||u?new as.IncDecExpression(o,h,l):new Io.VariableAssignment({variableIdentifier:o,assignedExpression:h,isTemporaryNewDeclaration:r})},this.DisallowIncrement=r=>{r instanceof as.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let r=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(r),true):(this.FailRule(r),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new $u.ReturnType(o)},this.Expression=(r=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>r){let h=`right side of '${u.type}' expression`,c=this.Expect(()=>this.ExpressionInfixRight(o,u),h);if(c===null)return this.FailRule(l),null;o=this.SucceedRule(l,c);continue}this.FailRule(l);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let r=this.Parse(this.ExpressionDivertTarget);if(r!==null)return r;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&o!==null&&(l=this.ExpressionUnary()),l===null)return null;o!==null&&(l=Vg.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let h=u==="++";if(!(l instanceof Fo.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let c=l;l=new as.IncDecExpression(c.identifier,h);}}return l},this.ExpressionNot=()=>{let r=this.Identifier();return r==="not"?r:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let r=this.Parse(this.SingleDivert);return !r||r&&r.isThread?null:(this.Whitespace(),new Ao.DivertTarget(r))},this.ExpressionInt=()=>{let r=this.ParseInt();return r===null?null:new Bt.NumberExpression(r,"int")},this.ExpressionFloat=()=>{let r=this.ParseFloat();return r===null?null:new Bt.NumberExpression(r,"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 $e.Text("")]:o.find(l=>l instanceof Ct.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Vn.StringExpression(o)},this.ExpressionBool=()=>{let r=this.Parse(this.Identifier);return r==="true"?new Bt.NumberExpression(true,"bool"):r==="false"?new Bt.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new ss.FunctionCall(r,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,r);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let r=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return r===null||Hu.Story.IsReservedKeyword(r[0].name)?null:new Fo.VariableReference(r)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let r=this.Parse(this.Expression);return r===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),r)},this.ExpressionInfixRight=(r,o)=>{if(!r)return null;this.Whitespace();let l=this.Parse(()=>this.Expression(o.precedence));return l?new gg.BinaryExpression(r,l,o.type):null},this.ParseInfixOperator=()=>{for(let r of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(r.type)!==null){if(r.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,r)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let r=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new Bu.List(r)},this.ListMember=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${r}`);r.name+=`.${l?.name}`;}return this.Whitespace(),r},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(r,o,l=false)=>{let u=new xg.InfixOperator(r,o,l);this._binaryOperators.push(u),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,r.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let r=this.Expect(()=>this.ParseUntilCharactersFromString(`
34
34
  \r`),"filename for include statement");r=r.replace(new RegExp(/[ \t]+$/g),"");let o=this.fileHandler.ResolveInkFilename(r);if(this.FilenameIsAlreadyOpen(o))return this.Error(`Recursive INCLUDE detected: '${o}' is already open.`),this.ParseUntilCharactersFromString(`\r
35
- `),new qu.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o);}catch(h){this.Error(`Failed to load: '${r}'.
36
- Error:${h}`);}return u!=null&&(l=new s(u,r,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new qu.IncludedFile(l)},this.FilenameIsAlreadyOpen=r=>this._rootParser._openFilenames.includes(r),this.AddOpenFilename=r=>{this._rootParser._openFilenames.push(r);},this.RemoveOpenFilename=r=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(r),1);},this.KnotDefinition=()=>{let r=this.Parse(this.KnotDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(oe.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new Tg.Knot(r.name,l,r.args,r.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata),o,l=r?.name==="function";l?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=r,o===null&&(this.Error(`Expected the name of the ${l?"function":"knot"}`),o=new Fn.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new Wu.FlowDecl(o,u,l)},this.KnotTitleEquals=()=>{let r=this.ParseCharactersFromString("=");return r===null||r.length<=1?null:r},this.StitchDefinition=()=>{let r=this.Parse(this.StitchDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(oe.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new Ng.Stitch(r.name,l,r.args,r.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let r=this.ParseString("function")!==null;r&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new Wu.FlowDecl(o,l,r)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new Q.CharacterSet("="),null),[new Be.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),r===null&&(r=[]),r},this.FlowDeclArgument=()=>{let r=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(r==null&&l===null)return null;let u=new hg.Argument;return o!==null&&(u.isDivertTarget=true),r!==null&&r.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=r,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},this.ExternalDeclaration=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new Fn.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(Qe.filterUndef);return new yg.ExternalDeclaration(o,u)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let r=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(r,"expression after '~'",this.SkipToNextLine);if(o===null)return new pe.ContentList;o instanceof vg.Expression&&!(o instanceof is.FunctionCall||o instanceof rs.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
35
+ `),new Mu.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o);}catch(h){this.Error(`Failed to load: '${r}'.
36
+ Error:${h}`);}return u!=null&&(l=new s(u,r,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new Mu.IncludedFile(l)},this.FilenameIsAlreadyOpen=r=>this._rootParser._openFilenames.includes(r),this.AddOpenFilename=r=>{this._rootParser._openFilenames.push(r);},this.RemoveOpenFilename=r=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(r),1);},this.KnotDefinition=()=>{let r=this.Parse(this.KnotDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(le.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new Pg.Knot(r.name,l,r.args,r.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata),o,l=r?.name==="function";l?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=r,o===null&&(this.Error(`Expected the name of the ${l?"function":"knot"}`),o=new kn.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new ju.FlowDecl(o,u,l)},this.KnotTitleEquals=()=>{let r=this.ParseCharactersFromString("=");return r===null||r.length<=1?null:r},this.StitchDefinition=()=>{let r=this.Parse(this.StitchDeclaration);if(r===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(le.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new Fg.Stitch(r.name,l,r.args,r.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let r=this.ParseString("function")!==null;r&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new ju.FlowDecl(o,l,r)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new Z.CharacterSet("="),null),[new $e.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let r=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),r===null&&(r=[]),r},this.FlowDeclArgument=()=>{let r=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(r==null&&l===null)return null;let u=new fg.Argument;return o!==null&&(u.isDivertTarget=true),r!==null&&r.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=r,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},this.ExternalDeclaration=()=>{this.Whitespace();let r=this.Parse(this.IdentifierWithMetadata);if(r===null||r.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new kn.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(et.filterUndef);return new _g.ExternalDeclaration(o,u)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let r=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(r,"expression after '~'",this.SkipToNextLine);if(o===null)return new ge.ContentList;o instanceof bg.Expression&&!(o instanceof ss.FunctionCall||o instanceof as.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 l=(0, Qe.asOrNull)(o,is.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(is.FunctionCall)()!==null&&(o=new pe.ContentList(o,new Be.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 jt.NumberExpression||u instanceof In.StringExpression||u instanceof Po.DivertTarget||u instanceof No.VariableReference||u instanceof ju.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 In.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new Oo.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 Fn.Identifier(o.name),new Oo.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let r=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return r===null?null:new wg.ListDefinition(r)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let r=this.ParseString("(")!==null,o=r;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),r&&this.ParseString(")")!=null&&(o=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 xg.ListElementDefinition(l,r,u)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l instanceof jt.NumberExpression||l instanceof Po.DivertTarget||l instanceof In.StringExpression?l instanceof In.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 mg.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new bg.Glue(new _g.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let r=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let l=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(l===null)return this.parsingStringExpression=r,null;this.DisallowIncrement(l);let u=(0, Qe.asOrNull)(l,pe.ContentList);return u||(u=new pe.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=r,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let r=this.ParseObject(this.SequenceTypeAnnotation);if(r!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new Gu.Sequence(u,r)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let l=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let u of l){let h=this.BeginRule(),c=this.ParseObject(u);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let r=this.Parse(this.Expression);return r&&(r.outputWhenComplete=true),r},this.IdentifierWithMetadata=()=>{let r=this.Identifier();return r===null?null:new Fn.Identifier(r)},this.Identifier=()=>{let r=this.ParseCharactersFromCharSet(this.identifierCharSet);if(r===null)return null;let o=true;for(let l of r)if(!(l>="0"&&l<="9")){o=false;break}return o?null:r},this._sequenceTypeSymbols=new Q.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let r=Y.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(r=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new Gu.Sequence(l,r)},this.SequenceTypeAnnotation=()=>{let r=this.Parse(this.SequenceTypeSymbolAnnotation);if(r===null&&(r=this.Parse(this.SequenceTypeWordAnnotation)),r===null)return null;switch(r){case Y.SequenceType.Once:case Y.SequenceType.Cycle:case Y.SequenceType.Stopping:case Y.SequenceType.Shuffle:case Y.SequenceType.Shuffle|Y.SequenceType.Stopping:case Y.SequenceType.Shuffle|Y.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${r}`),Y.SequenceType.Stopping}return r},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new Q.CharacterSet("!&~$ "));let r=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":r|=Y.SequenceType.Once;break;case "&":r|=Y.SequenceType.Cycle;break;case "~":r|=Y.SequenceType.Shuffle;break;case "$":r|=Y.SequenceType.Stopping;break}return r===0?null:r},this.SequenceTypeWordAnnotation=()=>{let r=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(r===null||r.length===0||this.ParseString(":")===null)return null;let o=0;for(let l of r)o|=l;return o},this.SequenceTypeSingleWord=()=>{let r=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":r=Y.SequenceType.Once;break;case "cycle":r=Y.SequenceType.Cycle;break;case "shuffle":r=Y.SequenceType.Shuffle;break;case "stopping":r=Y.SequenceType.Stopping;break}return r===null?null:r},this.InnerSequenceObjects=()=>{let r=this.Parse(this.Newline)!==null,o=null;return r?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let r=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(r===null)return null;let o=[],l=false;for(let u of r)if(u==="|")l||o.push(new pe.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 pe.ContentList(h)),l=true;}return l||o.push(new pe.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineSequenceElement);return r===null?null:r},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=this.StatementsAtLevel(oe.StatementLevel.InnerBlock);return r===null?this.MultilineWhitespace():r.unshift(new Be.Text(`
42
- `)),new pe.ContentList(r)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=r=>(r===oe.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(r),()=>this.StatementsBreakForLevel(r))),this.StatementAtLevel=r=>{let o=this._statementRulesAtLevel[r],l=this.OneOf(o);return r===oe.StatementLevel.Top&&l instanceof Bu.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=r=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[r],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let r=Object.values(oe.StatementLevel);this._statementRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]);for(let o of r){let l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=oe.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>oe.StatementLevel.InnerBlock&&l.push(this.Gather),o>=oe.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<=oe.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=oe.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=oe.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(),Me.ParseSuccess),this.Line=r=>()=>{let o=this.ParseObject(r);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let r=null;if(this.tagActive){let o=new pe.ContentList;o.AddContent(new qt.Tag(false)),o.AddContent(new qt.Tag(true)),r=o;}else r=new qt.Tag(true);return this.tagActive=true,this.Whitespace(),r},this._inlineWhitespaceChars=new Q.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Me.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Me.ParseSuccess:null),this.MultilineWhitespace=()=>{let r=this.OneOrMore(this.Newline);return r===null?null:r.length>=1?Me.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Me.ParseSuccess:null,this.Spaced=r=>()=>{this.Whitespace();let o=this.ParseObject(r);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let r=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)r=true;return r?Me.ParseSuccess:null},this.MultiSpaced=r=>()=>{this.AnyWhitespace();let o=this.ParseObject(r);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new Ig.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let r=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(r);}}else this._rootParser=i;}PreProcessInputString(e){return new pg.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(ns.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(ns.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(ns.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(ns.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new Q.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 pe.ContentList?e.AddContent(new qt.Tag(false)):e.push(new qt.Tag(false))),this.tagActive=false);}};ss.InkParser=L;L.LatinBasic=xe.CharacterRange.Define("A","z",new Q.CharacterSet().AddRange("[","`"));L.LatinExtendedA=xe.CharacterRange.Define("\u0100","\u017F");L.LatinExtendedB=xe.CharacterRange.Define("\u0180","\u024F");L.Greek=xe.CharacterRange.Define("\u0370","\u03FF",new Q.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));L.Cyrillic=xe.CharacterRange.Define("\u0400","\u04FF",new Q.CharacterSet().AddRange("\u0482","\u0489"));L.Armenian=xe.CharacterRange.Define("\u0530","\u058F",new Q.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));L.Hebrew=xe.CharacterRange.Define("\u0590","\u05FF",new Q.CharacterSet);L.Arabic=xe.CharacterRange.Define("\u0600","\u06FF",new Q.CharacterSet);L.Korean=xe.CharacterRange.Define("\uAC00","\uD7AF",new Q.CharacterSet);L.Latin1Supplement=xe.CharacterRange.Define("\x80","\xFF",new Q.CharacterSet);L.Chinese=xe.CharacterRange.Define("\u4E00","\u9FFF",new Q.CharacterSet);L.ListAllCharacterRanges=()=>[L.LatinBasic,L.LatinExtendedA,L.LatinExtendedB,L.Arabic,L.Armenian,L.Cyrillic,L.Greek,L.Hebrew,L.Korean,L.Latin1Supplement,L.Chinese];});var Uu=C(as=>{Object.defineProperty(as,"__esModule",{value:true});as.GenerateStoryStats=void 0;var Fg=xt(),Vg=At(),kg=cn(),Rg=Ha(),Dg=Qa(),Lg=Ue();function Wg(s){let e=s.FindAll(Lg.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=s.FindAll(Rg.Knot)(),i=s.FindAll(Dg.Stitch)(),a=s.FindAll(Fg.Choice)(),r=s.FindAll(kg.Gather)(l=>l.debugMetadata!=null),o=s.FindAll(Vg.Divert)();return {words:t,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:i.length,gathers:r.length,diverts:o.length-1,choices:a.length}}as.GenerateStoryStats=Wg;});var Ku=C(os=>{Object.defineProperty(os,"__esModule",{value:true});os.JsonFileHandler=void 0;var Io=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}.`)};}};os.JsonFileHandler=Io;});var Xu=C(se=>{Object.defineProperty(se,"__esModule",{value:true});se.Compiler=se.Story=se.InkList=se.JsonFileHandler=se.StatementLevel=se.InkParser=se.CompilerOptions=void 0;var qg=ps(),jg=rl(),Fo=Bn(),Mg=Ao(),Bg=M(),Gg=R(),$g=Uu(),Jg=ps();Object.defineProperty(se,"CompilerOptions",{enumerable:true,get:function(){return Jg.CompilerOptions}});var Hg=Ao();Object.defineProperty(se,"InkParser",{enumerable:true,get:function(){return Hg.InkParser}});var Ug=Xa();Object.defineProperty(se,"StatementLevel",{enumerable:true,get:function(){return Ug.StatementLevel}});var Kg=Ku();Object.defineProperty(se,"JsonFileHandler",{enumerable:true,get:function(){return Kg.JsonFileHandler}});var zu=bn();Object.defineProperty(se,"InkList",{enumerable:true,get:function(){return zu.InkList}});Object.defineProperty(se,"Story",{enumerable:true,get:function(){return zu.Story}});var Vo=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 Mg.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, Gg.asOrNull)(i,Bg.StringValue);if(a!==null){let r=new jg.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(r);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, $g.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let i=0,a=null;for(let r of this.debugSourceRanges){if(r.debugMetadata!==null&&(a=r.debugMetadata),n>=i&&n<i+r.length)return a;i+=r.length;}return null},this.OnError=(n,i)=>{switch(i){case Fo.ErrorType.Author:this._authorMessages.push(n);break;case Fo.ErrorType.Warning:this._warnings.push(n);break;case Fo.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=e,this._options=t||new qg.CompilerOptions;}};se.Compiler=Vo;});var V;(i=>(i.log=(a,...r)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...r),i.warn=(a,...r)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...r),i.error=(a,...r)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...r),i.info=(a,...r)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...r)))(V||={});var Ho="\xA7SPACE\xA7",Uo="\xA7DOUBLE_QUOTES\xA7",Ko="\xA7QUOTES\xA7",zo="SPECIAL_\xA7QUOTES\xA7",Xo="\xA7CURLY_BRACKETS1\xA7",Yo="\xA7CURLY_BRACKETS2\xA7",vh=["add","play","pause","resume","remove","volume"],nt=class s{static _customHashtagScript=e=>false;static runCustomHashtagScript(e,t){return s._customHashtagScript(e,t,s.convertListStringToObj)}static set customHashtagScript(e){s._customHashtagScript=e;}static async generateOrRunOperationFromHashtagScript(e,t,n){try{e=e.replaceAll('\\"',Uo),e=e.replaceAll("\\'",Ko),e=e.replaceAll("\\`",zo),e=e.replaceAll("\\{",Xo),e=e.replaceAll("\\}",Yo),e=e.replaceAll("{"," { "),e=e.replaceAll("}"," } "),e=e.replaceAll(Xo,"{"),e=e.replaceAll(Yo,"}");let i=[],a,r="";for(let h=0;h<e.length;h++){let c=e[h];c==='"'||c==="'"||c==="`"?a===void 0?(i.push(r),r="",a=c,r+=c):a===c?(a=void 0,r+=c,i.push(r),r=""):r+=c:r+=c;}r!==""&&i.push(r),i.forEach((h,c)=>{c%2===1&&(i[c]=h.replaceAll(" ",Ho));}),e=i.join(""),i=e.split(" ").filter(h=>h!==""),i=i.map(h=>h.replaceAll(Ho," ").replaceAll(Uo,'"').replaceAll(Ko,"'").replaceAll(zo,"`"));let o=s.runCustomHashtagScript(i,n);if(o===!0)return;if(typeof o=="string")return o.startsWith("#")&&(o=o.substring(1)),s.generateOrRunOperationFromHashtagScript(o,t,n);let l=i.length>1?s.removeExtraDoubleQuotes(i[1]):"",u=i.length>0?s.removeExtraDoubleQuotes(i[0]):"";switch(l){case "image":case "imagecontainer":case "canvaselement":case "video":return l==="video"&&(u==="pause"||u==="resume")?{type:"video",operationType:u,alias:s.removeExtraDoubleQuotes(i[2])}:s.getCanvasOperationFromComment(i,l);case "sound":return s.getSoundOperationFromComment(i);case "input":if(u==="request"){let h={type:"input",operationType:"request"};if(i.length>2)try{let c=i.slice(2),f=s.convertListStringToObj(c);"type"in f&&typeof f.type=="string"&&(h.valueType=f.type),"default"in f&&(h.defaultValue=f.default);}catch{}return h}break;case "assets":case "bundle":switch(u){case "load":case "lazyload":return {type:l,operationType:u,aliases:i.slice(2)}}break;default:if(l)switch(u){case "call":case "jump":t.labelToOpen={label:l,type:u},t.goNextStep=void 0;return;case "fade":case "move":case "rotate":case "zoom":case "shake":let h={};if(i.length>2)try{h=s.convertListStringToObj(i.slice(2));}catch{}if(u=="move"&&"x"in h&&"y"in h&&(h.destination={x:h.x,y:h.y,type:"pixel"},delete h.x,delete h.y),u=="move"&&"xAlign"in h&&"yAlign"in h&&(h.destination={x:h.xAlign,y:h.yAlign,type:"align"},delete h.xAlign,delete h.yAlign),u=="move"&&"xPercentage"in h&&"yPercentage"in h&&(h.destination={x:h.xPercentage,y:h.yPercentage,type:"percentage"},delete h.xPercentage,delete h.yPercentage),u=="move"&&!("destination"in h)){V.error("The move operation don't have a destination or destination is not valid",h);return}return {alias:l,type:u,props:h};case "animate":let f={},p={};if(i.length>2){let y=i.slice(2),b=[];if(y.includes("options")){let _=y.indexOf("options");b=y.slice(_+1),y=y.slice(0,_);}try{f=s.convertListStringToObj(y);}catch{}if(b.length>0)try{p=s.convertListStringToObj(b);}catch{}}return {alias:l,type:u,keyframes:f,options:p}}else switch(u){case "pause":"dialogue"in t&&delete t.dialogue,"goNextStep"in t&&delete t.goNextStep;break}}}catch(i){throw V.error("Error parsing ink hashtag-script",e),i}V.error("The operation is not valid",e);}static getCanvasOperationFromComment(e,t){let n=s.removeExtraDoubleQuotes(e[0]),i=s.removeExtraDoubleQuotes(e[2]),a=s.convertListStringToPropList(e.slice(3));switch(n){case "show":switch(t){case "image":case "video":return s.getImageOperationFromComment(t,i,a);case "imagecontainer":return s.getContainerOperationFromComment(t,i,a);case "canvaselement":default:V.error("This show operation is not valid for this type of element",t);}case "edit":return {type:t,operationType:"edit",alias:i,props:s.convertPropListStringToObj(a)};case "remove":let o={type:t,operationType:"remove",alias:i};if(a.length>1&&a[0]==="with"){let l=e[e.indexOf("with")+1],u=e.slice(e.indexOf("with")+2),h=s.getTransition(l,u);h!==void 0&&(o.transition=h);}return o;default:V.error("The operation type is not valid",n);}}static getImageOperationFromComment(e,t,n){let i,a;n.length%2===0?(i=t,a=n):(i=s.removeExtraDoubleQuotes(n[0]),a=s.convertListStringToPropList(n.slice(1)));let r={type:e,operationType:"show",alias:t,url:i};return s.setShowProps(r,a)}static getContainerOperationFromComment(e,t,n){let i=[],a=n.findIndex(u=>u.startsWith("[")),r=n.findIndex(u=>u.endsWith("]"));if(a===-1||r===-1){V.error("Show imagecontainer must have a list of image ulrs",n);return}if(i=n.slice(a,r+1),i.length<2){V.error("Show imagecontainer must have a list of image ulrs",n);return}i[0]==="["?i.shift():i[0]=i[0].substring(1),i[i.length-1]==="]"?i.pop():i[i.length-1]=i[i.length-1].substring(0,i[i.length-1].length-1);let o={type:e,operationType:"show",alias:t,urls:i.map(u=>s.removeExtraDoubleQuotes(u))},l=s.convertListStringToPropList(n.slice(r+1));return s.setShowProps(o,l)}static getSoundOperationFromComment(e){let t=s.removeExtraDoubleQuotes(e[0]);if(!vh.includes(t))return;let n=s.removeExtraDoubleQuotes(e[2]);switch(t){case "play":let i={type:"sound",operationType:"play",alias:n};if(e.length>3){let u=s.getSoundPlayOptions(e.slice(3));u!==void 0&&(i.props=u);}return i;case "pause":case "resume":return {type:"sound",operationType:t,alias:n};case "stop":case "remove":return {type:"sound",operationType:"stop",alias:n};case "volume":let o=parseFloat(e[3]);return {type:"sound",operationType:"volume",alias:n,value:o}}}static setShowProps(e,t){if(t.length>0){if(t.includes("with")&&t.length>t.indexOf("with")+1){let n=t[t.indexOf("with")+1],i=t.slice(t.indexOf("with")+2);t=t.slice(0,t.indexOf("with"));let a=s.getTransition(n,i);a!==void 0&&(e.transition=a);}if(t.length>0){let n=s.convertListStringToObj(t);e.props=n;}}return e}static getTransition(e,t){switch(e){case "dissolve":case "fade":case "movein":case "moveout":case "zoomin":case "zoomout":case "pushin":case "pushout":break;default:return}let n={type:e};if(t.length>0)try{let i=s.convertPropListStringToObj(t);n.props=i;}catch{}return n}static getSoundOption(e){try{return s.convertListStringToObj(e)}catch{return}}static getSoundPlayOptions(e){try{return s.convertListStringToObj(e)}catch{return}}static convertListStringToObj(e){let t=s.convertListStringToPropList(e);return s.convertPropListStringToObj(t)}static convertListStringToPropList(e){let t=[],n=0,i="";for(let a=0;a<e.length;a++){let r=e[a];r.startsWith("{")?(n++,i+=r):r.endsWith("}")&&n>0?(n--,i+=r,n===0&&(t.push(i),i="")):n>0?i+=r:t.push(r);}return t}static convertPropListStringToObj(e){if(e.length===0)return {};if(e.length%2!==0)throw V.error("The props list must have a pair number of elements",e),new Error("The props list must have a pair number of elements");let t="{";e.forEach((n,i)=>{if(i%2===0)t+=`"${n}": `;else {switch(n){case "null":case "undefined":case "true":case "false":t+=`${n}`;break;default:s.containExtraDoubleQuotes(n)?(n=s.removeExtraDoubleQuotes(n),t+=`"${n}"`):n.startsWith("{")&&n.endsWith("}")?t+=`${n}`:n.startsWith('"')&&n.endsWith('"')?t+=`${n}`:isNaN(parseFloat(n))?t+=`"${n}"`:t+=`${n}`;}i<e.length-1&&(t+=", ");}}),t+="}";try{return JSON.parse(t)}catch(n){throw V.error("Error parsing ink json",t),n}}static removeExtraDoubleQuotes(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")||e.startsWith("`")&&e.endsWith("`")?e.substring(1,e.length-1):e}static containExtraDoubleQuotes(e){return !!(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")||e.startsWith("`")&&e.endsWith("`"))}};function yh(s){nt.customHashtagScript=s;}var jh=Object.create,el=Object.defineProperty,Mh=Object.getOwnPropertyDescriptor,Bh=Object.getOwnPropertyNames,Gh=Object.getPrototypeOf,$h=Object.prototype.hasOwnProperty,Qo=(s=>typeof tt<"u"?tt:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof tt<"u"?tt:e)[t]}):s)(function(s){if(typeof tt<"u")return tt.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')}),tl=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Jh=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bh(e))!$h.call(s,i)&&i!==t&&el(s,i,{get:()=>e[i],enumerable:!(n=Mh(e,i))||n.enumerable});return s},Hh=(s,e,t)=>(t=s!=null?jh(Gh(s)):{},Jh(el(t,"default",{value:s,enumerable:true}),s)),Uh=tl((s,e)=>{(function(t,n){typeof s=="object"?e.exports=s=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(s,function(){var t=t||function(n,i){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof Qo=="function")try{a=Qo("crypto");}catch{}var r=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||function(){function d(){}return function(S){var v;return d.prototype=S,v=new d,d.prototype=null,v}}(),l={},u=l.lib={},h=u.Base=function(){return {extend:function(d){var S=o(this);return d&&S.mixIn(d),(!S.hasOwnProperty("init")||this.init===S.init)&&(S.init=function(){S.$super.init.apply(this,arguments);}),S.init.prototype=S,S.$super=this,S},create:function(){var d=this.extend();return d.init.apply(d,arguments),d},init:function(){},mixIn:function(d){for(var S in d)d.hasOwnProperty(S)&&(this[S]=d[S]);d.hasOwnProperty("toString")&&(this.toString=d.toString);},clone:function(){return this.init.prototype.extend(this)}}}(),c=u.WordArray=h.extend({init:function(d,S){d=this.words=d||[],S!=i?this.sigBytes=S:this.sigBytes=d.length*4;},toString:function(d){return (d||p).stringify(this)},concat:function(d){var S=this.words,v=d.words,g=this.sigBytes,E=d.sigBytes;if(this.clamp(),g%4)for(var I=0;I<E;I++){var ge=v[I>>>2]>>>24-I%4*8&255;S[g+I>>>2]|=ge<<24-(g+I)%4*8;}else for(var D=0;D<E;D+=4)S[g+D>>>2]=v[D>>>2];return this.sigBytes+=E,this},clamp:function(){var d=this.words,S=this.sigBytes;d[S>>>2]&=4294967295<<32-S%4*8,d.length=n.ceil(S/4);},clone:function(){var d=h.clone.call(this);return d.words=this.words.slice(0),d},random:function(d){for(var S=[],v=0;v<d;v+=4)S.push(r());return new c.init(S,d)}}),f=l.enc={},p=f.Hex={stringify:function(d){for(var S=d.words,v=d.sigBytes,g=[],E=0;E<v;E++){var I=S[E>>>2]>>>24-E%4*8&255;g.push((I>>>4).toString(16)),g.push((I&15).toString(16));}return g.join("")},parse:function(d){for(var S=d.length,v=[],g=0;g<S;g+=2)v[g>>>3]|=parseInt(d.substr(g,2),16)<<24-g%8*4;return new c.init(v,S/2)}},m=f.Latin1={stringify:function(d){for(var S=d.words,v=d.sigBytes,g=[],E=0;E<v;E++){var I=S[E>>>2]>>>24-E%4*8&255;g.push(String.fromCharCode(I));}return g.join("")},parse:function(d){for(var S=d.length,v=[],g=0;g<S;g++)v[g>>>2]|=(d.charCodeAt(g)&255)<<24-g%4*8;return new c.init(v,S)}},y=f.Utf8={stringify:function(d){try{return decodeURIComponent(escape(m.stringify(d)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(d){return m.parse(unescape(encodeURIComponent(d)))}},b=u.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new c.init,this._nDataBytes=0;},_append:function(d){typeof d=="string"&&(d=y.parse(d)),this._data.concat(d),this._nDataBytes+=d.sigBytes;},_process:function(d){var S,v=this._data,g=v.words,E=v.sigBytes,I=this.blockSize,ge=I*4,D=E/ge;d?D=n.ceil(D):D=n.max((D|0)-this._minBufferSize,0);var G=D*I,me=n.min(G*4,E);if(G){for(var mt=0;mt<G;mt+=I)this._doProcessBlock(g,mt);S=g.splice(0,G),v.sigBytes-=me;}return new c.init(S,me)},clone:function(){var d=h.clone.call(this);return d._data=this._data.clone(),d},_minBufferSize:0});u.Hasher=b.extend({cfg:h.extend(),init:function(d){this.cfg=this.cfg.extend(d),this.reset();},reset:function(){b.reset.call(this),this._doReset();},update:function(d){return this._append(d),this._process(),this},finalize:function(d){d&&this._append(d);var S=this._doFinalize();return S},blockSize:16,_createHelper:function(d){return function(S,v){return new d.init(v).finalize(S)}},_createHmacHelper:function(d){return function(S,v){return new _.HMAC.init(d,v).finalize(S)}}});var _=l.algo={};return l}(Math);return t});}),Kh=tl((s,e)=>{(function(t,n){typeof s=="object"?e.exports=s=n(Uh()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(s,function(t){return function(){var n=t,i=n.lib,a=i.WordArray,r=i.Hasher,o=n.algo,l=[],u=o.SHA1=r.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(h,c){for(var f=this._hash.words,p=f[0],m=f[1],y=f[2],b=f[3],_=f[4],d=0;d<80;d++){if(d<16)l[d]=h[c+d]|0;else {var S=l[d-3]^l[d-8]^l[d-14]^l[d-16];l[d]=S<<1|S>>>31;}var v=(p<<5|p>>>27)+_+l[d];d<20?v+=(m&y|~m&b)+1518500249:d<40?v+=(m^y^b)+1859775393:d<60?v+=(m&y|m&b|y&b)-1894007588:v+=(m^y^b)-899497514,_=b,b=y,y=m<<30|m>>>2,m=p,p=v;}f[0]=f[0]+p|0,f[1]=f[1]+m|0,f[2]=f[2]+y|0,f[3]=f[3]+b|0,f[4]=f[4]+_|0;},_doFinalize:function(){var h=this._data,c=h.words,f=this._nDataBytes*8,p=h.sigBytes*8;return c[p>>>5]|=128<<24-p%32,c[(p+64>>>9<<4)+14]=Math.floor(f/4294967296),c[(p+64>>>9<<4)+15]=f,h.sigBytes=c.length*4,this._process(),this._hash},clone:function(){var h=r.clone.call(this);return h._hash=this._hash.clone(),h}});n.SHA1=r._createHelper(u),n.HmacSHA1=r._createHmacHelper(u);}(),t.SHA1});}),zh=Hh(Kh()),Ut="___param___",it=class P{static _beforeToTranslate=void 0;static _translate=e=>e;static _afterToTranslate=void 0;static t(e){return Array.isArray(e)?e.map(t=>P.translate(`${t}`)):P.translate(`${e}`)}static set beforeToTranslate(e){P._beforeToTranslate=e;}static set translate(e){P._translate=e;}static get translate(){return e=>{let t=e;return P._beforeToTranslate&&(t=P._beforeToTranslate(t)),t=P._translate(t),P._afterToTranslate&&(t=P._afterToTranslate(t)),t}}static set afterToTranslate(e){P._afterToTranslate=e;}static addKey(e,t,n){let i=n.defaultValue||"empty_string";typeof t=="string"&&(t=[t]),Array.isArray(t)&&t.forEach(a=>{e[a]===void 0&&(i==="empty_string"?e[a]="":i==="copy_key"&&(P._beforeToTranslate?e[a]=P._beforeToTranslate(a):e[a]=a));});}static getConditionalsThenElse(e,t=[]){if(typeof e=="object"&&e&&"type"in e)if(e.type==="ifelse")e.then&&P.getConditionalsThenElse(e.then,t),e.else&&P.getConditionalsThenElse(e.else,t);else if(e.type==="stepswitch"){if(e.elements)if(Array.isArray(e.elements))e.elements.forEach(n=>{P.getConditionalsThenElse(n,t);});else if(e.elements.type==="ifelse"){let n=[];P.getConditionalsThenElse(e.elements,n),n.forEach(i=>{t.push(...i);});}else if(e.elements.type==="stepswitch"){let n=[];P.getConditionalsThenElse(e.elements,n),n.forEach(i=>{t.push(...i);});}else P.getConditionalsThenElse(e.elements,t);}else e.type==="resulttocombine"?(e.firstItem&&P.getConditionalsThenElse(e.firstItem,t),e.secondConditionalItem&&e.secondConditionalItem.forEach(n=>{P.getConditionalsThenElse(n,t);})):t.push(e);else e&&t.push(e);return t}static generateJsonTranslation(e,t={},n={}){return e.forEach(i=>{if(i.choices){let a=[];Array.isArray(i.choices)?a=[i.choices]:a=P.getConditionalsThenElse(i.choices),a.forEach(r=>r.forEach(o=>{if("type"in o){let l=[];o.type==="ifelse"||o.type==="stepswitch"?P.getConditionalsThenElse(o,l):l=[o],l.map(u=>P.getConditionalsThenElse(u.text)).forEach(u=>{Array.isArray(u)&&u.forEach(h=>{Array.isArray(h)?h.forEach(c=>{typeof c=="string"?P.addKey(t,c,n):P.getConditionalsThenElse(c).forEach(f=>{Array.isArray(f)?f.forEach(p=>{typeof p=="string"&&P.addKey(t,p,n);}):typeof f=="string"&&P.addKey(t,f,n);});}):typeof h=="string"&&P.addKey(t,h,n);});});}}));}if(i.dialogue){let a=[];Array.isArray(i.dialogue)?a=[i.dialogue]:a=P.getConditionalsThenElse(i.dialogue),a.forEach(r=>{typeof r=="string"?P.addKey(t,r,n):"text"in r&&Array.isArray(r.text)&&r.text.forEach(o=>{typeof o=="string"?P.addKey(t,o,n):P.getConditionalsThenElse(o).forEach(l=>{typeof l=="string"?P.addKey(t,l,n):Array.isArray(l)&&l.forEach(u=>{typeof u=="string"?P.addKey(t,u,n):P.getConditionalsThenElse(u).forEach(h=>{typeof h=="string"&&P.addKey(t,h,n);});});});});});}i.conditionalStep&&P.getConditionalsThenElse(i.conditionalStep).forEach(a=>{Array.isArray(a)?P.generateJsonTranslation(a,t,n):P.generateJsonTranslation([a],t,n);});}),t}},We=it,ee;(s=>(s.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),s.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),s.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),s.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(ee||={});function Xh(s,e){return Math.floor(Math.random()*(e-s+1)+s)}function Yh(s){if(Array.isArray(s)||!s)return s;if(s&&typeof s=="object"&&"type"in s)switch(s.type){case "resulttocombine":return Qh(s);case "ifelse":return x(s.condition)?x(s.then):x(s.else);case "stepswitch":let e=x(s.elements)||[];if(e.length===0){ee.error("getValueFromConditionalStatements elements.length === 0");return}switch(s.choiceType){case "random":let t=Xh(0,e.length-1);return x(e[t]);case "loop":let n=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounter(s.nestedId)-1;return n>e.length-1&&(n=n%e.length),x(e[n]);case "sequential":let i,a=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounter(s.nestedId)-1;return s.end=="lastItem"&&(i=x(e[e.length-1])),a>e.length-1?i:x(e[a]);case "sequentialrandom":let r=pixiVn.NarrationManagerStatic.getRandomNumber(0,e.length-1,{nestedId:s.nestedId,onceOnly:true});if(r==null&&s.end=="lastItem"){let o=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounterData(s.nestedId);if(!o||!o?.usedRandomNumbers){ee.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let l=o.usedRandomNumbers[`0-${e.length-1}`];return x(e[l[l.length-1]])}if(r==null){ee.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return x(e[r])}}return s}function Wn(s){if(s.conditionalStep){let e=pixiVn.createExportableElement(x(s.conditionalStep));if(e?.glueEnabled===void 0&&delete e?.glueEnabled,e?.goNextStep===void 0&&delete e?.goNextStep,e?.end===void 0&&delete e?.end,e?.choices===void 0&&delete e?.choices,e?.dialogue===void 0&&delete e?.dialogue,e?.labelToOpen===void 0&&delete e?.labelToOpen,e?.operations===void 0&&delete e?.operations,e){let t={...s,conditionalStep:void 0,...e};return Wn(t)}else pixiVn.storage.getFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY)&&pixiVn.storage.setFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,false);}return s}function Qh(s){let e=s.firstItem,t=[];s.secondConditionalItem?.forEach(i=>{if(Array.isArray(i))i.forEach(a=>{let r=x(a);t.push(r);});else {let a=x(i);t.push(a);}});let n=e?[e,...t]:t;if(n.length===0){ee.warn("combinateResult toCheck.length === 0");return}if(typeof n[0]=="string")return We.t(n);if(typeof n[0]=="object"){let i=n,a,r=i.map((b,_)=>{b=Wn(b);let d=x(b.dialogue)||"";return _===0?(a=x(b.glueEnabled)||false,d):(typeof d=="object"&&"text"in d&&(d=d.character+": "+d.text),a===false&&(d=`
40
+ ~ myFunction()`);let l=(0, et.asOrNull)(o,ss.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(ss.FunctionCall)()!==null&&(o=new ge.ContentList(o,new $e.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 Bt.NumberExpression||u instanceof Vn.StringExpression||u instanceof Ao.DivertTarget||u instanceof Fo.VariableReference||u instanceof Bu.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):u instanceof Vn.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new Io.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 kn.Identifier(o.name),new Io.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let r=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return r===null?null:new Og.ListDefinition(r)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let r=this.ParseString("(")!==null,o=r;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),r&&this.ParseString(")")!=null&&(o=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 Ng.ListElementDefinition(l,r,u)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l instanceof Bt.NumberExpression||l instanceof Ao.DivertTarget||l instanceof Vn.StringExpression?l instanceof Vn.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 yg.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new Tg.Glue(new wg.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let r=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let l=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(l===null)return this.parsingStringExpression=r,null;this.DisallowIncrement(l);let u=(0, et.asOrNull)(l,ge.ContentList);return u||(u=new ge.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=r,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let r=this.ParseObject(this.SequenceTypeAnnotation);if(r!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new Ju.Sequence(u,r)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let l=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let u of l){let h=this.BeginRule(),c=this.ParseObject(u);if(c)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(h);else return this.SucceedRule(h,c);else this.FailRule(h);}return null},this.InnerExpression=()=>{let r=this.Parse(this.Expression);return r&&(r.outputWhenComplete=true),r},this.IdentifierWithMetadata=()=>{let r=this.Identifier();return r===null?null:new kn.Identifier(r)},this.Identifier=()=>{let r=this.ParseCharactersFromCharSet(this.identifierCharSet);if(r===null)return null;let o=true;for(let l of r)if(!(l>="0"&&l<="9")){o=false;break}return o?null:r},this._sequenceTypeSymbols=new Z.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let r=Q.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(r=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new Ju.Sequence(l,r)},this.SequenceTypeAnnotation=()=>{let r=this.Parse(this.SequenceTypeSymbolAnnotation);if(r===null&&(r=this.Parse(this.SequenceTypeWordAnnotation)),r===null)return null;switch(r){case Q.SequenceType.Once:case Q.SequenceType.Cycle:case Q.SequenceType.Stopping:case Q.SequenceType.Shuffle:case Q.SequenceType.Shuffle|Q.SequenceType.Stopping:case Q.SequenceType.Shuffle|Q.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${r}`),Q.SequenceType.Stopping}return r},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new Z.CharacterSet("!&~$ "));let r=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":r|=Q.SequenceType.Once;break;case "&":r|=Q.SequenceType.Cycle;break;case "~":r|=Q.SequenceType.Shuffle;break;case "$":r|=Q.SequenceType.Stopping;break}return r===0?null:r},this.SequenceTypeWordAnnotation=()=>{let r=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(r===null||r.length===0||this.ParseString(":")===null)return null;let o=0;for(let l of r)o|=l;return o},this.SequenceTypeSingleWord=()=>{let r=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":r=Q.SequenceType.Once;break;case "cycle":r=Q.SequenceType.Cycle;break;case "shuffle":r=Q.SequenceType.Shuffle;break;case "stopping":r=Q.SequenceType.Stopping;break}return r===null?null:r},this.InnerSequenceObjects=()=>{let r=this.Parse(this.Newline)!==null,o=null;return r?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let r=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(r===null)return null;let o=[],l=false;for(let u of r)if(u==="|")l||o.push(new ge.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 ge.ContentList(h)),l=true;}return l||o.push(new ge.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let r=this.OneOrMore(this.SingleMultilineSequenceElement);return r===null?null:r},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let r=this.StatementsAtLevel(le.StatementLevel.InnerBlock);return r===null?this.MultilineWhitespace():r.unshift(new $e.Text(`
42
+ `)),new ge.ContentList(r)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=r=>(r===le.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(r),()=>this.StatementsBreakForLevel(r))),this.StatementAtLevel=r=>{let o=this._statementRulesAtLevel[r],l=this.OneOf(o);return r===le.StatementLevel.Top&&l instanceof $u.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=r=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[r],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let r=Object.values(le.StatementLevel);this._statementRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(r.length).split("f").map(()=>[]);for(let o of r){let l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=le.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>le.StatementLevel.InnerBlock&&l.push(this.Gather),o>=le.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<=le.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=le.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=le.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(),Ge.ParseSuccess),this.Line=r=>()=>{let o=this.ParseObject(r);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let r=null;if(this.tagActive){let o=new ge.ContentList;o.AddContent(new Mt.Tag(false)),o.AddContent(new Mt.Tag(true)),r=o;}else r=new Mt.Tag(true);return this.tagActive=true,this.Whitespace(),r},this._inlineWhitespaceChars=new Z.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Ge.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Ge.ParseSuccess:null),this.MultilineWhitespace=()=>{let r=this.OneOrMore(this.Newline);return r===null?null:r.length>=1?Ge.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Ge.ParseSuccess:null,this.Spaced=r=>()=>{this.Whitespace();let o=this.ParseObject(r);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let r=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)r=true;return r?Ge.ParseSuccess:null},this.MultiSpaced=r=>()=>{this.AnyWhitespace();let o=this.ParseObject(r);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=n,a===null?this._fileHandler=new kg.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let r=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(r);}}else this._rootParser=i;}PreProcessInputString(e){return new Cg.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(rs.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(rs.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(rs.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(rs.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new Z.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(e){this.tagActive&&(e!=null&&(e instanceof ge.ContentList?e.AddContent(new Mt.Tag(false)):e.push(new Mt.Tag(false))),this.tagActive=false);}};os.InkParser=W;W.LatinBasic=Pe.CharacterRange.Define("A","z",new Z.CharacterSet().AddRange("[","`"));W.LatinExtendedA=Pe.CharacterRange.Define("\u0100","\u017F");W.LatinExtendedB=Pe.CharacterRange.Define("\u0180","\u024F");W.Greek=Pe.CharacterRange.Define("\u0370","\u03FF",new Z.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));W.Cyrillic=Pe.CharacterRange.Define("\u0400","\u04FF",new Z.CharacterSet().AddRange("\u0482","\u0489"));W.Armenian=Pe.CharacterRange.Define("\u0530","\u058F",new Z.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));W.Hebrew=Pe.CharacterRange.Define("\u0590","\u05FF",new Z.CharacterSet);W.Arabic=Pe.CharacterRange.Define("\u0600","\u06FF",new Z.CharacterSet);W.Korean=Pe.CharacterRange.Define("\uAC00","\uD7AF",new Z.CharacterSet);W.Latin1Supplement=Pe.CharacterRange.Define("\x80","\xFF",new Z.CharacterSet);W.Chinese=Pe.CharacterRange.Define("\u4E00","\u9FFF",new Z.CharacterSet);W.ListAllCharacterRanges=()=>[W.LatinBasic,W.LatinExtendedA,W.LatinExtendedB,W.Arabic,W.Armenian,W.Cyrillic,W.Greek,W.Hebrew,W.Korean,W.Latin1Supplement,W.Chinese];});var zu=C(ls=>{Object.defineProperty(ls,"__esModule",{value:true});ls.GenerateStoryStats=void 0;var Rg=Ot(),Dg=Ft(),Lg=fn(),Wg=za(),qg=to(),jg=ze();function Mg(s){let e=s.FindAll(jg.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=s.FindAll(Wg.Knot)(),i=s.FindAll(qg.Stitch)(),a=s.FindAll(Rg.Choice)(),r=s.FindAll(Lg.Gather)(l=>l.debugMetadata!=null),o=s.FindAll(Dg.Divert)();return {words:t,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:i.length,gathers:r.length,diverts:o.length-1,choices:a.length}}ls.GenerateStoryStats=Mg;});var Xu=C(us=>{Object.defineProperty(us,"__esModule",{value:true});us.JsonFileHandler=void 0;var ko=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}.`)};}};us.JsonFileHandler=ko;});var Qu=C(ae=>{Object.defineProperty(ae,"__esModule",{value:true});ae.Compiler=ae.Story=ae.InkList=ae.JsonFileHandler=ae.StatementLevel=ae.InkParser=ae.CompilerOptions=void 0;var Bg=Cs(),Gg=al(),Ro=$n(),$g=Vo(),Jg=B(),Hg=D(),Ug=zu(),Kg=Cs();Object.defineProperty(ae,"CompilerOptions",{enumerable:true,get:function(){return Kg.CompilerOptions}});var zg=Vo();Object.defineProperty(ae,"InkParser",{enumerable:true,get:function(){return zg.InkParser}});var Xg=Za();Object.defineProperty(ae,"StatementLevel",{enumerable:true,get:function(){return Xg.StatementLevel}});var Yg=Xu();Object.defineProperty(ae,"JsonFileHandler",{enumerable:true,get:function(){return Yg.JsonFileHandler}});var Yu=En();Object.defineProperty(ae,"InkList",{enumerable:true,get:function(){return Yu.InkList}});Object.defineProperty(ae,"Story",{enumerable:true,get:function(){return Yu.Story}});var Do=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 $g.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, Hg.asOrNull)(i,Jg.StringValue);if(a!==null){let r=new Gg.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(r);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, Ug.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let i=0,a=null;for(let r of this.debugSourceRanges){if(r.debugMetadata!==null&&(a=r.debugMetadata),n>=i&&n<i+r.length)return a;i+=r.length;}return null},this.OnError=(n,i)=>{switch(i){case Ro.ErrorType.Author:this._authorMessages.push(n);break;case Ro.ErrorType.Warning:this._warnings.push(n);break;case Ro.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,i);},this._inputString=e,this._options=t||new Bg.CompilerOptions;}};ae.Compiler=Do;});var V;(i=>(i.log=(a,...r)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...r),i.warn=(a,...r)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...r),i.error=(a,...r)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...r),i.info=(a,...r)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...r)))(V||(V={}));var Ko="\xA7SPACE\xA7",zo="\xA7DOUBLE_QUOTES\xA7",Xo="\xA7QUOTES\xA7",Yo="SPECIAL_\xA7QUOTES\xA7",Qo="\xA7CURLY_BRACKETS1\xA7",Zo="\xA7CURLY_BRACKETS2\xA7",bh=["add","play","pause","resume","remove","volume"],O=class O{static runCustomHashtagScript(e,t){return O._customHashtagScript(e,t,O.convertListStringToObj)}static set customHashtagScript(e){O._customHashtagScript=e;}static async generateOrRunOperationFromHashtagScript(e,t,n){try{e=e.replaceAll('\\"',zo),e=e.replaceAll("\\'",Xo),e=e.replaceAll("\\`",Yo),e=e.replaceAll("\\{",Qo),e=e.replaceAll("\\}",Zo),e=e.replaceAll("{"," { "),e=e.replaceAll("}"," } "),e=e.replaceAll(Qo,"{"),e=e.replaceAll(Zo,"}");let i=[],a,r="";for(let h=0;h<e.length;h++){let c=e[h];c==='"'||c==="'"||c==="`"?a===void 0?(i.push(r),r="",a=c,r+=c):a===c?(a=void 0,r+=c,i.push(r),r=""):r+=c:r+=c;}r!==""&&i.push(r),i.forEach((h,c)=>{c%2===1&&(i[c]=h.replaceAll(" ",Ko));}),e=i.join(""),i=e.split(" ").filter(h=>h!==""),i=i.map(h=>h.replaceAll(Ko," ").replaceAll(zo,'"').replaceAll(Xo,"'").replaceAll(Yo,"`"));let o=O.runCustomHashtagScript(i,n);if(o===!0)return;if(typeof o=="string")return o.startsWith("#")&&(o=o.substring(1)),O.generateOrRunOperationFromHashtagScript(o,t,n);let l=i.length>1?O.removeExtraDoubleQuotes(i[1]):"",u=i.length>0?O.removeExtraDoubleQuotes(i[0]):"";switch(l){case "image":case "imagecontainer":case "canvaselement":case "video":return l==="video"&&(u==="pause"||u==="resume")?{type:"video",operationType:u,alias:O.removeExtraDoubleQuotes(i[2])}:O.getCanvasOperationFromComment(i,l);case "sound":return O.getSoundOperationFromComment(i);case "input":if(u==="request"){let h={type:"input",operationType:"request"};if(i.length>2)try{let c=i.slice(2),f=O.convertListStringToObj(c);"type"in f&&typeof f.type=="string"&&(h.valueType=f.type),"default"in f&&(h.defaultValue=f.default);}catch{}return h}break;case "assets":case "bundle":switch(u){case "load":case "lazyload":return {type:l,operationType:u,aliases:i.slice(2)}}break;default:if(l)switch(u){case "call":case "jump":t.labelToOpen={label:l,type:u},t.goNextStep=void 0;return;case "fade":case "move":case "rotate":case "zoom":case "shake":let h={};if(i.length>2)try{h=O.convertListStringToObj(i.slice(2));}catch{}if(u=="move"&&"x"in h&&"y"in h&&(h.destination={x:h.x,y:h.y,type:"pixel"},delete h.x,delete h.y),u=="move"&&"xAlign"in h&&"yAlign"in h&&(h.destination={x:h.xAlign,y:h.yAlign,type:"align"},delete h.xAlign,delete h.yAlign),u=="move"&&"xPercentage"in h&&"yPercentage"in h&&(h.destination={x:h.xPercentage,y:h.yPercentage,type:"percentage"},delete h.xPercentage,delete h.yPercentage),u=="move"&&!("destination"in h)){V.error("The move operation don't have a destination or destination is not valid",h);return}return {alias:l,type:u,props:h};case "animate":let f={},p={};if(i.length>2){let y=i.slice(2),b=[];if(y.includes("options")){let T=y.indexOf("options");b=y.slice(T+1),y=y.slice(0,T);}try{f=O.convertListStringToObj(y);}catch{}if(b.length>0)try{p=O.convertListStringToObj(b);}catch{}}return {alias:l,type:u,keyframes:f,options:p}}else switch(u){case "pause":"dialogue"in t&&delete t.dialogue,"goNextStep"in t&&delete t.goNextStep;break}}}catch(i){throw V.error("Error parsing ink hashtag-script",e),i}V.error("The operation is not valid",e);}static getCanvasOperationFromComment(e,t){let n=O.removeExtraDoubleQuotes(e[0]),i=O.removeExtraDoubleQuotes(e[2]),a=O.convertListStringToPropList(e.slice(3));switch(n){case "show":switch(t){case "image":case "video":return O.getImageOperationFromComment(t,i,a);case "imagecontainer":return O.getContainerOperationFromComment(t,i,a);case "canvaselement":default:V.error("This show operation is not valid for this type of element",t);}case "edit":return {type:t,operationType:"edit",alias:i,props:O.convertPropListStringToObj(a)};case "remove":let o={type:t,operationType:"remove",alias:i};if(a.length>1&&a[0]==="with"){let l=e[e.indexOf("with")+1],u=e.slice(e.indexOf("with")+2),h=O.getTransition(l,u);h!==void 0&&(o.transition=h);}return o;default:V.error("The operation type is not valid",n);}}static getImageOperationFromComment(e,t,n){let i,a;n.length%2===0?(i=t,a=n):(i=O.removeExtraDoubleQuotes(n[0]),a=O.convertListStringToPropList(n.slice(1)));let r={type:e,operationType:"show",alias:t,url:i};return O.setShowProps(r,a)}static getContainerOperationFromComment(e,t,n){let i=[],a=n.findIndex(u=>u.startsWith("[")),r=n.findIndex(u=>u.endsWith("]"));if(a===-1||r===-1){V.error("Show imagecontainer must have a list of image ulrs",n);return}if(i=n.slice(a,r+1),i.length<2){V.error("Show imagecontainer must have a list of image ulrs",n);return}i[0]==="["?i.shift():i[0]=i[0].substring(1),i[i.length-1]==="]"?i.pop():i[i.length-1]=i[i.length-1].substring(0,i[i.length-1].length-1);let o={type:e,operationType:"show",alias:t,urls:i.map(u=>O.removeExtraDoubleQuotes(u))},l=O.convertListStringToPropList(n.slice(r+1));return O.setShowProps(o,l)}static getSoundOperationFromComment(e){let t=O.removeExtraDoubleQuotes(e[0]);if(!bh.includes(t))return;let n=O.removeExtraDoubleQuotes(e[2]);switch(t){case "play":let i={type:"sound",operationType:"play",alias:n};if(e.length>3){let u=O.getSoundPlayOptions(e.slice(3));u!==void 0&&(i.props=u);}return i;case "pause":case "resume":return {type:"sound",operationType:t,alias:n};case "stop":case "remove":return {type:"sound",operationType:"stop",alias:n};case "volume":let o=parseFloat(e[3]);return {type:"sound",operationType:"volume",alias:n,value:o}}}static setShowProps(e,t){if(t.length>0){if(t.includes("with")&&t.length>t.indexOf("with")+1){let n=t[t.indexOf("with")+1],i=t.slice(t.indexOf("with")+2);t=t.slice(0,t.indexOf("with"));let a=O.getTransition(n,i);a!==void 0&&(e.transition=a);}if(t.length>0){let n=O.convertListStringToObj(t);e.props=n;}}return e}static getTransition(e,t){switch(e){case "dissolve":case "fade":case "movein":case "moveout":case "zoomin":case "zoomout":case "pushin":case "pushout":break;default:return}let n={type:e};if(t.length>0)try{let i=O.convertPropListStringToObj(t);n.props=i;}catch{}return n}static getSoundOption(e){try{return O.convertListStringToObj(e)}catch{return}}static getSoundPlayOptions(e){try{return O.convertListStringToObj(e)}catch{return}}static convertListStringToObj(e){let t=O.convertListStringToPropList(e);return O.convertPropListStringToObj(t)}static convertListStringToPropList(e){let t=[],n=0,i="";for(let a=0;a<e.length;a++){let r=e[a];r.startsWith("{")?(n++,i+=r):r.endsWith("}")&&n>0?(n--,i+=r,n===0&&(t.push(i),i="")):n>0?i+=r:t.push(r);}return t}static convertPropListStringToObj(e){if(e.length===0)return {};if(e.length%2!==0)throw V.error("The props list must have a pair number of elements",e),new Error("The props list must have a pair number of elements");let t="{";e.forEach((n,i)=>{if(i%2===0)t+=`"${n}": `;else {switch(n){case "null":case "undefined":case "true":case "false":t+=`${n}`;break;default:O.containExtraDoubleQuotes(n)?(n=O.removeExtraDoubleQuotes(n),t+=`"${n}"`):n.startsWith("{")&&n.endsWith("}")?t+=`${n}`:n.startsWith('"')&&n.endsWith('"')?t+=`${n}`:isNaN(parseFloat(n))?t+=`"${n}"`:t+=`${n}`;}i<e.length-1&&(t+=", ");}}),t+="}";try{return JSON.parse(t)}catch(n){throw V.error("Error parsing ink json",t),n}}static removeExtraDoubleQuotes(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")||e.startsWith("`")&&e.endsWith("`")?e.substring(1,e.length-1):e}static containExtraDoubleQuotes(e){return !!(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")||e.startsWith("`")&&e.endsWith("`"))}};qe(O,"_customHashtagScript",e=>false);var rt=O;function _h(s){rt.customHashtagScript=s;}var Gh=Object.create,nl=Object.defineProperty,$h=Object.getOwnPropertyDescriptor,Jh=Object.getOwnPropertyNames,Hh=Object.getPrototypeOf,Uh=Object.prototype.hasOwnProperty,el=(s=>typeof it<"u"?it:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof it<"u"?it:e)[t]}):s)(function(s){if(typeof it<"u")return it.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')}),il=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Kh=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jh(e))!Uh.call(s,i)&&i!==t&&nl(s,i,{get:()=>e[i],enumerable:!(n=$h(e,i))||n.enumerable});return s},zh=(s,e,t)=>(t=s!=null?Gh(Hh(s)):{},Kh(nl(t,"default",{value:s,enumerable:true}),s)),Xh=il((s,e)=>{(function(t,n){typeof s=="object"?e.exports=s=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(s,function(){var t=t||(function(n,i){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof el=="function")try{a=el("crypto");}catch{}var r=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||(function(){function d(){}return function(S){var v;return d.prototype=S,v=new d,d.prototype=null,v}})(),l={},u=l.lib={},h=u.Base=(function(){return {extend:function(d){var S=o(this);return d&&S.mixIn(d),(!S.hasOwnProperty("init")||this.init===S.init)&&(S.init=function(){S.$super.init.apply(this,arguments);}),S.init.prototype=S,S.$super=this,S},create:function(){var d=this.extend();return d.init.apply(d,arguments),d},init:function(){},mixIn:function(d){for(var S in d)d.hasOwnProperty(S)&&(this[S]=d[S]);d.hasOwnProperty("toString")&&(this.toString=d.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),c=u.WordArray=h.extend({init:function(d,S){d=this.words=d||[],S!=i?this.sigBytes=S:this.sigBytes=d.length*4;},toString:function(d){return (d||p).stringify(this)},concat:function(d){var S=this.words,v=d.words,m=this.sigBytes,_=d.sigBytes;if(this.clamp(),m%4)for(var F=0;F<_;F++){var me=v[F>>>2]>>>24-F%4*8&255;S[m+F>>>2]|=me<<24-(m+F)%4*8;}else for(var L=0;L<_;L+=4)S[m+L>>>2]=v[L>>>2];return this.sigBytes+=_,this},clamp:function(){var d=this.words,S=this.sigBytes;d[S>>>2]&=4294967295<<32-S%4*8,d.length=n.ceil(S/4);},clone:function(){var d=h.clone.call(this);return d.words=this.words.slice(0),d},random:function(d){for(var S=[],v=0;v<d;v+=4)S.push(r());return new c.init(S,d)}}),f=l.enc={},p=f.Hex={stringify:function(d){for(var S=d.words,v=d.sigBytes,m=[],_=0;_<v;_++){var F=S[_>>>2]>>>24-_%4*8&255;m.push((F>>>4).toString(16)),m.push((F&15).toString(16));}return m.join("")},parse:function(d){for(var S=d.length,v=[],m=0;m<S;m+=2)v[m>>>3]|=parseInt(d.substr(m,2),16)<<24-m%8*4;return new c.init(v,S/2)}},g=f.Latin1={stringify:function(d){for(var S=d.words,v=d.sigBytes,m=[],_=0;_<v;_++){var F=S[_>>>2]>>>24-_%4*8&255;m.push(String.fromCharCode(F));}return m.join("")},parse:function(d){for(var S=d.length,v=[],m=0;m<S;m++)v[m>>>2]|=(d.charCodeAt(m)&255)<<24-m%4*8;return new c.init(v,S)}},y=f.Utf8={stringify:function(d){try{return decodeURIComponent(escape(g.stringify(d)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(d){return g.parse(unescape(encodeURIComponent(d)))}},b=u.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new c.init,this._nDataBytes=0;},_append:function(d){typeof d=="string"&&(d=y.parse(d)),this._data.concat(d),this._nDataBytes+=d.sigBytes;},_process:function(d){var S,v=this._data,m=v.words,_=v.sigBytes,F=this.blockSize,me=F*4,L=_/me;d?L=n.ceil(L):L=n.max((L|0)-this._minBufferSize,0);var $=L*F,Ce=n.min($*4,_);if($){for(var vt=0;vt<$;vt+=F)this._doProcessBlock(m,vt);S=m.splice(0,$),v.sigBytes-=Ce;}return new c.init(S,Ce)},clone:function(){var d=h.clone.call(this);return d._data=this._data.clone(),d},_minBufferSize:0});u.Hasher=b.extend({cfg:h.extend(),init:function(d){this.cfg=this.cfg.extend(d),this.reset();},reset:function(){b.reset.call(this),this._doReset();},update:function(d){return this._append(d),this._process(),this},finalize:function(d){d&&this._append(d);var S=this._doFinalize();return S},blockSize:16,_createHelper:function(d){return function(S,v){return new d.init(v).finalize(S)}},_createHmacHelper:function(d){return function(S,v){return new T.HMAC.init(d,v).finalize(S)}}});var T=l.algo={};return l})(Math);return t});}),Yh=il((s,e)=>{(function(t,n){typeof s=="object"?e.exports=s=n(Xh()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(s,function(t){return (function(){var n=t,i=n.lib,a=i.WordArray,r=i.Hasher,o=n.algo,l=[],u=o.SHA1=r.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(h,c){for(var f=this._hash.words,p=f[0],g=f[1],y=f[2],b=f[3],T=f[4],d=0;d<80;d++){if(d<16)l[d]=h[c+d]|0;else {var S=l[d-3]^l[d-8]^l[d-14]^l[d-16];l[d]=S<<1|S>>>31;}var v=(p<<5|p>>>27)+T+l[d];d<20?v+=(g&y|~g&b)+1518500249:d<40?v+=(g^y^b)+1859775393:d<60?v+=(g&y|g&b|y&b)-1894007588:v+=(g^y^b)-899497514,T=b,b=y,y=g<<30|g>>>2,g=p,p=v;}f[0]=f[0]+p|0,f[1]=f[1]+g|0,f[2]=f[2]+y|0,f[3]=f[3]+b|0,f[4]=f[4]+T|0;},_doFinalize:function(){var h=this._data,c=h.words,f=this._nDataBytes*8,p=h.sigBytes*8;return c[p>>>5]|=128<<24-p%32,c[(p+64>>>9<<4)+14]=Math.floor(f/4294967296),c[(p+64>>>9<<4)+15]=f,h.sigBytes=c.length*4,this._process(),this._hash},clone:function(){var h=r.clone.call(this);return h._hash=this._hash.clone(),h}});n.SHA1=r._createHelper(u),n.HmacSHA1=r._createHmacHelper(u);})(),t.SHA1});}),Qh=zh(Yh()),zt="___param___",x,st=(x=class{static t(e){return Array.isArray(e)?e.map(t=>x.translate(`${t}`)):x.translate(`${e}`)}static set beforeToTranslate(e){x._beforeToTranslate=e;}static set translate(e){x._translate=e;}static get translate(){return e=>{let t=e;return x._beforeToTranslate&&(t=x._beforeToTranslate(t)),t=x._translate(t),x._afterToTranslate&&(t=x._afterToTranslate(t)),t}}static set afterToTranslate(e){x._afterToTranslate=e;}static addKey(e,t,n){let i=n.defaultValue||"empty_string";typeof t=="string"&&(t=[t]),Array.isArray(t)&&t.forEach(a=>{e[a]===void 0&&(i==="empty_string"?e[a]="":i==="copy_key"&&(x._beforeToTranslate?e[a]=x._beforeToTranslate(a):e[a]=a));});}static getConditionalsThenElse(e,t=[]){if(typeof e=="object"&&e&&"type"in e)if(e.type==="ifelse")e.then&&x.getConditionalsThenElse(e.then,t),e.else&&x.getConditionalsThenElse(e.else,t);else if(e.type==="stepswitch"){if(e.elements)if(Array.isArray(e.elements))e.elements.forEach(n=>{x.getConditionalsThenElse(n,t);});else if(e.elements.type==="ifelse"){let n=[];x.getConditionalsThenElse(e.elements,n),n.forEach(i=>{t.push(...i);});}else if(e.elements.type==="stepswitch"){let n=[];x.getConditionalsThenElse(e.elements,n),n.forEach(i=>{t.push(...i);});}else x.getConditionalsThenElse(e.elements,t);}else e.type==="resulttocombine"?(e.firstItem&&x.getConditionalsThenElse(e.firstItem,t),e.secondConditionalItem&&e.secondConditionalItem.forEach(n=>{x.getConditionalsThenElse(n,t);})):t.push(e);else e&&t.push(e);return t}static generateJsonTranslation(e,t={},n={}){let{defaultValue:i="copy_key"}=n;return e.forEach(a=>{if(a.choices){let r=[];Array.isArray(a.choices)?r=[a.choices]:r=x.getConditionalsThenElse(a.choices),r.forEach(o=>o.forEach(l=>{if("type"in l){let u=[];l.type==="ifelse"||l.type==="stepswitch"?x.getConditionalsThenElse(l,u):u=[l],u.map(h=>x.getConditionalsThenElse(h.text)).forEach(h=>{Array.isArray(h)&&h.forEach(c=>{Array.isArray(c)?c.forEach(f=>{typeof f=="string"?x.addKey(t,f,{defaultValue:i}):x.getConditionalsThenElse(f).forEach(p=>{Array.isArray(p)?p.forEach(g=>{typeof g=="string"&&x.addKey(t,g,{defaultValue:i});}):typeof p=="string"&&x.addKey(t,p,{defaultValue:i});});}):typeof c=="string"&&x.addKey(t,c,{defaultValue:i});});});}}));}if(a.dialogue){let r=[];Array.isArray(a.dialogue)?r=[a.dialogue]:r=x.getConditionalsThenElse(a.dialogue),r.forEach(o=>{typeof o=="string"?x.addKey(t,o,{defaultValue:i}):"text"in o&&Array.isArray(o.text)&&o.text.forEach(l=>{typeof l=="string"?x.addKey(t,l,{defaultValue:i}):x.getConditionalsThenElse(l).forEach(u=>{typeof u=="string"?x.addKey(t,u,{defaultValue:i}):Array.isArray(u)&&u.forEach(h=>{typeof h=="string"?x.addKey(t,h,{defaultValue:i}):x.getConditionalsThenElse(h).forEach(c=>{typeof c=="string"&&x.addKey(t,c,{defaultValue:i});});});});});});}a.conditionalStep&&x.getConditionalsThenElse(a.conditionalStep).forEach(r=>{Array.isArray(r)?x.generateJsonTranslation(r,t,n):x.generateJsonTranslation([r],t,n);});}),t}},qe(x,"_beforeToTranslate"),qe(x,"_translate",e=>e),qe(x,"_afterToTranslate"),x),je=st,te;(s=>(s.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),s.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),s.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),s.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(te||(te={}));function Zh(s,e){return Math.floor(Math.random()*(e-s+1)+s)}function ec(s){if(Array.isArray(s)||!s)return s;if(s&&typeof s=="object"&&"type"in s)switch(s.type){case "resulttocombine":return tc(s);case "ifelse":return P(s.condition)?P(s.then):P(s.else);case "stepswitch":let e=P(s.elements)||[];if(e.length===0){te.error("getValueFromConditionalStatements elements.length === 0");return}switch(s.choiceType){case "random":let t=Zh(0,e.length-1);return P(e[t]);case "loop":let n=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounter(s.nestedId)-1;return n>e.length-1&&(n=n%e.length),P(e[n]);case "sequential":let i,a=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounter(s.nestedId)-1;return s.end=="lastItem"&&(i=P(e[e.length-1])),a>e.length-1?i:P(e[a]);case "sequentialrandom":let r=pixiVn.NarrationManagerStatic.getRandomNumber(0,e.length-1,{nestedId:s.nestedId,onceOnly:true});if(r==null&&s.end=="lastItem"){let o=pixiVn.NarrationManagerStatic.getCurrentStepTimesCounterData(s.nestedId);if(!o||!o?.usedRandomNumbers){te.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let l=o.usedRandomNumbers[`0-${e.length-1}`];return P(e[l[l.length-1]])}if(r==null){te.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return P(e[r])}}return s}function jn(s){if(s.conditionalStep){let e=pixiVn.createExportableElement(P(s.conditionalStep));if(e?.glueEnabled===void 0&&delete e?.glueEnabled,e?.goNextStep===void 0&&delete e?.goNextStep,e?.end===void 0&&delete e?.end,e?.choices===void 0&&delete e?.choices,e?.dialogue===void 0&&delete e?.dialogue,e?.labelToOpen===void 0&&delete e?.labelToOpen,e?.operations===void 0&&delete e?.operations,e){let t={...s,conditionalStep:void 0,...e};return jn(t)}else pixiVn.storage.getFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY)&&pixiVn.storage.setFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,false);}return s}function tc(s){let e=s.firstItem,t=[];s.secondConditionalItem?.forEach(i=>{if(Array.isArray(i))i.forEach(a=>{let r=P(a);t.push(r);});else {let a=P(i);t.push(a);}});let n=e?[e,...t]:t;if(n.length===0){te.warn("combinateResult toCheck.length === 0");return}if(typeof n[0]=="string")return je.t(n);if(typeof n[0]=="object"){let i=n,a,r=i.map((b,T)=>{b=jn(b);let d=P(b.dialogue)||"";return T===0?(a=P(b.glueEnabled)||false,d):(typeof d=="object"&&"text"in d&&(d=d.character+": "+d.text),a===false&&(d=`
45
45
 
46
- `+d),a=x(b.glueEnabled)||false,d)}),o=x(r[0]),l=typeof o=="object"&&"character"in o?o.character:void 0,u=r.flatMap(b=>{let _;b&&typeof b=="object"&&"text"in b?_=b.text:_=b;let d;return Array.isArray(_)?d=_.map(S=>{let v=x(S);return We.t(`${v}`)}):d=x(_)||"",We.t(d)}),h=i.find(b=>b.end),c=i.find(b=>b.choices),f=false,p=false;i.length>0&&(i[0].glueEnabled&&i[0].goNextStep&&i[0].dialogue===void 0&&pixiVn.storage.setFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,true),f=i[i.length-1].glueEnabled,p=i.reverse().find(b=>!(b.operations&&(!b.dialogue||!b.choices)))?.goNextStep);let m=i.find(b=>b.labelToOpen),y=[];return i.forEach(b=>{b.operations&&y.forEach(_=>{y.push(_);});}),{dialogue:l?{character:l,text:u}:u,end:h?.end,choices:c?.choices,glueEnabled:f,goNextStep:p,labelToOpen:m?.labelToOpen,operations:y}}}function Zh(s){if(!s)return false;if(typeof s!="object"||!("type"in s))return !!s;switch(s.type){case "compare":let e=x(s.leftValue),t=x(s.rightValue);switch(s.operator){case "==":return e===t;case "!=":return e!==t;case "<":return e<t;case "<=":return e<=t;case ">":return e>t;case ">=":return e>=t;case "CONTAINS":return e.toString().includes(t.toString())}break;case "valueCondition":return !!x(s.value);case "union":return tc(s)}return !!s}function ec(s){if(s&&typeof s=="object"&&"type"in s&&s.type==="value"&&s.storageOperationType==="get")switch(s.storageType){case "storage":case "tempstorage":return pixiVn.storage.getVariable(s.key);case "flagStorage":return pixiVn.storage.getFlag(s.key);case "label":return pixiVn.narration.getTimesLabelOpened(s.label);case "choice":return pixiVn.narration.getTimesChoiceMade(s.index);case "logic":return x(s.operation);case "params":let e=pixiVn.storage.getVariable(`${Ut}${pixiVn.narration.openedLabels.length-1}`)||[];if(e&&e.length>s.key)return e[s.key];ee.warn("getValue params not found");return}return s}function tc(s){if(s.unionType==="not")return !x(s.condition);let e=s.unionType==="and";for(let t=0;t<s.conditions.length;t++)if(e=x(s.conditions[t])||false,s.unionType==="and"){if(!e)return false}else if(e)return true;return e}function nc(s){let e=x(s.value),t;switch(e&&typeof e=="object"&&"type"in e?t=x(e):t=e,s.storageType){case "flagStorage":pixiVn.storage.setFlag(s.key,s.value);break;case "storage":pixiVn.storage.setVariable(s.key,t);break;case "tempstorage":pixiVn.storage.setTempVariable(s.key,t);break;case "params":let n=pixiVn.storage.getVariable(`${Ut}${pixiVn.narration.openedLabels.length-1}`)||[];n&&n.length-1>=s.key&&(n[s.key]=t),pixiVn.storage.setTempVariable(`${Ut}${pixiVn.narration.openedLabels.length-1}`,n);break}}function x(s){let e=Yh(s);if(e&&typeof e=="object"&&"type"in e)switch(e.type){case "value":return ec(e);case "arithmetic":case "arithmeticsingle":return ic(e);case "compare":case "valueCondition":case "union":return Zh(e)}return e}function ic(s){let e=x(s.leftValue);switch(s.type){case "arithmetic":let t=x(s.rightValue);switch(s.operator){case "*":return e*t;case "/":return e/t;case "+":return e+t;case "-":return e-t;case "%":return e%t;case "POW":return Math.pow(e,t);case "RANDOM":return pixiVn.narration.getRandomNumber(e,t)}case "arithmeticsingle":switch(s.operator){case "INT":return parseInt(e);case "FLOOR":return Math.floor(e);case "FLOAT":return parseFloat(e)}break}}async function nl(s){let e=x(s);if(e)switch(e.type){case "assets":switch(e.operationType){case "load":await pixiVn.Assets.load(e.aliases);break;case "lazyload":pixiVn.Assets.backgroundLoad(e.aliases);break}break;case "bundle":switch(e.operationType){case "load":await pixiVn.Assets.loadBundle(e.aliases);break;case "lazyload":pixiVn.Assets.backgroundLoadBundle(e.aliases);break}break}}async function ds(s,e){let t=x(s);if(t)switch(t.type){case "sound":switch(t.operationType){case "play":pixiVn.sound.play(t.alias,t.props);break;case "stop":pixiVn.sound.stop(t.alias);break;case "pause":pixiVn.sound.pause(t.alias);break;case "resume":pixiVn.sound.resume(t.alias);break;case "volume":pixiVn.sound.volume(t.alias,t.value);break}break;case "assets":case "bundle":await nl(t);break;case "image":switch(t.operationType){case "show":let o=new pixiVn.ImageSprite(t.props,t.url||t.alias);await cs(o,t);break;case "edit":let l=pixiVn.canvas.find(t.alias);l?t.props&&await l.setMemory({...l.memory,...t.props}):ee.error(`Image with alias ${t.alias} not found.`);break;case "remove":Ln(t);break}break;case "video":switch(t.operationType){case "show":let o=new pixiVn.VideoSprite(t.props,t.url||t.alias);await cs(o,t);break;case "edit":let l=pixiVn.canvas.find(t.alias);l?t.props&&await l.setMemory({...l.memory,...t.props}):ee.error(`Video with alias ${t.alias} not found.`);break;case "remove":Ln(t);break;case "pause":let u=pixiVn.canvas.find(t.alias);u?u.paused=true:ee.error(`Video with alias ${t.alias} not found.`);break;case "resume":let h=pixiVn.canvas.find(t.alias);h?h.paused=false:ee.error(`Video with alias ${t.alias} not found.`);break}break;case "imagecontainer":switch(t.operationType){case "show":let o=new pixiVn.ImageContainer(t.props,t.urls);await cs(o,t);break;case "edit":let l=pixiVn.canvas.find(t.alias);l?t.props&&await l.setMemory({...l.memory,...t.props}):ee.error(`ImageContainer with alias ${t.alias} not found.`);break;case "remove":Ln(t);break}break;case "canvaselement":switch(t.operationType){case "edit":try{let o=pixiVn.canvas.find(t.alias);o?t.props&&(o.memory={...o.memory,...t.props}):ee.error(`Canvas Element with alias ${t.alias} not found.`);}catch(o){ee.error(`There was an error while trying to edit the canvas element with alias ${t.alias}.`,o);}break;case "remove":Ln(t);break}break;case "value":nc(t);break;case "operationtoconvert":if(e){let o="";t.values.forEach(u=>{if(typeof u=="string")o+=u;else {let h=x(u);o+=`${h}`;}});let l=await e(o);l&&await ds(l,e);}break;case "input":switch(t.operationType){case "request":pixiVn.narration.requestInput({type:t.valueType},t.defaultValue);break}break;case "fade":let n=new pixiVn.FadeAlphaTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,n);break;case "move":let i=new pixiVn.MoveTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,i);break;case "rotate":let a=new pixiVn.RotateTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,a);break;case "zoom":let r=new pixiVn.ZoomTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,r);break;case "shake":await pixiVn.shakeEffect(t.alias,t.props,t.priority);break}}async function cs(s,e){if(e.transition)switch(e.transition.type){case "fade":await pixiVn.showWithFade(e.alias,s,e.transition.props,e.transition.priority);break;case "dissolve":await pixiVn.showWithDissolve(e.alias,s,e.transition.props,e.transition.priority);break;case "movein":case "moveout":await pixiVn.moveIn(e.alias,s,e.transition.props,e.transition.priority);break;case "zoomin":case "zoomout":await pixiVn.zoomIn(e.alias,s,e.transition.props,e.transition.priority);break;case "pushin":case "pushout":await pixiVn.pushIn(e.alias,s,e.transition.props,e.transition.priority);break}else await s.load(),pixiVn.canvas.add(e.alias,s);}function Ln(s){if(s.transition)switch(s.transition.type){case "fade":pixiVn.removeWithFade(s.alias,s.transition.props,s.transition.priority);break;case "dissolve":pixiVn.removeWithDissolve(s.alias,s.transition.props,s.transition.priority);break;case "movein":case "moveout":pixiVn.moveOut(s.alias,s.transition.props,s.transition.priority);break;case "zoomin":case "zoomout":pixiVn.zoomOut(s.alias,s.transition.props,s.transition.priority);break;case "pushin":case "pushout":pixiVn.pushOut(s.alias,s.transition.props,s.transition.priority);break}else pixiVn.canvas.remove(s.alias);}var rc=class extends pixiVn.LabelAbstract{constructor(s,e,t,n={}){t||(t={}),t.onLoadingLabel=async()=>{for(let i of e){let a;if(typeof i=="function"?a=i():a=i,a=Wn(a),a.operations){let r=a.operations.map(o=>nl(o));await Promise.all(r);}}},super(s,t),this._steps=e,this.operationStringConvert=n.operationStringConvert,this.skipEmptyDialogs=n.skipEmptyDialogs||false;}_steps;get steps(){return this._steps.map(s=>this.stepConverter(s))}get stepCount(){return this._steps.length}getStepById(s){if(s<0||s>=this._steps.length)return;let e=this._steps[s];return this.stepConverter(e)}operationStringConvert;skipEmptyDialogs=false;getStepSha(s){if(s<0||s>=this.steps.length)return;let e=this._steps[s];return (0, zh.default)(e.toString().toLocaleLowerCase()).toString()}getDialogueText(s){let e="";if(Array.isArray(s)){let t=[];s.forEach(n=>{if(typeof n=="string")t.push(n);else if(n&&typeof n=="object"){let i=x(n);i?(i&&!Array.isArray(i)&&typeof i=="object"&&(i=x(i)||""),Array.isArray(i)?t=t.concat(i):t.push(`${i}`)):t.push(`${n}`);}}),e=t;}else {let t=x(s)||"";t&&!Array.isArray(t)&&typeof t=="object"&&(t=x(t)||""),e=t;}return `${e}`}getDialogue(s){if(s==null)return;let e=x(s);return e==null?"":typeof e=="object"&&"character"in e&&"text"in e?{character:e.character,text:it.t(this.getDialogueText(e.text))}:it.t(this.getDialogueText(e))}getChoices(s){return x(s)?.map(e=>x(e)).filter(e=>e!==void 0)}stepConverter(s){return async e=>{let t=typeof s=="function"?s():s;t=pixiVn.createExportableElement(t),t=Wn(t);let n=this.operationStringConvert?f=>this.operationStringConvert(f,t,e):void 0,{operations:i=[]}=t;for(let f of i)await ds(f,n);let{labelToOpen:a=[]}=t,r=this.getChoices(t.choices),o=x(t.glueEnabled),l=this.getDialogue(t.dialogue),u=[];Array.isArray(a)||(a=[a]),a.forEach(f=>{let p=x(f);p&&u.push(p);});let h=x(t.goNextStep),c=x(t.end);if(r){let f=r.map(p=>{let m="";if(Array.isArray(p.text)){let y=[];p.text.forEach(b=>{if(typeof b=="string")y.push(it.t(b));else if(b&&typeof b=="object"){let _=x(b);_&&!Array.isArray(_)&&typeof _=="object"&&(_=x(_)||""),_&&(Array.isArray(_)?y=y.concat(it.t(_)):y.push(it.t(_)));}}),m=y;}else typeof p.text=="string"&&(m=it.t(p.text));return {label:p.label,text:m,props:p.props,type:p.type,oneTime:p.oneTime,onlyHaveNoChoice:p.onlyHaveNoChoice,autoSelect:p.autoSelect}});pixiVn.narration.choiceMenuOptions=f;}else pixiVn.narration.choiceMenuOptions=void 0;l!==void 0&&(pixiVn.narration.dialogue=l,this.skipEmptyDialogs&&typeof l=="string"&&(l===""||RegExp(/^\s+$/).test(l))&&(h=true)),o?pixiVn.storage.setFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,true):o===false&&pixiVn.storage.setFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,false);for(let f of u){let p=f.label;typeof p=="object"&&(p=x(p)||"");let m=f.params?.map(y=>x(y));e={...e,...f.props},f.type==="jump"?(pixiVn.narration.openedLabels.length>0&&pixiVn.narration.closeCurrentLabel(),pixiVn.storage.setTempVariable(`${Ut}${pixiVn.narration.openedLabels.length}`,m),await pixiVn.narration.callLabel(p,e)):(pixiVn.storage.setTempVariable(`${Ut}${pixiVn.narration.openedLabels.length}`,m),await pixiVn.narration.callLabel(p,e));}c==="game_end"?(pixiVn.narration.closeAllLabels(),await pixiVn.narration.goNext(e,{runNow:true})):c==="label_end"&&pixiVn.narration.closeCurrentLabel(),h&&await pixiVn.narration.goNext(e,{runNow:true});}}};async function il(s,e={}){let{operationStringConvert:t,skipEmptyDialogs:n}=e;if(!Array.isArray(s))if(typeof s=="object"||typeof s=="string")s=[s];else {ee.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let i=s.map(async r=>{if(typeof r=="string")try{r=JSON.parse(r);}catch(o){ee.error("Error parsing imported Pixi'VN JSON",o),r={};}return r}),a=(await Promise.all(i)).map(async r=>{let o=[];if(r.initialOperations){r.initialOperations.forEach(u=>{let h=ds(u,t?c=>t(c,{},{}):void 0);o.push(h);});let l={};[...pixiVn.storage.storage.keys()].forEach((u,h)=>{l[u]=pixiVn.storage.storage.get(u);}),pixiVn.storage.startingStorage=l;}if(r.labels){let l=r.labels;for(let u in l)try{let h=l[u],c=new rc(u,h,void 0,e);pixiVn.RegisteredLabels.add(c);}catch(h){ee.error(`Error creating JSON label ${u}`,h);}}return Promise.all(o)});await Promise.all(a);}var hh=Ch(Xu());var ls="global decl",Ze="___external_value___";function Vn(s,e){if(s.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(s)&&(s=s.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!s.startsWith(".")))return s.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(s)&&s.includes("g-")){let n=s.split("g-");return ko(e)+"_|_"+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(s);)t++,s=s.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(s)&&e){let n=s.substring(1);return ko(e,t)+"_|_"+n.replaceAll(".","_|_")}return s.replaceAll(".","_|_")||ko(e,t).replaceAll(".","_|_")}function ko(s,e=0){let t=s.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var Yu="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Le(s){return s.startsWith("^")&&(s=s.substring(1)),s=s.replaceAll("\\\\",Yu),s=s.replaceAll("\\n",`
47
- `),s=s.replaceAll("\\t"," "),s=s.replaceAll(" "," "),s=s.replaceAll(Yu,"\\\\"),s}var Qu=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],Zu=["+","-","/","*","%","POW","RANDOM"],eh=["INT","FLOOR","FLOAT"],th=["==",">","<",">=","<=","!=","CONTAINS"];function Mt(s,e,t){s=s.map(i=>{if(typeof i=="string"){if(i==="rnd")return "RANDOM";if(i==="?")return "CONTAINS"}return i});let n=[];return s.forEach(i=>{if(typeof i=="object"&&"CNT?"in i)if(new RegExp(/.*\.[0-9]\..*/).test(i["CNT?"])){let a=i["CNT?"].split("."),r=a.pop(),o=a.pop();if(o===void 0||r===void 0){V.error("Error parsing ink file: Conditional statement is not valid",s);return}let l=parseInt(o),u=a.join(".");if(u.includes("^.")){let c=u.split("."),f=c[c.length-1].replaceAll(".","_|_");c.pop(),u=c.join(".")+"."+f,r.includes("c-")&&(u=u+"_|_"+r);}else u=u.replaceAll(".","_|_");let h=Vn(u,e);if(!h)return;n.push({type:"compare",leftValue:nh(h),operator:">=",rightValue:{type:"value",value:l}});}else {let a=Vn(i["CNT?"],e);if(!a)return;n.push(nh(a));}else if(typeof i=="object"&&"VAR?"in i)n.push(Bt(i["VAR?"],t));else if(i==="&&"||i==="||"){if(n.length>=2){let a={type:"union",unionType:i==="&&"?"and":"or",conditions:[n[n.length-2],n[n.length-1]]};n.pop(),n.pop(),n.push(a);}}else if(i==="!")if(n.length===0)V.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"union",unionType:"not",condition:n[n.length-1]};n[n.length-1]=a;}else if(i&&typeof i=="string"&&th.includes(i))if(n.length<2)V.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"compare",operator:i,rightValue:n[n.length-1],leftValue:n[n.length-2]};n.pop(),n.pop(),n.push(a);}else if(i&&typeof i=="string"&&Zu.includes(i))if(n.length<2)V.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"arithmetic",operator:i,rightValue:n[n.length-1],leftValue:n[n.length-2]};n.pop(),n.pop(),n.push(a);}else if(i&&typeof i=="string"&&eh.includes(i)){let a={type:"arithmeticsingle",operator:i,leftValue:n[n.length-1]};n.pop(),n.push(a);}else i&&typeof i=="string"?i.startsWith("^")&&n.push(Le(i)):typeof i=="object"&&"^->"in i?i["^->"].includes("$r")||n.push(i["^->"]):n.push(i);}),n}function nh(s){return {type:"value",storageType:"label",storageOperationType:"get",label:s}}function ih(s,e,t){return Mt(s,e,t)}function Bt(s,e,t="storage"){let n=e.indexOf(s);return n>=0?{type:"value",storageType:"params",storageOperationType:"get",key:n}:{type:"value",storageOperationType:"get",storageType:t,key:s}}function Ro(s,e,t,n="storage"){let i=e.indexOf(s);return i>=0?{type:"value",storageType:"params",storageOperationType:"set",key:i,value:t}:{type:"value",storageOperationType:"set",storageType:n,key:s,value:t}}function us(s,e){e&&(typeof e=="string"?e.startsWith("^")&&s.push(Le(e)):typeof e=="object"&&"type"in e&&e.type!=="value"&&s.push(e));}function Do(s,e,t,n,i=true,a=false){return Xg(s,e,t,n,i,a)}function Xg(s,e,t,n,i,a=false){if(e){if(a)Array.isArray(e)&&e.length>0&&s.push({operations:[{type:"operationtoconvert",values:e}],goNextStep:true});else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type=="value"&&e.storageOperationType==="get"){if(!i&&s.length>0){let r=s[s.length-1];!r.glueEnabled&&!r.operations&&(r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true)),s[s.length-1]=r;}typeof e=="string"?s.push(Yg(Le(e))):s.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")s.push({end:"game_end"});else if(e==="done")s.push({end:"label_end",goNextStep:true});else if(e=="<>")if(s.length>0){let r=s[s.length-1];r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true),s[s.length-1]=r;}else s.push({glueEnabled:true,goNextStep:false});}else if(typeof e=="object"){if("type"in e&&e.type!=="value"){if(!i&&s.length>0){let r=s[s.length-1];!r.glueEnabled&&!r.operations&&(r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true)),s[s.length-1]=r;}s.push({conditionalStep:e});}else if("->"in e){let r=i?void 0:true;if(!i&&s.length>0){let o=s[s.length-1];o.labelToOpen||(o.goNextStep=true),s[s.length-1]=o;}if(e.params&&e.params.length===0&&(e.params=void 0),e.var)s.push({labelToOpen:{label:Bt(e["->"],n),type:"jump",params:e.params},glueEnabled:r});else {let o=Vn(e["->"],t);if(!o)return;s.push({labelToOpen:{label:o,type:"jump",params:e.params},glueEnabled:r});}}"type"in e&&e.type=="value"&&e.storageOperationType==="set"&&(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=Le(e.value)),s.push({goNextStep:true,operations:[e]}));}}}function Yg(s){let e;if(s.includes(": ")){let t=s.split(": "),n=t[0],i=t.slice(1).join(": ");pixiVn.RegisteredCharacters.get(n)&&(e=n,s=i);}return e?{dialogue:{character:e,text:s}}:{dialogue:s}}function Lo(s,e,t,n=true,i=false){return Qg(s,e,t,n,i)}function Qg(s,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"?s.push(Le(e)):s.push(e):typeof e=="object"&&"type"in e&&s.push(e));}function hs(s,e,t){if(s.length===0){V.error("Error parsing ink file: Arithmetic statement is not valid",s);return}let n=Mt(s,e,t);if(n.length===1){let i=n[0];return i&&typeof i=="object"&&"type"in i?{type:"value",storageType:"logic",storageOperationType:"get",operation:i}:i}}function Gt(s,e,t,n="",i,a,r=void 0){let o=[],l="sequential",u=false,h=true;s.forEach(p=>{p==="%"&&(l="loop"),p==="seq"&&(l="random"),p==="MIN"&&(u=true);});let c=s[s.length-1];return Object.keys(c).forEach(p=>{let m=c[p];if(Array.isArray(m)&&m.length>3){m=m.slice(1,m.length-2);let y=[];et(m,n,i,y,e,e,t,$t,r,true,a),y.length===1?o.push(y[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:y});}else Array.isArray(m)&&m.length===3&&(h=false);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:h?"lastItem":void 0,nestedId:r}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:h?"lastItem":void 0,nestedId:r}:{type:"stepswitch",elements:o,choiceType:l}}function Wo(s="",e=""){let t=Array.isArray(s)?s:[s],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function $t(s,e,t,n,i){if(s.length>0){let a={};rh(s,a,i);for(let[r,o]of Object.entries(a)){let l=t+"_|_"+r,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:"jump",oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let h=qo(u,o.conditions,i,t)||u,c=e[e.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),e.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let f=c.choices;f&&Array.isArray(f)?f.push(h):V.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,f),c.choices=f.sort((p,m)=>{try{let y=p.label.split("."),b=y[y.length-1].replaceAll(".","_|_"),_=m.label.split("."),d=_[_.length-1].replaceAll(".","_|_");if(b.includes("c-")&&d.includes("c-")){let S=b.split("c-")[1],v=parseInt(S),g=d.split("c-")[1],E=parseInt(g);return v-E}}catch{}return 0});}else e.push({choices:[h]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function rh(s,e,t,n){let i=[],a="",r="",o=false,l=[];for(let u=0;u<s.length;u++){let h=s[u];if(typeof h=="string")h.startsWith("^")?i.push(Le(h)):Qu.includes(h)&&l.push(h);else if(Array.isArray(h)&&h.includes("visit")){let c=Gt(h,us,(f,p,m)=>{},n,{preDialog:{}},t);i.push(c);}else if(h&&typeof h=="object")if("*"in h&&typeof h["*"]&&typeof h["*"]=="string")h["*"].includes("c")&&(a="c"+h["*"].split("c")[1],h.flg&16&&(o=true));else if("s"in h&&h.s instanceof Array){let c=sh(h.s),f=h.s.includes("<>");c&&(n&&e[n]?(e[n].preDialog={text:c,glue:f},e[n].text=Wo(c,e[n].text)):(i.push(c),r=c));}else "CNT?"in h&&l.push(h);else l.push(h);if(a){e[a]?e[a].text=Wo(i,e[a].text):e[a]={text:i,onetime:o,conditions:l},r&&(e[a].preDialog={text:r,glue:false});let c=s.slice(u+1);rh(c,e,t,a);return}}}function sh(s){for(let e of s)if(typeof e=="string"){if(e.startsWith("^"))return Le(e)}else if(e instanceof Array){let t=sh(e);if(t)return t}}function qo(s,e,t,n,i){if(e.length===0)return;let a=Mt(e,n,t);if(a.length===1){let r={type:"ifelse",condition:a[0],then:s,else:i};return r.else||delete r.else,r}else if(a.length>1){let r={type:"ifelse",condition:{type:"union",unionType:"and",conditions:a},then:s,else:i};return r.else||delete r.else,r}}function ah(s,e,t,n,i,a,r=void 0){if(s.length===0){V.error("Error parsing ink file: Conditional statement is not valid",s);return}let o=[],l=[];if(s.forEach(c=>{Array.isArray(c)?l.push(c):typeof c=="string"&&c==="du"?i.du?o.push(i.du):i.du=o[o.length-1]:(typeof c!="string"||c!=="/ev")&&o.push(c);}),l.length===0){V.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=jo(l[0],e,t,n+"_|_"+"then",i,a,`${r||""}then`),h;return l.length===2?h=jo(l[1],e,t,n+"_|_"+"else",i,a,`${r||""}else`):l.length>2&&(l.shift(),l.push("nop"),l=[{b:l}],h=jo(l,e,t,n+"_|_"+"else",i,a,`${r||""}else`)),i.du=void 0,qo(u,o,a,n,h)}function jo(s,e,t,n,i,a,r=void 0){let o=[];for(let u of s)typeof u=="object"&&"b"in u&&(u.b=u.b.filter(h=>h!==null&&!(typeof h=="object"&&"->"in h&&new RegExp(/.*\.[0-9]/).test(h["->"]))),et(u.b,n,i,o,e,e,t,$t,r,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function et(s,e,t,n=[],i,a,r,o,l=void 0,u=true,h=[]){let c=false,f=[],p=false,m=false,y=[],b=[];if(t.preDialog[e]&&(u=false,i(n,"^"+t.preDialog[e].text,e,h,u,m),t.preDialog[e].glue&&i(n,"<>",e,h,u,m),delete t.preDialog[e]),s.includes("visit")){let d=Gt(s,a,r,e,t,h,l);d&&(!u&&n.length>0&&i(n,"<>",e,h,u,m),i(n,d,e,h,u,m));return}let _=s[0];if(_&&typeof _=="object"&&"temp="in _){for(;s[0]&&typeof s[0]=="object"&&"temp="in s[0];)h.push(s[0]["temp="]),s.shift();h=h.reverse();}if(s.forEach((d,S)=>{if(m){if(typeof d=="string"&&d=="/#"){let v=[];et(b,e,t,v,Lo,Lo,r,o,l,u),i(n,v,e,h,u,m),m=false,b=[];}else b.push(d);return}else if(c)if(Array.isArray(d))f.push(d);else if(d&&typeof d=="object")if("CNT?"in d)S>0&&s[S-1]=="ev"?(p=true,y.push(d)):p?y.push(d):(f.push(d),u=false);else if("VAR="in d||"temp="in d){let v=Ro("VAR="in d?d["VAR="]:d["temp="],h,s[S-1],"VAR="in d?"storage":"tempstorage");if(v.value&&typeof v.value=="string"&&v.value=="/str"&&(v.value=s[S-2]),v.value&&typeof v.value=="object"&&"^->"in v.value&&(v.value=v.value["^->"]),f.length>1){let g=hs(f,e,h);f=[],g&&typeof g=="object"&&"type"in g&&g.type=="value"&&"storageType"in g&&g.storageType=="logic"&&(v.value=g.operation);}(typeof v.key!="string"||!v.key.includes("$r"))&&(i(n,v,e,h,u,m),u=true);}else "VAR?"in d?f.push(d):"^->"in d&&(d["^->"].includes("$r")||f.push(d));else if(typeof d=="string"&&d=="/ev")p&&y.push(d),c=false,f.push(d);else if(typeof d=="string"&&d=="out"){if(f.length>0){let v=f[f.length-1];if(v&&typeof v=="object"&&"VAR?"in v){f.pop();let g=Bt(v["VAR?"],h,"storage");i(n,g,e,h,u,m);}else {let g=[];for(;f.length>0&&f[f.length-1]!="/ev";)g.push(f.pop());g=g.reverse();let E=hs(g,e,h);f=[],E&&typeof E=="object"&&"type"in E&&E.type=="value"&&"storageType"in E&&E.storageType=="logic"?i(n,{storageOperationType:"get",storageType:"logic",operation:E.operation,type:"value"},e,h,u,m):(i(n,"<>",e,h,u,m),E=`^${E}`,i(n,E,e,h,u,m));}u=false;}}else f.push(d);else if(typeof d=="string")if(d.startsWith("^"))i(n,d,e,h,u,m),u=false;else if(d=="ev")c=true;else if(d==`
48
- `)u=true;else if(d=="done"||d=="end")i(n,d,e,h,u,m),u=false;else if(d=="<>")i(n,d,e,h,u,m),u=false;else if(d=="nop"&&p){let v=ah(y,a,r,e,t,h,l);v&&i(n,v,e,h,u,m),p=false,y=[];}else d=="#"&&(m=true);else if(d instanceof Array)if(p)y.push(d);else if(d.length>1&&typeof d[d.length-2]=="object"&&d[d.length-2]&&"c"in d[d.length-2]&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"b"in d[d.length-1]){f.pop();let v=[],g=[];for(;f.length>0&&f[f.length-1]!="/ev";)v.push(f.pop());y=[...y,...v.reverse()],p=true,g.push(d.pop()),g.push(d.pop()),y=[...y,...d],y.push(g);}else if(d.length>1&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"#n"in d[d.length-1]){let v=d.pop();if(!v){V.error("Error parsing ink file: el is undefined");return}let g=v["#n"];delete v["#n"],d.push(v),i(n,{"->":e?e+"_|_"+g:g},e,h,u,m),r({[g]:d},e,t);}else et(d,e,t,n,i,a,r,o,l,u);else if(d&&typeof d=="object")if("->"in d&&typeof d["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->"])){let v=[];f.length>0&&(v=ih(["ev",...f],e,h)),d.params=v,i(n,d,e,h,u,m),u=false;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(f.push(d),u=false);else if("s"in d&&d.s instanceof Array)f.push(d),u=false;else if("CNT?"in d)f.push(d),u=false;else if("VAR="in d||"temp="in d){let v=[],g=Ro("VAR="in d?d["VAR="]:d["temp="],h,void 0,"VAR="in d?"storage":"tempstorage");if(g.key!=="$r"){for(f.pop(),f[f.length-1]=="/ev"&&f.pop();f.length>0&&f[f.length-1]!="/ev";)v.push(f.pop());v=v.reverse(),g.value=hs(v,e,h),f=[],(g.value!==void 0||g.value!==null)&&i(n,g,e,h,u,m),u=false;}}else r(d,e,t);}),o(f,n,e,t,h),e.includes("_|_")&&n.length==2){let d=n[0],S=n[1];d&&S&&typeof d=="object"&&"dialogue"in d&&typeof S=="object"&&"labelToOpen"in S&&d.dialogue==" "&&S.labelToOpen&&(n.shift(),delete S.glueEnabled,n[0]=S);}}function oh(s){try{let e={};return lh(s,e),e}catch(e){V.error("Error parsing ink file",e);}}function lh(s,e,t={externalSwitch:void 0}){for(let n of s)if(n)if(n instanceof Array)if(n.includes("visit")){let i=Gt(n,us,(a,r,o)=>{},"",{preDialog:{}},[]);i&&(t.externalSwitch=i);}else lh(n,e,t);else typeof n=="object"&&(n&&"VAR="in n&&t.externalSwitch&&(e[Ze]||(e[Ze]=[]),e[Ze].push({operations:[{type:"value",value:t.externalSwitch,key:n["VAR="],storageType:"storage",storageOperationType:"set"}]})),uh(n,e));}function uh(s,e,t="",n={preDialog:{}}){if(s!==null){for(let[i,a]of Object.entries(s))if(a instanceof Array){let r=[],o={},l=(t?t+"_|_":"")+i;et(a,l,n,r,Do,Do,(u,h,c)=>{uh(u,o,h,c);},$t);for(let[u,h]of Object.entries(o))e[u]=h;r.length>0&&(e[l]=r);}}}function Mo(s){let e={},t=Zg(s),n;try{n=JSON.parse(t);}catch{V.error("Error parsing ink file");return}if(e.labels=oh(n.root),e.labels&&ls in e.labels){let i=e.labels[ls];delete e.labels[ls],i.forEach(a=>{a.operations&&(e.initialOperations=e.initialOperations?[...e.initialOperations,...a.operations]:[...a.operations]);});}if(e.labels&&Ze in e.labels){let i=e.labels[Ze];delete e.labels[Ze],i.forEach(a=>{a.operations&&(e.initialOperations=e.initialOperations?[...e.initialOperations,...a.operations]:[...a.operations]);});}return e}function Zg(s){try{return new hh.Compiler(s).Compile().ToJson()||""}catch(e){return V.error("Error compiling ink file",e),""}}async function em(s){Array.isArray(s)||(s=[s]);let e=s.map(async t=>{let n=Mo(t);n&&await il(n,{operationStringConvert:nt.generateOrRunOperationFromHashtagScript,skipEmptyDialogs:true});});return await Promise.all(e)}function tm(s){We.afterToTranslate=e=>Bo(e,s);}function nm(s){We.beforeToTranslate=e=>Bo(e,s);}function Bo(s,e){let t=s.match(/\[([^\]]+)\]/);if(t){let n=t[1],i=e(n);return i&&(s=s.replaceAll(t[0],i)),Bo(s,e)}return s}function im(s){We.translate=s;}function rm(s,e={},t={}){let n=[];return Array.isArray(s)?n=s:s.labels&&Object.values(s.labels).forEach(i=>{n=n.concat(i);}),We.generateJsonTranslation(n,e,t)}exports.convertInkText=Mo;exports.generateJsonInkTranslation=rm;exports.importInkText=em;exports.onInkHashtagScript=yh;exports.onInkTranslate=im;exports.onReplaceTextAfterTranslation=tm;exports.onReplaceTextBeforeTranslation=nm;
46
+ `+d),a=P(b.glueEnabled)||false,d)}),o=P(r[0]),l=typeof o=="object"&&"character"in o?o.character:void 0,u=r.flatMap(b=>{let T;b&&typeof b=="object"&&"text"in b?T=b.text:T=b;let d;return Array.isArray(T)?d=T.map(S=>{let v=P(S);return je.t(`${v}`)}):d=P(T)||"",je.t(d)}),h=i.find(b=>b.end),c=i.find(b=>b.choices),f=false,p=false;i.length>0&&(i[0].glueEnabled&&i[0].goNextStep&&i[0].dialogue===void 0&&pixiVn.storage.setFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,true),f=i[i.length-1].glueEnabled,p=i.reverse().find(b=>!(b.operations&&(!b.dialogue||!b.choices)))?.goNextStep);let g=i.find(b=>b.labelToOpen),y=[];return i.forEach(b=>{b.operations&&y.forEach(T=>{y.push(T);});}),{dialogue:l?{character:l,text:u}:u,end:h?.end,choices:c?.choices,glueEnabled:f,goNextStep:p,labelToOpen:g?.labelToOpen,operations:y}}}function nc(s){if(!s)return false;if(typeof s!="object"||!("type"in s))return !!s;switch(s.type){case "compare":let e=P(s.leftValue),t=P(s.rightValue);switch(s.operator){case "==":return e===t;case "!=":return e!==t;case "<":return e<t;case "<=":return e<=t;case ">":return e>t;case ">=":return e>=t;case "CONTAINS":return e.toString().includes(t.toString())}break;case "valueCondition":return !!P(s.value);case "union":return rc(s)}return !!s}function ic(s){if(s&&typeof s=="object"&&"type"in s&&s.type==="value"&&s.storageOperationType==="get")switch(s.storageType){case "storage":case "tempstorage":return pixiVn.storage.getVariable(s.key);case "flagStorage":return pixiVn.storage.getFlag(s.key);case "label":return pixiVn.narration.getTimesLabelOpened(s.label);case "choice":return pixiVn.narration.getTimesChoiceMade(s.index);case "logic":return P(s.operation);case "params":let e=pixiVn.storage.getVariable(`${zt}${pixiVn.narration.openedLabels.length-1}`)||[];if(e&&e.length>s.key)return e[s.key];te.warn("getValue params not found");return}return s}function rc(s){if(s.unionType==="not")return !P(s.condition);let e=s.unionType==="and";for(let t=0;t<s.conditions.length;t++)if(e=P(s.conditions[t])||false,s.unionType==="and"){if(!e)return false}else if(e)return true;return e}function sc(s){let e=P(s.value),t;switch(e&&typeof e=="object"&&"type"in e?t=P(e):t=e,s.storageType){case "flagStorage":pixiVn.storage.setFlag(s.key,s.value);break;case "storage":pixiVn.storage.setVariable(s.key,t);break;case "tempstorage":pixiVn.storage.setTempVariable(s.key,t);break;case "params":let n=pixiVn.storage.getVariable(`${zt}${pixiVn.narration.openedLabels.length-1}`)||[];n&&n.length-1>=s.key&&(n[s.key]=t),pixiVn.storage.setTempVariable(`${zt}${pixiVn.narration.openedLabels.length-1}`,n);break}}function P(s){let e=ec(s);if(e&&typeof e=="object"&&"type"in e)switch(e.type){case "value":return ic(e);case "arithmetic":case "arithmeticsingle":return ac(e);case "compare":case "valueCondition":case "union":return nc(e)}return e}function ac(s){let e=P(s.leftValue);switch(s.type){case "arithmetic":let t=P(s.rightValue);switch(s.operator){case "*":return e*t;case "/":return e/t;case "+":return e+t;case "-":return e-t;case "%":return e%t;case "POW":return Math.pow(e,t);case "RANDOM":return pixiVn.narration.getRandomNumber(e,t)}case "arithmeticsingle":switch(s.operator){case "INT":return parseInt(e);case "FLOOR":return Math.floor(e);case "FLOAT":return parseFloat(e)}break}}async function rl(s){let e=P(s);if(e)switch(e.type){case "assets":switch(e.operationType){case "load":await pixiVn.Assets.load(e.aliases);break;case "lazyload":pixiVn.Assets.backgroundLoad(e.aliases);break}break;case "bundle":switch(e.operationType){case "load":await pixiVn.Assets.loadBundle(e.aliases);break;case "lazyload":pixiVn.Assets.backgroundLoadBundle(e.aliases);break}break}}async function gs(s,e){let t=P(s);if(t)switch(t.type){case "sound":switch(t.operationType){case "play":pixiVn.sound.play(t.alias,t.props);break;case "stop":pixiVn.sound.stop(t.alias);break;case "pause":pixiVn.sound.pause(t.alias);break;case "resume":pixiVn.sound.resume(t.alias);break;case "volume":pixiVn.sound.volume(t.alias,t.value);break}break;case "assets":case "bundle":await rl(t);break;case "image":switch(t.operationType){case "show":let o=new pixiVn.ImageSprite(t.props,t.url||t.alias);await ps(o,t);break;case "edit":let l=pixiVn.canvas.find(t.alias);l?t.props&&await l.setMemory({...l.memory,...t.props}):te.error(`Image with alias ${t.alias} not found.`);break;case "remove":qn(t);break}break;case "video":switch(t.operationType){case "show":let o=new pixiVn.VideoSprite(t.props,t.url||t.alias);await ps(o,t);break;case "edit":let l=pixiVn.canvas.find(t.alias);l?t.props&&await l.setMemory({...l.memory,...t.props}):te.error(`Video with alias ${t.alias} not found.`);break;case "remove":qn(t);break;case "pause":let u=pixiVn.canvas.find(t.alias);u?u.paused=true:te.error(`Video with alias ${t.alias} not found.`);break;case "resume":let h=pixiVn.canvas.find(t.alias);h?h.paused=false:te.error(`Video with alias ${t.alias} not found.`);break}break;case "imagecontainer":switch(t.operationType){case "show":let o=new pixiVn.ImageContainer(t.props,t.urls);await ps(o,t);break;case "edit":let l=pixiVn.canvas.find(t.alias);l?t.props&&await l.setMemory({...l.memory,...t.props}):te.error(`ImageContainer with alias ${t.alias} not found.`);break;case "remove":qn(t);break}break;case "canvaselement":switch(t.operationType){case "edit":try{let o=pixiVn.canvas.find(t.alias);o?t.props&&(o.memory={...o.memory,...t.props}):te.error(`Canvas Element with alias ${t.alias} not found.`);}catch(o){te.error(`There was an error while trying to edit the canvas element with alias ${t.alias}.`,o);}break;case "remove":qn(t);break}break;case "value":sc(t);break;case "operationtoconvert":if(e){let o="";t.values.forEach(u=>{if(typeof u=="string")o+=u;else {let h=P(u);o+=`${h}`;}});let l=await e(o);l&&await gs(l,e);}break;case "input":switch(t.operationType){case "request":pixiVn.narration.requestInput({type:t.valueType},t.defaultValue);break}break;case "fade":let n=new pixiVn.FadeAlphaTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,n);break;case "move":let i=new pixiVn.MoveTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,i);break;case "rotate":let a=new pixiVn.RotateTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,a);break;case "zoom":let r=new pixiVn.ZoomTicker(t.props,t.duration,t.priority);pixiVn.canvas.addTicker(t.alias,r);break;case "shake":await pixiVn.shakeEffect(t.alias,t.props,t.priority);break}}async function ps(s,e){if(e.transition)switch(e.transition.type){case "fade":await pixiVn.showWithFade(e.alias,s,e.transition.props,e.transition.priority);break;case "dissolve":await pixiVn.showWithDissolve(e.alias,s,e.transition.props,e.transition.priority);break;case "movein":case "moveout":await pixiVn.moveIn(e.alias,s,e.transition.props,e.transition.priority);break;case "zoomin":case "zoomout":await pixiVn.zoomIn(e.alias,s,e.transition.props,e.transition.priority);break;case "pushin":case "pushout":await pixiVn.pushIn(e.alias,s,e.transition.props,e.transition.priority);break}else await s.load(),pixiVn.canvas.add(e.alias,s);}function qn(s){if(s.transition)switch(s.transition.type){case "fade":pixiVn.removeWithFade(s.alias,s.transition.props,s.transition.priority);break;case "dissolve":pixiVn.removeWithDissolve(s.alias,s.transition.props,s.transition.priority);break;case "movein":case "moveout":pixiVn.moveOut(s.alias,s.transition.props,s.transition.priority);break;case "zoomin":case "zoomout":pixiVn.zoomOut(s.alias,s.transition.props,s.transition.priority);break;case "pushin":case "pushout":pixiVn.pushOut(s.alias,s.transition.props,s.transition.priority);break}else pixiVn.canvas.remove(s.alias);}var oc=class extends pixiVn.LabelAbstract{constructor(e,t,n,i={}){n||(n={}),n.onLoadingLabel=async()=>{for(let a of t){let r;if(typeof a=="function"?r=a():r=a,r=jn(r),r.operations){let o=r.operations.map(l=>rl(l));await Promise.all(o);}}};super(e,n);qe(this,"_steps");qe(this,"operationStringConvert");qe(this,"skipEmptyDialogs",false);this._steps=t,this.operationStringConvert=i.operationStringConvert,this.skipEmptyDialogs=i.skipEmptyDialogs||false;}get steps(){return this._steps.map(e=>this.stepConverter(e))}get stepCount(){return this._steps.length}getStepById(e){if(e<0||e>=this._steps.length)return;let t=this._steps[e];return this.stepConverter(t)}getStepSha(e){if(e<0||e>=this.steps.length)return;let t=this._steps[e];return (0, Qh.default)(t.toString().toLocaleLowerCase()).toString()}getDialogueText(e){let t="";if(Array.isArray(e)){let n=[];e.forEach(i=>{if(typeof i=="string")n.push(i);else if(i&&typeof i=="object"){let a=P(i);a?(a&&!Array.isArray(a)&&typeof a=="object"&&(a=P(a)||""),Array.isArray(a)?n=n.concat(a):n.push(`${a}`)):n.push(`${i}`);}}),t=n;}else {let n=P(e)||"";n&&!Array.isArray(n)&&typeof n=="object"&&(n=P(n)||""),t=n;}return `${t}`}getDialogue(e){if(e==null)return;let t=P(e);return t==null?"":typeof t=="object"&&"character"in t&&"text"in t?{character:t.character,text:st.t(this.getDialogueText(t.text))}:st.t(this.getDialogueText(t))}getChoices(e){return P(e)?.map(t=>P(t)).filter(t=>t!==void 0)}stepConverter(e){return async t=>{let n=typeof e=="function"?e():e;n=pixiVn.createExportableElement(n),n=jn(n);let i=this.operationStringConvert?p=>this.operationStringConvert(p,n,t):void 0,{operations:a=[]}=n;for(let p of a)await gs(p,i);let{labelToOpen:r=[]}=n,o=this.getChoices(n.choices),l=P(n.glueEnabled),u=this.getDialogue(n.dialogue),h=[];Array.isArray(r)||(r=[r]),r.forEach(p=>{let g=P(p);g&&h.push(g);});let c=P(n.goNextStep),f=P(n.end);if(o){let p=o.map(g=>{let y="";if(Array.isArray(g.text)){let b=[];g.text.forEach(T=>{if(typeof T=="string")b.push(st.t(T));else if(T&&typeof T=="object"){let d=P(T);d&&!Array.isArray(d)&&typeof d=="object"&&(d=P(d)||""),d&&(Array.isArray(d)?b=b.concat(st.t(d)):b.push(st.t(d)));}}),y=b;}else typeof g.text=="string"&&(y=st.t(g.text));return {label:g.label,text:y,props:g.props,type:g.type,oneTime:g.oneTime,onlyHaveNoChoice:g.onlyHaveNoChoice,autoSelect:g.autoSelect}});pixiVn.narration.choiceMenuOptions=p;}else pixiVn.narration.choiceMenuOptions=void 0;u!==void 0&&(pixiVn.narration.dialogue=u,this.skipEmptyDialogs&&typeof u=="string"&&(u===""||RegExp(/^\s+$/).test(u))&&(c=true)),l?pixiVn.storage.setFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,true):l===false&&pixiVn.storage.setFlag(pixiVn.SYSTEM_RESERVED_STORAGE_KEYS.ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY,false);for(let p of h){let g=p.label;typeof g=="object"&&(g=P(g)||"");let y=p.params?.map(b=>P(b));t={...t,...p.props},p.type==="jump"?(pixiVn.narration.openedLabels.length>0&&pixiVn.narration.closeCurrentLabel(),pixiVn.storage.setTempVariable(`${zt}${pixiVn.narration.openedLabels.length}`,y),await pixiVn.narration.callLabel(g,t)):(pixiVn.storage.setTempVariable(`${zt}${pixiVn.narration.openedLabels.length}`,y),await pixiVn.narration.callLabel(g,t));}f==="game_end"?(pixiVn.narration.closeAllLabels(),await pixiVn.narration.goNext(t,{runNow:true})):f==="label_end"&&pixiVn.narration.closeCurrentLabel(),c&&await pixiVn.narration.goNext(t,{runNow:true});}}};async function sl(s,e={}){let{operationStringConvert:t,skipEmptyDialogs:n}=e;if(!Array.isArray(s))if(typeof s=="object"||typeof s=="string")s=[s];else {te.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let i=s.map(async r=>{if(typeof r=="string")try{r=JSON.parse(r);}catch(o){te.error("Error parsing imported Pixi'VN JSON",o),r={};}return r}),a=(await Promise.all(i)).map(async r=>{let o=[];if(r.initialOperations){r.initialOperations.forEach(u=>{let h=gs(u,t?c=>t(c,{},{}):void 0);o.push(h);});let l={};[...pixiVn.storage.storage.keys()].forEach((u,h)=>{l[u]=pixiVn.storage.storage.get(u);}),pixiVn.storage.startingStorage=l;}if(r.labels){let l=r.labels;for(let u in l)try{let h=l[u],c=new oc(u,h,void 0,e);pixiVn.RegisteredLabels.add(c);}catch(h){te.error(`Error creating JSON label ${u}`,h);}}return Promise.all(o)});await Promise.all(a);}var dh=Sh(Qu());var hs="global decl",tt="___external_value___";function Rn(s,e){if(s.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(s)&&(s=s.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!s.startsWith(".")))return s.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(s)&&s.includes("g-")){let n=s.split("g-");return Lo(e)+"_|_"+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(s);)t++,s=s.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(s)&&e){let n=s.substring(1);return Lo(e,t)+"_|_"+n.replaceAll(".","_|_")}return s.replaceAll(".","_|_")||Lo(e,t).replaceAll(".","_|_")}function Lo(s,e=0){let t=s.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var Zu="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function We(s){return s.startsWith("^")&&(s=s.substring(1)),s=s.replaceAll("\\\\",Zu),s=s.replaceAll("\\n",`
47
+ `),s=s.replaceAll("\\t"," "),s=s.replaceAll(" "," "),s=s.replaceAll(Zu,"\\\\"),s}var eh=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],th=["+","-","/","*","%","POW","RANDOM"],nh=["INT","FLOOR","FLOAT"],ih=["==",">","<",">=","<=","!=","CONTAINS"];function Gt(s,e,t){s=s.map(i=>{if(typeof i=="string"){if(i==="rnd")return "RANDOM";if(i==="?")return "CONTAINS"}return i});let n=[];return s.forEach(i=>{if(typeof i=="object"&&"CNT?"in i)if(new RegExp(/.*\.[0-9]\..*/).test(i["CNT?"])){let a=i["CNT?"].split("."),r=a.pop(),o=a.pop();if(o===void 0||r===void 0){V.error("Error parsing ink file: Conditional statement is not valid",s);return}let l=parseInt(o),u=a.join(".");if(u.includes("^.")){let c=u.split("."),f=c[c.length-1].replaceAll(".","_|_");c.pop(),u=c.join(".")+"."+f,r.includes("c-")&&(u=u+"_|_"+r);}else u=u.replaceAll(".","_|_");let h=Rn(u,e);if(!h)return;n.push({type:"compare",leftValue:rh(h),operator:">=",rightValue:{type:"value",value:l}});}else {let a=Rn(i["CNT?"],e);if(!a)return;n.push(rh(a));}else if(typeof i=="object"&&"VAR?"in i)n.push($t(i["VAR?"],t));else if(i==="&&"||i==="||"){if(n.length>=2){let a={type:"union",unionType:i==="&&"?"and":"or",conditions:[n[n.length-2],n[n.length-1]]};n.pop(),n.pop(),n.push(a);}}else if(i==="!")if(n.length===0)V.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"union",unionType:"not",condition:n[n.length-1]};n[n.length-1]=a;}else if(i&&typeof i=="string"&&ih.includes(i))if(n.length<2)V.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"compare",operator:i,rightValue:n[n.length-1],leftValue:n[n.length-2]};n.pop(),n.pop(),n.push(a);}else if(i&&typeof i=="string"&&th.includes(i))if(n.length<2)V.error("Error parsing ink file: Conditional statement is not valid",s);else {let a={type:"arithmetic",operator:i,rightValue:n[n.length-1],leftValue:n[n.length-2]};n.pop(),n.pop(),n.push(a);}else if(i&&typeof i=="string"&&nh.includes(i)){let a={type:"arithmeticsingle",operator:i,leftValue:n[n.length-1]};n.pop(),n.push(a);}else i&&typeof i=="string"?i.startsWith("^")&&n.push(We(i)):typeof i=="object"&&"^->"in i?i["^->"].includes("$r")||n.push(i["^->"]):n.push(i);}),n}function rh(s){return {type:"value",storageType:"label",storageOperationType:"get",label:s}}function sh(s,e,t){return Gt(s,e,t)}function $t(s,e,t="storage"){let n=e.indexOf(s);return n>=0?{type:"value",storageType:"params",storageOperationType:"get",key:n}:{type:"value",storageOperationType:"get",storageType:t,key:s}}function Wo(s,e,t,n="storage"){let i=e.indexOf(s);return i>=0?{type:"value",storageType:"params",storageOperationType:"set",key:i,value:t}:{type:"value",storageOperationType:"set",storageType:n,key:s,value:t}}function cs(s,e){e&&(typeof e=="string"?e.startsWith("^")&&s.push(We(e)):typeof e=="object"&&"type"in e&&e.type!=="value"&&s.push(e));}function qo(s,e,t,n,i=true,a=false){return Zg(s,e,t,n,i,a)}function Zg(s,e,t,n,i,a=false){if(e){if(a)Array.isArray(e)&&e.length>0&&s.push({operations:[{type:"operationtoconvert",values:e}],goNextStep:true});else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type=="value"&&e.storageOperationType==="get"){if(!i&&s.length>0){let r=s[s.length-1];!r.glueEnabled&&!r.operations&&(r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true)),s[s.length-1]=r;}typeof e=="string"?s.push(em(We(e))):s.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")s.push({end:"game_end"});else if(e==="done")s.push({end:"label_end",goNextStep:true});else if(e=="<>")if(s.length>0){let r=s[s.length-1];r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true),s[s.length-1]=r;}else s.push({glueEnabled:true,goNextStep:false});}else if(typeof e=="object"){if("type"in e&&e.type!=="value"){if(!i&&s.length>0){let r=s[s.length-1];!r.glueEnabled&&!r.operations&&(r.glueEnabled=true,r.labelToOpen||(r.goNextStep=true)),s[s.length-1]=r;}s.push({conditionalStep:e});}else if("->"in e){let r=i?void 0:true;if(!i&&s.length>0){let o=s[s.length-1];o.labelToOpen||(o.goNextStep=true),s[s.length-1]=o;}if(e.params&&e.params.length===0&&(e.params=void 0),e.var)s.push({labelToOpen:{label:$t(e["->"],n),type:"jump",params:e.params},glueEnabled:r});else {let o=Rn(e["->"],t);if(!o)return;s.push({labelToOpen:{label:o,type:"jump",params:e.params},glueEnabled:r});}}"type"in e&&e.type=="value"&&e.storageOperationType==="set"&&(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=We(e.value)),s.push({goNextStep:true,operations:[e]}));}}}function em(s){let e;if(s.includes(": ")){let t=s.split(": "),n=t[0],i=t.slice(1).join(": ");pixiVn.RegisteredCharacters.get(n)&&(e=n,s=i);}return e?{dialogue:{character:e,text:s}}:{dialogue:s}}function jo(s,e,t,n=true,i=false){return tm(s,e,t,n,i)}function tm(s,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"?s.push(We(e)):s.push(e):typeof e=="object"&&"type"in e&&s.push(e));}function ds(s,e,t){if(s.length===0){V.error("Error parsing ink file: Arithmetic statement is not valid",s);return}let n=Gt(s,e,t);if(n.length===1){let i=n[0];return i&&typeof i=="object"&&"type"in i?{type:"value",storageType:"logic",storageOperationType:"get",operation:i}:i}}function Jt(s,e,t,n="",i,a,r=void 0){let o=[],l="sequential",u=false,h=true;s.forEach(p=>{p==="%"&&(l="loop"),p==="seq"&&(l="random"),p==="MIN"&&(u=true);});let c=s[s.length-1];return Object.keys(c).forEach(p=>{let g=c[p];if(Array.isArray(g)&&g.length>3){g=g.slice(1,g.length-2);let y=[];nt(g,n,i,y,e,e,t,Ht,r,true,a),y.length===1?o.push(y[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:y});}else Array.isArray(g)&&g.length===3&&(h=false);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:h?"lastItem":void 0,nestedId:r}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:h?"lastItem":void 0,nestedId:r}:{type:"stepswitch",elements:o,choiceType:l}}function Mo(s="",e=""){let t=Array.isArray(s)?s:[s],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function Ht(s,e,t,n,i){if(s.length>0){let a={};ah(s,a,i);for(let[r,o]of Object.entries(a)){let l=t+"_|_"+r,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:"jump",oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let h=Bo(u,o.conditions,i,t)||u,c=e[e.length-1];if(typeof c=="object"&&c&&"type"in c&&(c={conditionalStep:c}),e.length>0&&typeof c=="object"&&c&&"choices"in c&&c.choices){let f=c.choices;f&&Array.isArray(f)?f.push(h):V.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,f),c.choices=f.sort((p,g)=>{try{let y=p.label.split("."),b=y[y.length-1].replaceAll(".","_|_"),T=g.label.split("."),d=T[T.length-1].replaceAll(".","_|_");if(b.includes("c-")&&d.includes("c-")){let S=b.split("c-")[1],v=parseInt(S),m=d.split("c-")[1],_=parseInt(m);return v-_}}catch{}return 0});}else e.push({choices:[h]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function ah(s,e,t,n){let i=[],a="",r="",o=false,l=[];for(let u=0;u<s.length;u++){let h=s[u];if(typeof h=="string")h.startsWith("^")?i.push(We(h)):eh.includes(h)&&l.push(h);else if(Array.isArray(h)&&h.includes("visit")){let c=Jt(h,cs,(f,p,g)=>{},n,{preDialog:{}},t);i.push(c);}else if(h&&typeof h=="object")if("*"in h&&typeof h["*"]&&typeof h["*"]=="string")h["*"].includes("c")&&(a="c"+h["*"].split("c")[1],h.flg&16&&(o=true));else if("s"in h&&h.s instanceof Array){let c=oh(h.s),f=h.s.includes("<>");c&&(n&&e[n]?(e[n].preDialog={text:c,glue:f},e[n].text=Mo(c,e[n].text)):(i.push(c),r=c));}else "CNT?"in h&&l.push(h);else l.push(h);if(a){e[a]?e[a].text=Mo(i,e[a].text):e[a]={text:i,onetime:o,conditions:l},r&&(e[a].preDialog={text:r,glue:false});let c=s.slice(u+1);ah(c,e,t,a);return}}}function oh(s){for(let e of s)if(typeof e=="string"){if(e.startsWith("^"))return We(e)}else if(e instanceof Array){let t=oh(e);if(t)return t}}function Bo(s,e,t,n,i){if(e.length===0)return;let a=Gt(e,n,t);if(a.length===1){let r={type:"ifelse",condition:a[0],then:s,else:i};return r.else||delete r.else,r}else if(a.length>1){let r={type:"ifelse",condition:{type:"union",unionType:"and",conditions:a},then:s,else:i};return r.else||delete r.else,r}}function lh(s,e,t,n,i,a,r=void 0){if(s.length===0){V.error("Error parsing ink file: Conditional statement is not valid",s);return}let o=[],l=[];if(s.forEach(c=>{Array.isArray(c)?l.push(c):typeof c=="string"&&c==="du"?i.du?o.push(i.du):i.du=o[o.length-1]:(typeof c!="string"||c!=="/ev")&&o.push(c);}),l.length===0){V.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=Go(l[0],e,t,n+"_|_"+"then",i,a,`${r||""}then`),h;return l.length===2?h=Go(l[1],e,t,n+"_|_"+"else",i,a,`${r||""}else`):l.length>2&&(l.shift(),l.push("nop"),l=[{b:l}],h=Go(l,e,t,n+"_|_"+"else",i,a,`${r||""}else`)),i.du=void 0,Bo(u,o,a,n,h)}function Go(s,e,t,n,i,a,r=void 0){let o=[];for(let u of s)typeof u=="object"&&"b"in u&&(u.b=u.b.filter(h=>h!==null&&!(typeof h=="object"&&"->"in h&&new RegExp(/.*\.[0-9]/).test(h["->"]))),nt(u.b,n,i,o,e,e,t,Ht,r,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function nt(s,e,t,n=[],i,a,r,o,l=void 0,u=true,h=[]){let c=false,f=[],p=false,g=false,y=[],b=[];if(t.preDialog[e]&&(u=false,i(n,"^"+t.preDialog[e].text,e,h,u,g),t.preDialog[e].glue&&i(n,"<>",e,h,u,g),delete t.preDialog[e]),s.includes("visit")){let d=Jt(s,a,r,e,t,h,l);d&&(!u&&n.length>0&&i(n,"<>",e,h,u,g),i(n,d,e,h,u,g));return}let T=s[0];if(T&&typeof T=="object"&&"temp="in T){for(;s[0]&&typeof s[0]=="object"&&"temp="in s[0];)h.push(s[0]["temp="]),s.shift();h=h.reverse();}if(s.forEach((d,S)=>{if(g){if(typeof d=="string"&&d=="/#"){let v=[];nt(b,e,t,v,jo,jo,r,o,l,u),i(n,v,e,h,u,g),g=false,b=[];}else b.push(d);return}else if(c)if(Array.isArray(d))f.push(d);else if(d&&typeof d=="object")if("CNT?"in d)S>0&&s[S-1]=="ev"?(p=true,y.push(d)):p?y.push(d):(f.push(d),u=false);else if("VAR="in d||"temp="in d){let v=Wo("VAR="in d?d["VAR="]:d["temp="],h,s[S-1],"VAR="in d?"storage":"tempstorage");if(v.value&&typeof v.value=="string"&&v.value=="/str"&&(v.value=s[S-2]),v.value&&typeof v.value=="object"&&"^->"in v.value&&(v.value=v.value["^->"]),f.length>1){let m=ds(f,e,h);f=[],m&&typeof m=="object"&&"type"in m&&m.type=="value"&&"storageType"in m&&m.storageType=="logic"&&(v.value=m.operation);}(typeof v.key!="string"||!v.key.includes("$r"))&&(i(n,v,e,h,u,g),u=true);}else "VAR?"in d?f.push(d):"^->"in d&&(d["^->"].includes("$r")||f.push(d));else if(typeof d=="string"&&d=="/ev")p&&y.push(d),c=false,f.push(d);else if(typeof d=="string"&&d=="out"){if(f.length>0){let v=f[f.length-1];if(v&&typeof v=="object"&&"VAR?"in v){f.pop();let m=$t(v["VAR?"],h,"storage");i(n,m,e,h,u,g);}else {let m=[];for(;f.length>0&&f[f.length-1]!="/ev";)m.push(f.pop());m=m.reverse();let _=ds(m,e,h);f=[],_&&typeof _=="object"&&"type"in _&&_.type=="value"&&"storageType"in _&&_.storageType=="logic"?i(n,{storageOperationType:"get",storageType:"logic",operation:_.operation,type:"value"},e,h,u,g):(i(n,"<>",e,h,u,g),_=`^${_}`,i(n,_,e,h,u,g));}u=false;}}else f.push(d);else if(typeof d=="string")if(d.startsWith("^"))i(n,d,e,h,u,g),u=false;else if(d=="ev")c=true;else if(d==`
48
+ `)u=true;else if(d=="done"||d=="end")i(n,d,e,h,u,g),u=false;else if(d=="<>")i(n,d,e,h,u,g),u=false;else if(d=="nop"&&p){let v=lh(y,a,r,e,t,h,l);v&&i(n,v,e,h,u,g),p=false,y=[];}else d=="#"&&(g=true);else if(d instanceof Array)if(p)y.push(d);else if(d.length>1&&typeof d[d.length-2]=="object"&&d[d.length-2]&&"c"in d[d.length-2]&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"b"in d[d.length-1]){f.pop();let v=[],m=[];for(;f.length>0&&f[f.length-1]!="/ev";)v.push(f.pop());y=[...y,...v.reverse()],p=true,m.push(d.pop()),m.push(d.pop()),y=[...y,...d],y.push(m);}else if(d.length>1&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"#n"in d[d.length-1]){let v=d.pop();if(!v){V.error("Error parsing ink file: el is undefined");return}let m=v["#n"];delete v["#n"],d.push(v),i(n,{"->":e?e+"_|_"+m:m},e,h,u,g),r({[m]:d},e,t);}else nt(d,e,t,n,i,a,r,o,l,u);else if(d&&typeof d=="object")if("->"in d&&typeof d["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->"])){let v=[];f.length>0&&(v=sh(["ev",...f],e,h)),d.params=v,i(n,d,e,h,u,g),u=false;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(f.push(d),u=false);else if("s"in d&&d.s instanceof Array)f.push(d),u=false;else if("CNT?"in d)f.push(d),u=false;else if("VAR="in d||"temp="in d){let v=[],m=Wo("VAR="in d?d["VAR="]:d["temp="],h,void 0,"VAR="in d?"storage":"tempstorage");if(m.key!=="$r"){for(f.pop(),f[f.length-1]=="/ev"&&f.pop();f.length>0&&f[f.length-1]!="/ev";)v.push(f.pop());v=v.reverse(),m.value=ds(v,e,h),f=[],(m.value!==void 0||m.value!==null)&&i(n,m,e,h,u,g),u=false;}}else r(d,e,t);}),o(f,n,e,t,h),e.includes("_|_")&&n.length==2){let d=n[0],S=n[1];d&&S&&typeof d=="object"&&"dialogue"in d&&typeof S=="object"&&"labelToOpen"in S&&d.dialogue==" "&&S.labelToOpen&&(n.shift(),delete S.glueEnabled,n[0]=S);}}function uh(s){try{let e={};return hh(s,e),e}catch(e){V.error("Error parsing ink file",e);}}function hh(s,e,t={externalSwitch:void 0}){for(let n of s)if(n)if(n instanceof Array)if(n.includes("visit")){let i=Jt(n,cs,(a,r,o)=>{},"",{preDialog:{}},[]);i&&(t.externalSwitch=i);}else hh(n,e,t);else typeof n=="object"&&(n&&"VAR="in n&&t.externalSwitch&&(e[tt]||(e[tt]=[]),e[tt].push({operations:[{type:"value",value:t.externalSwitch,key:n["VAR="],storageType:"storage",storageOperationType:"set"}]})),ch(n,e));}function ch(s,e,t="",n={preDialog:{}}){if(s!==null){for(let[i,a]of Object.entries(s))if(a instanceof Array){let r=[],o={},l=(t?t+"_|_":"")+i;nt(a,l,n,r,qo,qo,(u,h,c)=>{ch(u,o,h,c);},Ht);for(let[u,h]of Object.entries(o))e[u]=h;r.length>0&&(e[l]=r);}}}function $o(s){let e={},t=nm(s),n;try{n=JSON.parse(t);}catch{V.error("Error parsing ink file");return}if(e.labels=uh(n.root),e.labels&&hs in e.labels){let i=e.labels[hs];delete e.labels[hs],i.forEach(a=>{a.operations&&(e.initialOperations=e.initialOperations?[...e.initialOperations,...a.operations]:[...a.operations]);});}if(e.labels&&tt in e.labels){let i=e.labels[tt];delete e.labels[tt],i.forEach(a=>{a.operations&&(e.initialOperations=e.initialOperations?[...e.initialOperations,...a.operations]:[...a.operations]);});}return e}function nm(s){try{return new dh.Compiler(s).Compile().ToJson()||""}catch(e){return V.error("Error compiling ink file",e),""}}async function im(s){Array.isArray(s)||(s=[s]);let e=s.map(async t=>{let n=$o(t);n&&await sl(n,{operationStringConvert:rt.generateOrRunOperationFromHashtagScript,skipEmptyDialogs:true});});return await Promise.all(e)}function rm(s){je.afterToTranslate=e=>Jo(e,s);}function sm(s){je.beforeToTranslate=e=>Jo(e,s);}function Jo(s,e){let t=s.match(/\[([^\]]+)\]/);if(t){let n=t[1],i=e(n);return i&&(s=s.replaceAll(t[0],i)),Jo(s,e)}return s}function am(s){je.translate=s;}function om(s,e={},t={}){let n=[];return s.labels&&Object.values(s.labels).forEach(i=>{n=n.concat(i);}),je.generateJsonTranslation(n,e,t)}exports.convertInkText=$o;exports.generateJsonInkTranslation=om;exports.importInkText=im;exports.onInkHashtagScript=_h;exports.onInkTranslate=am;exports.onReplaceTextAfterTranslation=rm;exports.onReplaceTextBeforeTranslation=sm;