@drincs/pixi-vn-ink 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,9 +23,9 @@
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
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
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(`
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(),x=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,x.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);i=new x.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, 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(),x.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 x.Value){let n=e;if(n instanceof x.DivertTargetValue){let i=n;return this.Error("Shouldn't use a divert target (to "+i.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return 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 x.DivertTargetValue)){let r=(0, A.asOrNull)(i,x.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";r instanceof x.IntValue&&r.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, A.asOrThrows)(i,x.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 x.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,x.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 x.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 x.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 x.StringValue(me.toString()));break}case N.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new x.IntValue(a));break;case N.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new x.IntValue(this.state.currentTurnIndex+1));break;case N.ControlCommand.CommandType.TurnsSince:case N.ControlCommand.CommandType.ReadCount:let r=this.state.PopEvaluationStack();if(!(r instanceof x.DivertTargetValue)){let m="";r instanceof x.IntValue&&(m=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+r+m);break}let o=(0, A.asOrThrows)(r,x.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 x.IntValue(u));break;case N.ControlCommand.CommandType.Random:{let m=(0, A.asOrNull)(this.state.PopEvaluationStack(),x.IntValue),_=(0, A.asOrNull)(this.state.PopEvaluationStack(),x.IntValue);if(_==null||!(_ instanceof x.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(m==null||!(m instanceof x.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(m.value===null)return (0, 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 x.IntValue(Ce)),this.state.previousRandom=$;break}case N.ControlCommand.CommandType.SeedRandom:let h=(0, A.asOrNull)(this.state.PopEvaluationStack(),x.IntValue);if(h==null||!(h instanceof x.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(h.value===null)return (0, 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 x.IntValue(c));break;case N.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new x.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(),x.IntValue),g=(0, A.asOrThrows)(this.state.PopEvaluationStack(),x.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 x.ListValue(m.result,p.value));}else throw new pt.StoryException("Failed to find LIST called "+g.value);y==null&&(y=new x.ListValue),this.state.PushEvaluationStack(y);break;case N.ControlCommand.CommandType.ListRange:let T=(0, A.asOrNull)(this.state.PopEvaluationStack(),x.Value),d=(0, A.asOrNull)(this.state.PopEvaluationStack(),x.Value),S=(0, A.asOrNull)(this.state.PopEvaluationStack(),x.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 x.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 x.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 x.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 x.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(),x.Value).valueObject;r.push(c);}r.reverse();let o=n.function(r),l=null;o!=null?(l=x.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new 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 x.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, A.asOrThrows)(t,x.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,x.StringValue);l!==null?(a===null&&(a=[]),l.value!==null&&a.push(l.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let 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(),x.IntValue);if(!(e instanceof x.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(),x.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
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
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
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(`
@@ -41,8 +41,8 @@ Error:${h}`);}return u!=null&&(l=new s(u,r,this._externalErrorHandler,this._root
41
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
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
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=`
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___",w,st=(w=class{static t(e){return Array.isArray(e)?e.map(t=>w.translate(`${t}`)):w.translate(`${e}`)}static set beforeToTranslate(e){w._beforeToTranslate=e;}static set translate(e){w._translate=e;}static get translate(){return e=>{let t=e;return w._beforeToTranslate&&(t=w._beforeToTranslate(t)),t=w._translate(t),w._afterToTranslate&&(t=w._afterToTranslate(t)),t}}static set afterToTranslate(e){w._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"&&(w._beforeToTranslate?e[a]=w._beforeToTranslate(a):e[a]=a));});}static getConditionalsThenElse(e,t=[]){if(typeof e=="object"&&e&&"type"in e)if(e.type==="ifelse")e.then&&w.getConditionalsThenElse(e.then,t),e.else&&w.getConditionalsThenElse(e.else,t);else if(e.type==="stepswitch"){if(e.elements)if(Array.isArray(e.elements))e.elements.forEach(n=>{w.getConditionalsThenElse(n,t);});else if(e.elements.type==="ifelse"){let n=[];w.getConditionalsThenElse(e.elements,n),n.forEach(i=>{t.push(...i);});}else if(e.elements.type==="stepswitch"){let n=[];w.getConditionalsThenElse(e.elements,n),n.forEach(i=>{t.push(...i);});}else w.getConditionalsThenElse(e.elements,t);}else e.type==="resulttocombine"?(e.firstItem&&w.getConditionalsThenElse(e.firstItem,t),e.secondConditionalItem&&e.secondConditionalItem.forEach(n=>{w.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=w.getConditionalsThenElse(a.choices),r.forEach(o=>o.forEach(l=>{if("type"in l){let u=[];l.type==="ifelse"||l.type==="stepswitch"?w.getConditionalsThenElse(l,u):u=[l],u.map(h=>w.getConditionalsThenElse(h.text)).forEach(h=>{Array.isArray(h)&&h.forEach(c=>{Array.isArray(c)?c.forEach(f=>{typeof f=="string"?w.addKey(t,f,{defaultValue:i}):w.getConditionalsThenElse(f).forEach(p=>{Array.isArray(p)?p.forEach(g=>{typeof g=="string"&&w.addKey(t,g,{defaultValue:i});}):typeof p=="string"&&w.addKey(t,p,{defaultValue:i});});}):typeof c=="string"&&w.addKey(t,c,{defaultValue:i});});});}}));}if(a.dialogue){let r=[];Array.isArray(a.dialogue)?r=[a.dialogue]:r=w.getConditionalsThenElse(a.dialogue),r.forEach(o=>{if(typeof o=="string")w.addKey(t,o,{defaultValue:i});else if("text"in o){let l=w.getConditionalsThenElse(o.text);typeof l=="string"&&(l=[l]),l.forEach(u=>{typeof u=="string"?w.addKey(t,u,{defaultValue:i}):w.getConditionalsThenElse(u).forEach(h=>{typeof h=="string"?w.addKey(t,h,{defaultValue:i}):Array.isArray(h)&&h.forEach(c=>{typeof c=="string"?w.addKey(t,c,{defaultValue:i}):w.getConditionalsThenElse(c).forEach(f=>{typeof f=="string"&&w.addKey(t,f,{defaultValue:i});});});});});}});}a.conditionalStep&&w.getConditionalsThenElse(a.conditionalStep).forEach(r=>{Array.isArray(r)?w.generateJsonTranslation(r,t,n):w.generateJsonTranslation([r],t,n);});}),t}},qe(w,"_beforeToTranslate"),qe(w,"_translate",e=>e),qe(w,"_afterToTranslate"),w),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
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
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 Array.isArray(s)?n=s: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;
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;
@@ -1,4 +1,4 @@
1
- import { PixiVNJson, PixiVNJsonLabelStep } from '@drincs/pixi-vn-json';
1
+ import { PixiVNJson } from '@drincs/pixi-vn-json';
2
2
  import { StepLabelPropsType } from '@drincs/pixi-vn';
3
3
 
4
4
  /**
@@ -144,7 +144,7 @@ key: string) => string | undefined): void;
144
144
  declare function onInkTranslate(t: (text: string) => string): void;
145
145
  /**
146
146
  * Generate a json object with the keys of the labels and the values of the text to be translated
147
- * @param labels The labels to be used in the narrative. They will be added to the system
147
+ * @param pixivnJson The labels to be used in the narrative. They will be added to the system
148
148
  * @param json If you want to add more keys to the existing json
149
149
  * @param options The options to set the default value if the key is not found
150
150
  * @returns The json object with the keys of the labels and the values of the text to be translated
@@ -157,7 +157,7 @@ declare function onInkTranslate(t: (text: string) => string): void;
157
157
  * })
158
158
  * ```
159
159
  */
160
- declare function generateJsonInkTranslation(labels: PixiVNJsonLabelStep[] | PixiVNJson, json?: object, options?: {
160
+ declare function generateJsonInkTranslation(pixivnJson: PixiVNJson, json?: object, options?: {
161
161
  /**
162
162
  * Default value to set if the key is not found
163
163
  * @default "copy_key"