@drincs/pixi-vn-ink 1.2.2 → 1.3.0

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.
@@ -1,102 +1,102 @@
1
- 'use strict';var zod=require('zod'),characters=require('@drincs/pixi-vn/characters'),pixiVn=require('@drincs/pixi-vn'),canvas=require('@drincs/pixi-vn/canvas'),narration=require('@drincs/pixi-vn/narration'),sound=require('@drincs/pixi-vn/sound'),storage=require('@drincs/pixi-vn/storage'),virtual_pixiVnInk=require('virtual:pixi-vn-ink');var tC=Object.create;var Zf=Object.defineProperty;var nC=Object.getOwnPropertyDescriptor;var rC=Object.getOwnPropertyNames;var iC=Object.getPrototypeOf,sC=Object.prototype.hasOwnProperty;var Dn=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var S=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var aC=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rC(e))!sC.call(n,i)&&i!==t&&Zf(n,i,{get:()=>e[i],enumerable:!(r=nC(e,i))||r.enumerable});return n};var Xr=(n,e,t)=>(t=n!=null?tC(iC(n)):{},aC(Zf(t,"default",{value:n,enumerable:true}),n));var ri=S(z=>{Object.defineProperty(z,"__esModule",{value:true});z.regexpCode=z.getEsmExportName=z.getProperty=z.safeStringify=z.stringify=z.strConcat=z.addCodeArg=z.str=z._=z.nil=z._Code=z.Name=z.IDENTIFIER=z._CodeOrName=void 0;var ti=class{};z._CodeOrName=ti;z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Tn=class extends ti{constructor(e){if(super(),!z.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e;}toString(){return this.str}emptyStr(){return false}get names(){return {[this.str]:1}}};z.Name=Tn;var ot=class extends ti{constructor(e){super(),this._items=typeof e=="string"?[e]:e;}toString(){return this.str}emptyStr(){if(this._items.length>1)return false;let e=this._items[0];return e===""||e==='""'}get str(){var e;return (e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,r)=>`${t}${r}`,"")}get names(){var e;return (e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>(r instanceof Tn&&(t[r.str]=(t[r.str]||0)+1),t),{})}};z._Code=ot;z.nil=new ot("");function vp(n,...e){let t=[n[0]],r=0;for(;r<e.length;)il(t,e[r]),t.push(n[++r]);return new ot(t)}z._=vp;var rl=new ot("+");function Cp(n,...e){let t=[ni(n[0])],r=0;for(;r<e.length;)t.push(rl),il(t,e[r]),t.push(rl,ni(n[++r]));return DC(t),new ot(t)}z.str=Cp;function il(n,e){e instanceof ot?n.push(...e._items):e instanceof Tn?n.push(e):n.push(OC(e));}z.addCodeArg=il;function DC(n){let e=1;for(;e<n.length-1;){if(n[e]===rl){let t=AC(n[e-1],n[e+1]);if(t!==void 0){n.splice(e-1,3,t);continue}n[e++]="+";}e++;}}function AC(n,e){if(e==='""')return n;if(n==='""')return e;if(typeof n=="string")return e instanceof Tn||n[n.length-1]!=='"'?void 0:typeof e!="string"?`${n.slice(0,-1)}${e}"`:e[0]==='"'?n.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(n instanceof Tn))return `"${n}${e.slice(1)}`}function PC(n,e){return e.emptyStr()?n:n.emptyStr()?e:Cp`${n}${e}`}z.strConcat=PC;function OC(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:ni(Array.isArray(n)?n.join(","):n)}function xC(n){return new ot(ni(n))}z.stringify=xC;function ni(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}z.safeStringify=ni;function TC(n){return typeof n=="string"&&z.IDENTIFIER.test(n)?new ot(`.${n}`):vp`[${n}]`}z.getProperty=TC;function NC(n){if(typeof n=="string"&&z.IDENTIFIER.test(n))return new ot(`${n}`);throw new Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}z.getEsmExportName=NC;function FC(n){return new ot(n.toString())}z.regexpCode=FC;});var ol=S(He=>{Object.defineProperty(He,"__esModule",{value:true});He.ValueScope=He.ValueScopeName=He.Scope=He.varKinds=He.UsedValueState=void 0;var ze=ri(),sl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value;}},Ds;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed";})(Ds||(He.UsedValueState=Ds={}));He.varKinds={const:new ze.Name("const"),let:new ze.Name("let"),var:new ze.Name("var")};var As=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t;}toName(e){return e instanceof ze.Name?e:this.name(e)}name(e){return new ze.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return `${e}${t.index++}`}_nameGroup(e){var t,r;if(!((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};He.Scope=As;var Ps=class extends ze.Name{constructor(e,t){super(t),this.prefix=e;}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=(0, ze._)`.${new ze.Name(t)}[${r}]`;}};He.ValueScopeName=Ps;var IC=(0, ze._)`\n`,al=class extends As{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?IC:ze.nil};}get(){return this._scope}name(e){return new Ps(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:a}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[a];if(o){let c=o.get(s);if(c)return c}else o=this._values[a]=new Map;o.set(s,i);let u=this._scope[a]||(this._scope[a]=[]),l=u.length;return u[l]=t.ref,i.setValue(t,{property:a,itemIndex:l}),i}getValue(e,t){let r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return (0, ze._)`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let a=ze.nil;for(let s in e){let o=e[s];if(!o)continue;let u=r[s]=r[s]||new Map;o.forEach(l=>{if(u.has(l))return;u.set(l,Ds.Started);let c=t(l);if(c){let h=this.opts.es5?He.varKinds.var:He.varKinds.const;a=(0, ze._)`${a}${h} ${l} = ${c};${this.opts._n}`;}else if(c=i?.(l))a=(0, ze._)`${a}${c}${this.opts._n}`;else throw new sl(l);u.set(l,Ds.Completed);});}return a}};He.ValueScope=al;});var k=S($=>{Object.defineProperty($,"__esModule",{value:true});$.or=$.and=$.not=$.CodeGen=$.operators=$.varKinds=$.ValueScopeName=$.ValueScope=$.Scope=$.Name=$.regexpCode=$.stringify=$.getProperty=$.nil=$.strConcat=$.str=$._=void 0;var M=ri(),St=ol(),on=ri();Object.defineProperty($,"_",{enumerable:true,get:function(){return on._}});Object.defineProperty($,"str",{enumerable:true,get:function(){return on.str}});Object.defineProperty($,"strConcat",{enumerable:true,get:function(){return on.strConcat}});Object.defineProperty($,"nil",{enumerable:true,get:function(){return on.nil}});Object.defineProperty($,"getProperty",{enumerable:true,get:function(){return on.getProperty}});Object.defineProperty($,"stringify",{enumerable:true,get:function(){return on.stringify}});Object.defineProperty($,"regexpCode",{enumerable:true,get:function(){return on.regexpCode}});Object.defineProperty($,"Name",{enumerable:true,get:function(){return on.Name}});var Ns=ol();Object.defineProperty($,"Scope",{enumerable:true,get:function(){return Ns.Scope}});Object.defineProperty($,"ValueScope",{enumerable:true,get:function(){return Ns.ValueScope}});Object.defineProperty($,"ValueScopeName",{enumerable:true,get:function(){return Ns.ValueScopeName}});Object.defineProperty($,"varKinds",{enumerable:true,get:function(){return Ns.varKinds}});$.operators={GT:new M._Code(">"),GTE:new M._Code(">="),LT:new M._Code("<"),LTE:new M._Code("<="),EQ:new M._Code("==="),NEQ:new M._Code("!=="),NOT:new M._Code("!"),OR:new M._Code("||"),AND:new M._Code("&&"),ADD:new M._Code("+")};var Kt=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},ul=class extends Kt{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r;}render({es5:e,_n:t}){let r=e?St.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return `${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=ar(this.rhs,e,t)),this}get names(){return this.rhs instanceof M._CodeOrName?this.rhs.names:{}}},Os=class extends Kt{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r;}render({_n:e}){return `${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof M.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ar(this.rhs,e,t),this}get names(){let e=this.lhs instanceof M.Name?{}:{...this.lhs.names};return Ts(e,this.rhs)}},ll=class extends Os{constructor(e,t,r,i){super(e,r,i),this.op=t;}render({_n:e}){return `${this.lhs} ${this.op}= ${this.rhs};`+e}},cl=class extends Kt{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `${this.label}:`+e}},hl=class extends Kt{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `break${this.label?` ${this.label}`:""};`+e}},dl=class extends Kt{constructor(e){super(),this.error=e;}render({_n:e}){return `throw ${this.error};`+e}get names(){return this.error.names}},fl=class extends Kt{constructor(e){super(),this.code=e;}render({_n:e}){return `${this.code};`+e}optimizeNodes(){return `${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ar(this.code,e,t),this}get names(){return this.code instanceof M._CodeOrName?this.code.names:{}}},ii=class extends Kt{constructor(e=[]){super(),this.nodes=e;}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1);}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;for(;i--;){let a=r[i];a.optimizeNames(e,t)||(kC(e,a.names),r.splice(i,1));}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>In(e,t.names),{})}},Xt=class extends ii{render(e){return "{"+e._n+super.render(e)+"}"+e._n}},pl=class extends ii{},sr=class extends Xt{};sr.kind="else";var Nn=class n extends Xt{constructor(e,t){super(t),this.condition=e;}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===true)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new sr(r):r;}if(t)return e===false?t instanceof n?t:t.nodes:this.nodes.length?this:new n(bp(e),t instanceof n?[t]:t.nodes);if(!(e===false||!this.nodes.length))return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=ar(this.condition,e,t),this}get names(){let e=super.names;return Ts(e,this.condition),this.else&&In(e,this.else.names),e}};Nn.kind="if";var Fn=class extends Xt{};Fn.kind="for";var ml=class extends Fn{constructor(e){super(),this.iteration=e;}render(e){return `for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ar(this.iteration,e,t),this}get names(){return In(super.names,this.iteration.names)}},gl=class extends Fn{constructor(e,t,r,i){super(),this.varKind=e,this.name=t,this.from=r,this.to=i;}render(e){let t=e.es5?St.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return `for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){let e=Ts(super.names,this.from);return Ts(e,this.to)}},xs=class extends Fn{constructor(e,t,r,i){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=i;}render(e){return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ar(this.iterable,e,t),this}get names(){return In(super.names,this.iterable.names)}},si=class extends Xt{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r;}render(e){return `${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};si.kind="func";var ai=class extends ii{render(e){return "return "+super.render(e)}};ai.kind="return";var yl=class extends Xt{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&In(e,this.catch.names),this.finally&&In(e,this.finally.names),e}},oi=class extends Xt{constructor(e){super(),this.error=e;}render(e){return `catch(${this.error})`+super.render(e)}};oi.kind="catch";var ui=class extends Xt{render(e){return "finally"+super.render(e)}};ui.kind="finally";var vl=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
2
- `:""},this._extScope=e,this._scope=new St.Scope({parent:e}),this._nodes=[new pl];}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return (this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,i){let a=this._scope.toName(t);return r!==void 0&&i&&(this._constants[a.str]=r),this._leafNode(new ul(e,a,r)),a}const(e,t,r){return this._def(St.varKinds.const,e,t,r)}let(e,t,r){return this._def(St.varKinds.let,e,t,r)}var(e,t,r){return this._def(St.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new Os(e,t,r))}add(e,t){return this._leafNode(new ll(e,$.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==M.nil&&this._leafNode(new fl(e)),this}object(...e){let t=["{"];for(let[r,i]of e)t.length>1&&t.push(","),t.push(r),(r!==i||this.opts.es5)&&(t.push(":"),(0, M.addCodeArg)(t,i));return t.push("}"),new M._Code(t)}if(e,t,r){if(this._blockNode(new Nn(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Nn(e))}else(){return this._elseNode(new sr)}endIf(){return this._endBlockNode(Nn,sr)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new ml(e),t)}forRange(e,t,r,i,a=this.opts.es5?St.varKinds.var:St.varKinds.let){let s=this._scope.toName(e);return this._for(new gl(a,s,t,r),()=>i(s))}forOf(e,t,r,i=St.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=t instanceof M.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0, M._)`${s}.length`,o=>{this.var(a,(0, M._)`${s}[${o}]`),r(a);})}return this._for(new xs("of",i,a,t),()=>r(a))}forIn(e,t,r,i=this.opts.es5?St.varKinds.var:St.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0, M._)`Object.keys(${t})`,r);let a=this._scope.toName(e);return this._for(new xs("in",i,a,t),()=>r(a))}endFor(){return this._endBlockNode(Fn)}label(e){return this._leafNode(new cl(e))}break(e){return this._leafNode(new hl(e))}return(e){let t=new ai;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ai)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new yl;if(this._blockNode(i),this.code(e),t){let a=this.name("e");this._currNode=i.catch=new oi(a),t(a);}return r&&(this._currNode=i.finally=new ui,this.code(r)),this._endBlockNode(oi,ui)}throw(e){return this._leafNode(new dl(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=M.nil,r,i){return this._blockNode(new si(e,t,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(si)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants);}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e);}_endBlockNode(e,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof Nn))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e;}};$.CodeGen=vl;function In(n,e){for(let t in e)n[t]=(n[t]||0)+(e[t]||0);return n}function Ts(n,e){return e instanceof M._CodeOrName?In(n,e.names):n}function ar(n,e,t){if(n instanceof M.Name)return r(n);if(!i(n))return n;return new M._Code(n._items.reduce((a,s)=>(s instanceof M.Name&&(s=r(s)),s instanceof M._Code?a.push(...s._items):a.push(s),a),[]));function r(a){let s=t[a.str];return s===void 0||e[a.str]!==1?a:(delete e[a.str],s)}function i(a){return a instanceof M._Code&&a._items.some(s=>s instanceof M.Name&&e[s.str]===1&&t[s.str]!==void 0)}}function kC(n,e){for(let t in e)n[t]=(n[t]||0)-(e[t]||0);}function bp(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:(0, M._)`!${Cl(n)}`}$.not=bp;var VC=_p($.operators.AND);function RC(...n){return n.reduce(VC)}$.and=RC;var $C=_p($.operators.OR);function jC(...n){return n.reduce($C)}$.or=jC;function _p(n){return (e,t)=>e===M.nil?t:t===M.nil?e:(0, M._)`${Cl(e)} ${n} ${Cl(t)}`}function Cl(n){return n instanceof M.Name?n:(0, M._)`(${n})`}});var q=S(L=>{Object.defineProperty(L,"__esModule",{value:true});L.checkStrictMode=L.getErrorPath=L.Type=L.useFunc=L.setEvaluated=L.evaluatedPropsToName=L.mergeEvaluated=L.eachItem=L.unescapeJsonPointer=L.escapeJsonPointer=L.escapeFragment=L.unescapeFragment=L.schemaRefOrVal=L.schemaHasRulesButRef=L.schemaHasRules=L.checkUnknownRules=L.alwaysValidSchema=L.toHash=void 0;var re=k(),LC=ri();function qC(n){let e={};for(let t of n)e[t]=true;return e}L.toHash=qC;function BC(n,e){return typeof e=="boolean"?e:Object.keys(e).length===0?true:(wp(n,e),!Dp(e,n.self.RULES.all))}L.alwaysValidSchema=BC;function wp(n,e=n.schema){let{opts:t,self:r}=n;if(!t.strictSchema||typeof e=="boolean")return;let i=r.RULES.keywords;for(let a in e)i[a]||Op(n,`unknown keyword: "${a}"`);}L.checkUnknownRules=wp;function Dp(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(e[t])return true;return false}L.schemaHasRules=Dp;function WC(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(t!=="$ref"&&e.all[t])return true;return false}L.schemaHasRulesButRef=WC;function MC({topSchemaRef:n,schemaPath:e},t,r,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return (0, re._)`${t}`}return (0, re._)`${n}${e}${(0, re.getProperty)(r)}`}L.schemaRefOrVal=MC;function GC(n){return Ap(decodeURIComponent(n))}L.unescapeFragment=GC;function JC(n){return encodeURIComponent(_l(n))}L.escapeFragment=JC;function _l(n){return typeof n=="number"?`${n}`:n.replace(/~/g,"~0").replace(/\//g,"~1")}L.escapeJsonPointer=_l;function Ap(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}L.unescapeJsonPointer=Ap;function zC(n,e){if(Array.isArray(n))for(let t of n)e(t);else e(n);}L.eachItem=zC;function Sp({mergeNames:n,mergeToName:e,mergeValues:t,resultToName:r}){return (i,a,s,o)=>{let u=s===void 0?a:s instanceof re.Name?(a instanceof re.Name?n(i,a,s):e(i,a,s),s):a instanceof re.Name?(e(i,s,a),a):t(a,s);return o===re.Name&&!(u instanceof re.Name)?r(i,u):u}}L.mergeEvaluated={props:Sp({mergeNames:(n,e,t)=>n.if((0, re._)`${t} !== true && ${e} !== undefined`,()=>{n.if((0, re._)`${e} === true`,()=>n.assign(t,true),()=>n.assign(t,(0, re._)`${t} || {}`).code((0, re._)`Object.assign(${t}, ${e})`));}),mergeToName:(n,e,t)=>n.if((0, re._)`${t} !== true`,()=>{e===true?n.assign(t,true):(n.assign(t,(0, re._)`${t} || {}`),Sl(n,t,e));}),mergeValues:(n,e)=>n===true?true:{...n,...e},resultToName:Pp}),items:Sp({mergeNames:(n,e,t)=>n.if((0, re._)`${t} !== true && ${e} !== undefined`,()=>n.assign(t,(0, re._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(n,e,t)=>n.if((0, re._)`${t} !== true`,()=>n.assign(t,e===true?true:(0, re._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(n,e)=>n===true?true:Math.max(n,e),resultToName:(n,e)=>n.var("items",e)})};function Pp(n,e){if(e===true)return n.var("props",true);let t=n.var("props",(0, re._)`{}`);return e!==void 0&&Sl(n,t,e),t}L.evaluatedPropsToName=Pp;function Sl(n,e,t){Object.keys(t).forEach(r=>n.assign((0, re._)`${e}${(0, re.getProperty)(r)}`,true));}L.setEvaluated=Sl;var Ep={};function HC(n,e){return n.scopeValue("func",{ref:e,code:Ep[e.code]||(Ep[e.code]=new LC._Code(e.code))})}L.useFunc=HC;var bl;(function(n){n[n.Num=0]="Num",n[n.Str=1]="Str";})(bl||(L.Type=bl={}));function UC(n,e,t){if(n instanceof re.Name){let r=e===bl.Num;return t?r?(0, re._)`"[" + ${n} + "]"`:(0, re._)`"['" + ${n} + "']"`:r?(0, re._)`"/" + ${n}`:(0, re._)`"/" + ${n}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0, re.getProperty)(n).toString():"/"+_l(n)}L.getErrorPath=UC;function Op(n,e,t=n.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===true)throw new Error(e);n.self.logger.warn(e);}}L.checkStrictMode=Op;});var ut=S(El=>{Object.defineProperty(El,"__esModule",{value:true});var Te=k(),KC={data:new Te.Name("data"),valCxt:new Te.Name("valCxt"),instancePath:new Te.Name("instancePath"),parentData:new Te.Name("parentData"),parentDataProperty:new Te.Name("parentDataProperty"),rootData:new Te.Name("rootData"),dynamicAnchors:new Te.Name("dynamicAnchors"),vErrors:new Te.Name("vErrors"),errors:new Te.Name("errors"),this:new Te.Name("this"),self:new Te.Name("self"),scope:new Te.Name("scope"),json:new Te.Name("json"),jsonPos:new Te.Name("jsonPos"),jsonLen:new Te.Name("jsonLen"),jsonPart:new Te.Name("jsonPart")};El.default=KC;});var li=S(Ne=>{Object.defineProperty(Ne,"__esModule",{value:true});Ne.extendErrors=Ne.resetErrorsCount=Ne.reportExtraError=Ne.reportError=Ne.keyword$DataError=Ne.keywordError=void 0;var J=k(),Fs=q(),qe=ut();Ne.keywordError={message:({keyword:n})=>(0, J.str)`must pass "${n}" keyword validation`};Ne.keyword$DataError={message:({keyword:n,schemaType:e})=>e?(0, J.str)`"${n}" keyword must be ${e} ($data)`:(0, J.str)`"${n}" keyword is invalid ($data)`};function XC(n,e=Ne.keywordError,t,r){let{it:i}=n,{gen:a,compositeRule:s,allErrors:o}=i,u=Np(n,e,t);r??(s||o)?xp(a,u):Tp(i,(0, J._)`[${u}]`);}Ne.reportError=XC;function YC(n,e=Ne.keywordError,t){let{it:r}=n,{gen:i,compositeRule:a,allErrors:s}=r,o=Np(n,e,t);xp(i,o),a||s||Tp(r,qe.default.vErrors);}Ne.reportExtraError=YC;function ZC(n,e){n.assign(qe.default.errors,e),n.if((0, J._)`${qe.default.vErrors} !== null`,()=>n.if(e,()=>n.assign((0, J._)`${qe.default.vErrors}.length`,e),()=>n.assign(qe.default.vErrors,null)));}Ne.resetErrorsCount=ZC;function QC({gen:n,keyword:e,schemaValue:t,data:r,errsCount:i,it:a}){if(i===void 0)throw new Error("ajv implementation error");let s=n.name("err");n.forRange("i",i,qe.default.errors,o=>{n.const(s,(0, J._)`${qe.default.vErrors}[${o}]`),n.if((0, J._)`${s}.instancePath === undefined`,()=>n.assign((0, J._)`${s}.instancePath`,(0, J.strConcat)(qe.default.instancePath,a.errorPath))),n.assign((0, J._)`${s}.schemaPath`,(0, J.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(n.assign((0, J._)`${s}.schema`,t),n.assign((0, J._)`${s}.data`,r));});}Ne.extendErrors=QC;function xp(n,e){let t=n.const("err",e);n.if((0, J._)`${qe.default.vErrors} === null`,()=>n.assign(qe.default.vErrors,(0, J._)`[${t}]`),(0, J._)`${qe.default.vErrors}.push(${t})`),n.code((0, J._)`${qe.default.errors}++`);}function Tp(n,e){let{gen:t,validateName:r,schemaEnv:i}=n;i.$async?t.throw((0, J._)`new ${n.ValidationError}(${e})`):(t.assign((0, J._)`${r}.errors`,e),t.return(false));}var kn={keyword:new J.Name("keyword"),schemaPath:new J.Name("schemaPath"),params:new J.Name("params"),propertyName:new J.Name("propertyName"),message:new J.Name("message"),schema:new J.Name("schema"),parentSchema:new J.Name("parentSchema")};function Np(n,e,t){let{createErrors:r}=n.it;return r===false?(0, J._)`{}`:eb(n,e,t)}function eb(n,e,t={}){let{gen:r,it:i}=n,a=[tb(i,t),nb(n,t)];return rb(n,e,a),r.object(...a)}function tb({errorPath:n},{instancePath:e}){let t=e?(0, J.str)`${n}${(0, Fs.getErrorPath)(e,Fs.Type.Str)}`:n;return [qe.default.instancePath,(0, J.strConcat)(qe.default.instancePath,t)]}function nb({keyword:n,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:r}){let i=r?e:(0, J.str)`${e}/${n}`;return t&&(i=(0, J.str)`${i}${(0, Fs.getErrorPath)(t,Fs.Type.Str)}`),[kn.schemaPath,i]}function rb(n,{params:e,message:t},r){let{keyword:i,data:a,schemaValue:s,it:o}=n,{opts:u,propertyName:l,topSchemaRef:c,schemaPath:h}=o;r.push([kn.keyword,i],[kn.params,typeof e=="function"?e(n):e||(0, J._)`{}`]),u.messages&&r.push([kn.message,typeof t=="function"?t(n):t]),u.verbose&&r.push([kn.schema,s],[kn.parentSchema,(0, J._)`${c}${h}`],[qe.default.data,a]),l&&r.push([kn.propertyName,l]);}});var Ip=S(or=>{Object.defineProperty(or,"__esModule",{value:true});or.boolOrEmptySchema=or.topBoolOrEmptySchema=void 0;var ib=li(),sb=k(),ab=ut(),ob={message:"boolean schema is false"};function ub(n){let{gen:e,schema:t,validateName:r}=n;t===false?Fp(n,false):typeof t=="object"&&t.$async===true?e.return(ab.default.data):(e.assign((0, sb._)`${r}.errors`,null),e.return(true));}or.topBoolOrEmptySchema=ub;function lb(n,e){let{gen:t,schema:r}=n;r===false?(t.var(e,false),Fp(n)):t.var(e,true);}or.boolOrEmptySchema=lb;function Fp(n,e){let{gen:t,data:r}=n,i={gen:t,keyword:"false schema",data:r,schema:false,schemaCode:false,schemaValue:false,params:{},it:n};(0, ib.reportError)(i,ob,void 0,e);}});var wl=S(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.getRules=ur.isJSONType=void 0;var cb=["string","number","integer","boolean","null","object","array"],hb=new Set(cb);function db(n){return typeof n=="string"&&hb.has(n)}ur.isJSONType=db;function fb(){let n={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return {types:{...n,integer:true,boolean:true,null:true},rules:[{rules:[]},n.number,n.string,n.array,n.object],post:{rules:[]},all:{},keywords:{}}}ur.getRules=fb;});var Dl=S(un=>{Object.defineProperty(un,"__esModule",{value:true});un.shouldUseRule=un.shouldUseGroup=un.schemaHasRulesForType=void 0;function pb({schema:n,self:e},t){let r=e.RULES.types[t];return r&&r!==true&&kp(n,r)}un.schemaHasRulesForType=pb;function kp(n,e){return e.rules.some(t=>Vp(n,t))}un.shouldUseGroup=kp;function Vp(n,e){var t;return n[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(r=>n[r]!==void 0))}un.shouldUseRule=Vp;});var ci=S(Fe=>{Object.defineProperty(Fe,"__esModule",{value:true});Fe.reportTypeError=Fe.checkDataTypes=Fe.checkDataType=Fe.coerceAndCheckDataType=Fe.getJSONTypes=Fe.getSchemaTypes=Fe.DataType=void 0;var mb=wl(),gb=Dl(),yb=li(),V=k(),Rp=q(),lr;(function(n){n[n.Correct=0]="Correct",n[n.Wrong=1]="Wrong";})(lr||(Fe.DataType=lr={}));function vb(n){let e=$p(n.type);if(e.includes("null")){if(n.nullable===false)throw new Error("type: null contradicts nullable: false")}else {if(!e.length&&n.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');n.nullable===true&&e.push("null");}return e}Fe.getSchemaTypes=vb;function $p(n){let e=Array.isArray(n)?n:n?[n]:[];if(e.every(mb.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=$p;function Cb(n,e){let{gen:t,data:r,opts:i}=n,a=bb(e,i.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0, gb.schemaHasRulesForType)(n,e[0]));if(s){let o=Pl(e,r,i.strictNumbers,lr.Wrong);t.if(o,()=>{a.length?_b(n,e,a):Ol(n);});}return s}Fe.coerceAndCheckDataType=Cb;var jp=new Set(["string","number","integer","boolean","null"]);function bb(n,e){return e?n.filter(t=>jp.has(t)||e==="array"&&t==="array"):[]}function _b(n,e,t){let{gen:r,data:i,opts:a}=n,s=r.let("dataType",(0, V._)`typeof ${i}`),o=r.let("coerced",(0, V._)`undefined`);a.coerceTypes==="array"&&r.if((0, V._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>r.assign(i,(0, V._)`${i}[0]`).assign(s,(0, V._)`typeof ${i}`).if(Pl(e,i,a.strictNumbers),()=>r.assign(o,i))),r.if((0, V._)`${o} !== undefined`);for(let l of t)(jp.has(l)||l==="array"&&a.coerceTypes==="array")&&u(l);r.else(),Ol(n),r.endIf(),r.if((0, V._)`${o} !== undefined`,()=>{r.assign(i,o),Sb(n,o);});function u(l){switch(l){case "string":r.elseIf((0, V._)`${s} == "number" || ${s} == "boolean"`).assign(o,(0, V._)`"" + ${i}`).elseIf((0, V._)`${i} === null`).assign(o,(0, V._)`""`);return;case "number":r.elseIf((0, V._)`${s} == "boolean" || ${i} === null
1
+ 'use strict';var zod=require('zod'),characters=require('@drincs/pixi-vn/characters'),pixiVn=require('@drincs/pixi-vn'),canvas=require('@drincs/pixi-vn/canvas'),narration=require('@drincs/pixi-vn/narration'),sound=require('@drincs/pixi-vn/sound'),storage=require('@drincs/pixi-vn/storage'),virtual_pixiVnInk=require('virtual:pixi-vn-ink');var r0=Object.create;var Qp=Object.defineProperty;var i0=Object.getOwnPropertyDescriptor;var s0=Object.getOwnPropertyNames;var a0=Object.getPrototypeOf,o0=Object.prototype.hasOwnProperty;var On=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var _=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var u0=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of s0(e))!o0.call(n,i)&&i!==t&&Qp(n,i,{get:()=>e[i],enumerable:!(r=i0(e,i))||r.enumerable});return n};var Zr=(n,e,t)=>(t=n!=null?r0(a0(n)):{},u0(Qp(t,"default",{value:n,enumerable:true}),n));var si=_(H=>{Object.defineProperty(H,"__esModule",{value:true});H.regexpCode=H.getEsmExportName=H.getProperty=H.safeStringify=H.stringify=H.strConcat=H.addCodeArg=H.str=H._=H.nil=H._Code=H.Name=H.IDENTIFIER=H._CodeOrName=void 0;var ri=class{};H._CodeOrName=ri;H.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fn=class extends ri{constructor(e){if(super(),!H.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e;}toString(){return this.str}emptyStr(){return false}get names(){return {[this.str]:1}}};H.Name=Fn;var lt=class extends ri{constructor(e){super(),this._items=typeof e=="string"?[e]:e;}toString(){return this.str}emptyStr(){if(this._items.length>1)return false;let e=this._items[0];return e===""||e==='""'}get str(){var e;return (e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,r)=>`${t}${r}`,"")}get names(){var e;return (e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>(r instanceof Fn&&(t[r.str]=(t[r.str]||0)+1),t),{})}};H._Code=lt;H.nil=new lt("");function Cf(n,...e){let t=[n[0]],r=0;for(;r<e.length;)al(t,e[r]),t.push(n[++r]);return new lt(t)}H._=Cf;var sl=new lt("+");function Sf(n,...e){let t=[ii(n[0])],r=0;for(;r<e.length;)t.push(sl),al(t,e[r]),t.push(sl,ii(n[++r]));return O0(t),new lt(t)}H.str=Sf;function al(n,e){e instanceof lt?n.push(...e._items):e instanceof Fn?n.push(e):n.push(T0(e));}H.addCodeArg=al;function O0(n){let e=1;for(;e<n.length-1;){if(n[e]===sl){let t=P0(n[e-1],n[e+1]);if(t!==void 0){n.splice(e-1,3,t);continue}n[e++]="+";}e++;}}function P0(n,e){if(e==='""')return n;if(n==='""')return e;if(typeof n=="string")return e instanceof Fn||n[n.length-1]!=='"'?void 0:typeof e!="string"?`${n.slice(0,-1)}${e}"`:e[0]==='"'?n.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(n instanceof Fn))return `"${n}${e.slice(1)}`}function x0(n,e){return e.emptyStr()?n:n.emptyStr()?e:Sf`${n}${e}`}H.strConcat=x0;function T0(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:ii(Array.isArray(n)?n.join(","):n)}function N0(n){return new lt(ii(n))}H.stringify=N0;function ii(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}H.safeStringify=ii;function F0(n){return typeof n=="string"&&H.IDENTIFIER.test(n)?new lt(`.${n}`):Cf`[${n}]`}H.getProperty=F0;function I0(n){if(typeof n=="string"&&H.IDENTIFIER.test(n))return new lt(`${n}`);throw new Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}H.getEsmExportName=I0;function k0(n){return new lt(n.toString())}H.regexpCode=k0;});var ll=_(Ke=>{Object.defineProperty(Ke,"__esModule",{value:true});Ke.ValueScope=Ke.ValueScopeName=Ke.Scope=Ke.varKinds=Ke.UsedValueState=void 0;var Ue=si(),ol=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value;}},Os;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed";})(Os||(Ke.UsedValueState=Os={}));Ke.varKinds={const:new Ue.Name("const"),let:new Ue.Name("let"),var:new Ue.Name("var")};var Ps=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t;}toName(e){return e instanceof Ue.Name?e:this.name(e)}name(e){return new Ue.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return `${e}${t.index++}`}_nameGroup(e){var t,r;if(!((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ke.Scope=Ps;var xs=class extends Ue.Name{constructor(e,t){super(t),this.prefix=e;}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=(0, Ue._)`.${new Ue.Name(t)}[${r}]`;}};Ke.ValueScopeName=xs;var V0=(0, Ue._)`\n`,ul=class extends Ps{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?V0:Ue.nil};}get(){return this._scope}name(e){return new xs(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:a}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[a];if(o){let c=o.get(s);if(c)return c}else o=this._values[a]=new Map;o.set(s,i);let u=this._scope[a]||(this._scope[a]=[]),l=u.length;return u[l]=t.ref,i.setValue(t,{property:a,itemIndex:l}),i}getValue(e,t){let r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return (0, Ue._)`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let a=Ue.nil;for(let s in e){let o=e[s];if(!o)continue;let u=r[s]=r[s]||new Map;o.forEach(l=>{if(u.has(l))return;u.set(l,Os.Started);let c=t(l);if(c){let h=this.opts.es5?Ke.varKinds.var:Ke.varKinds.const;a=(0, Ue._)`${a}${h} ${l} = ${c};${this.opts._n}`;}else if(c=i?.(l))a=(0, Ue._)`${a}${c}${this.opts._n}`;else throw new ol(l);u.set(l,Os.Completed);});}return a}};Ke.ValueScope=ul;});var k=_(j=>{Object.defineProperty(j,"__esModule",{value:true});j.or=j.and=j.not=j.CodeGen=j.operators=j.varKinds=j.ValueScopeName=j.ValueScope=j.Scope=j.Name=j.regexpCode=j.stringify=j.getProperty=j.nil=j.strConcat=j.str=j._=void 0;var G=si(),Et=ll(),ln=si();Object.defineProperty(j,"_",{enumerable:true,get:function(){return ln._}});Object.defineProperty(j,"str",{enumerable:true,get:function(){return ln.str}});Object.defineProperty(j,"strConcat",{enumerable:true,get:function(){return ln.strConcat}});Object.defineProperty(j,"nil",{enumerable:true,get:function(){return ln.nil}});Object.defineProperty(j,"getProperty",{enumerable:true,get:function(){return ln.getProperty}});Object.defineProperty(j,"stringify",{enumerable:true,get:function(){return ln.stringify}});Object.defineProperty(j,"regexpCode",{enumerable:true,get:function(){return ln.regexpCode}});Object.defineProperty(j,"Name",{enumerable:true,get:function(){return ln.Name}});var Is=ll();Object.defineProperty(j,"Scope",{enumerable:true,get:function(){return Is.Scope}});Object.defineProperty(j,"ValueScope",{enumerable:true,get:function(){return Is.ValueScope}});Object.defineProperty(j,"ValueScopeName",{enumerable:true,get:function(){return Is.ValueScopeName}});Object.defineProperty(j,"varKinds",{enumerable:true,get:function(){return Is.varKinds}});j.operators={GT:new G._Code(">"),GTE:new G._Code(">="),LT:new G._Code("<"),LTE:new G._Code("<="),EQ:new G._Code("==="),NEQ:new G._Code("!=="),NOT:new G._Code("!"),OR:new G._Code("||"),AND:new G._Code("&&"),ADD:new G._Code("+")};var Yt=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},cl=class extends Yt{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r;}render({es5:e,_n:t}){let r=e?Et.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return `${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=ur(this.rhs,e,t)),this}get names(){return this.rhs instanceof G._CodeOrName?this.rhs.names:{}}},Ts=class extends Yt{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r;}render({_n:e}){return `${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof G.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ur(this.rhs,e,t),this}get names(){let e=this.lhs instanceof G.Name?{}:{...this.lhs.names};return Fs(e,this.rhs)}},hl=class extends Ts{constructor(e,t,r,i){super(e,r,i),this.op=t;}render({_n:e}){return `${this.lhs} ${this.op}= ${this.rhs};`+e}},dl=class extends Yt{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `${this.label}:`+e}},pl=class extends Yt{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `break${this.label?` ${this.label}`:""};`+e}},fl=class extends Yt{constructor(e){super(),this.error=e;}render({_n:e}){return `throw ${this.error};`+e}get names(){return this.error.names}},ml=class extends Yt{constructor(e){super(),this.code=e;}render({_n:e}){return `${this.code};`+e}optimizeNodes(){return `${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ur(this.code,e,t),this}get names(){return this.code instanceof G._CodeOrName?this.code.names:{}}},ai=class extends Yt{constructor(e=[]){super(),this.nodes=e;}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1);}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;for(;i--;){let a=r[i];a.optimizeNames(e,t)||(R0(e,a.names),r.splice(i,1));}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Vn(e,t.names),{})}},Zt=class extends ai{render(e){return "{"+e._n+super.render(e)+"}"+e._n}},gl=class extends ai{},or=class extends Zt{};or.kind="else";var In=class n extends Zt{constructor(e,t){super(t),this.condition=e;}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===true)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new or(r):r;}if(t)return e===false?t instanceof n?t:t.nodes:this.nodes.length?this:new n(_f(e),t instanceof n?[t]:t.nodes);if(!(e===false||!this.nodes.length))return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=ur(this.condition,e,t),this}get names(){let e=super.names;return Fs(e,this.condition),this.else&&Vn(e,this.else.names),e}};In.kind="if";var kn=class extends Zt{};kn.kind="for";var yl=class extends kn{constructor(e){super(),this.iteration=e;}render(e){return `for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ur(this.iteration,e,t),this}get names(){return Vn(super.names,this.iteration.names)}},vl=class extends kn{constructor(e,t,r,i){super(),this.varKind=e,this.name=t,this.from=r,this.to=i;}render(e){let t=e.es5?Et.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return `for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){let e=Fs(super.names,this.from);return Fs(e,this.to)}},Ns=class extends kn{constructor(e,t,r,i){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=i;}render(e){return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ur(this.iterable,e,t),this}get names(){return Vn(super.names,this.iterable.names)}},oi=class extends Zt{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r;}render(e){return `${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};oi.kind="func";var ui=class extends ai{render(e){return "return "+super.render(e)}};ui.kind="return";var bl=class extends Zt{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&Vn(e,this.catch.names),this.finally&&Vn(e,this.finally.names),e}},li=class extends Zt{constructor(e){super(),this.error=e;}render(e){return `catch(${this.error})`+super.render(e)}};li.kind="catch";var ci=class extends Zt{render(e){return "finally"+super.render(e)}};ci.kind="finally";var Cl=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
2
+ `:""},this._extScope=e,this._scope=new Et.Scope({parent:e}),this._nodes=[new gl];}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return (this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,i){let a=this._scope.toName(t);return r!==void 0&&i&&(this._constants[a.str]=r),this._leafNode(new cl(e,a,r)),a}const(e,t,r){return this._def(Et.varKinds.const,e,t,r)}let(e,t,r){return this._def(Et.varKinds.let,e,t,r)}var(e,t,r){return this._def(Et.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new Ts(e,t,r))}add(e,t){return this._leafNode(new hl(e,j.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==G.nil&&this._leafNode(new ml(e)),this}object(...e){let t=["{"];for(let[r,i]of e)t.length>1&&t.push(","),t.push(r),(r!==i||this.opts.es5)&&(t.push(":"),(0, G.addCodeArg)(t,i));return t.push("}"),new G._Code(t)}if(e,t,r){if(this._blockNode(new In(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new In(e))}else(){return this._elseNode(new or)}endIf(){return this._endBlockNode(In,or)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new yl(e),t)}forRange(e,t,r,i,a=this.opts.es5?Et.varKinds.var:Et.varKinds.let){let s=this._scope.toName(e);return this._for(new vl(a,s,t,r),()=>i(s))}forOf(e,t,r,i=Et.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=t instanceof G.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0, G._)`${s}.length`,o=>{this.var(a,(0, G._)`${s}[${o}]`),r(a);})}return this._for(new Ns("of",i,a,t),()=>r(a))}forIn(e,t,r,i=this.opts.es5?Et.varKinds.var:Et.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0, G._)`Object.keys(${t})`,r);let a=this._scope.toName(e);return this._for(new Ns("in",i,a,t),()=>r(a))}endFor(){return this._endBlockNode(kn)}label(e){return this._leafNode(new dl(e))}break(e){return this._leafNode(new pl(e))}return(e){let t=new ui;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ui)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new bl;if(this._blockNode(i),this.code(e),t){let a=this.name("e");this._currNode=i.catch=new li(a),t(a);}return r&&(this._currNode=i.finally=new ci,this.code(r)),this._endBlockNode(li,ci)}throw(e){return this._leafNode(new fl(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=G.nil,r,i){return this._blockNode(new oi(e,t,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(oi)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants);}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e);}_endBlockNode(e,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof In))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e;}};j.CodeGen=Cl;function Vn(n,e){for(let t in e)n[t]=(n[t]||0)+(e[t]||0);return n}function Fs(n,e){return e instanceof G._CodeOrName?Vn(n,e.names):n}function ur(n,e,t){if(n instanceof G.Name)return r(n);if(!i(n))return n;return new G._Code(n._items.reduce((a,s)=>(s instanceof G.Name&&(s=r(s)),s instanceof G._Code?a.push(...s._items):a.push(s),a),[]));function r(a){let s=t[a.str];return s===void 0||e[a.str]!==1?a:(delete e[a.str],s)}function i(a){return a instanceof G._Code&&a._items.some(s=>s instanceof G.Name&&e[s.str]===1&&t[s.str]!==void 0)}}function R0(n,e){for(let t in e)n[t]=(n[t]||0)-(e[t]||0);}function _f(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:(0, G._)`!${Sl(n)}`}j.not=_f;var j0=wf(j.operators.AND);function $0(...n){return n.reduce(j0)}j.and=$0;var L0=wf(j.operators.OR);function q0(...n){return n.reduce(L0)}j.or=q0;function wf(n){return (e,t)=>e===G.nil?t:t===G.nil?e:(0, G._)`${Sl(e)} ${n} ${Sl(t)}`}function Sl(n){return n instanceof G.Name?n:(0, G._)`(${n})`}});var q=_(L=>{Object.defineProperty(L,"__esModule",{value:true});L.checkStrictMode=L.getErrorPath=L.Type=L.useFunc=L.setEvaluated=L.evaluatedPropsToName=L.mergeEvaluated=L.eachItem=L.unescapeJsonPointer=L.escapeJsonPointer=L.escapeFragment=L.unescapeFragment=L.schemaRefOrVal=L.schemaHasRulesButRef=L.schemaHasRules=L.checkUnknownRules=L.alwaysValidSchema=L.toHash=void 0;var ie=k(),B0=si();function W0(n){let e={};for(let t of n)e[t]=true;return e}L.toHash=W0;function M0(n,e){return typeof e=="boolean"?e:Object.keys(e).length===0?true:(Af(n,e),!Of(e,n.self.RULES.all))}L.alwaysValidSchema=M0;function Af(n,e=n.schema){let{opts:t,self:r}=n;if(!t.strictSchema||typeof e=="boolean")return;let i=r.RULES.keywords;for(let a in e)i[a]||Tf(n,`unknown keyword: "${a}"`);}L.checkUnknownRules=Af;function Of(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(e[t])return true;return false}L.schemaHasRules=Of;function G0(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(t!=="$ref"&&e.all[t])return true;return false}L.schemaHasRulesButRef=G0;function J0({topSchemaRef:n,schemaPath:e},t,r,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return (0, ie._)`${t}`}return (0, ie._)`${n}${e}${(0, ie.getProperty)(r)}`}L.schemaRefOrVal=J0;function z0(n){return Pf(decodeURIComponent(n))}L.unescapeFragment=z0;function H0(n){return encodeURIComponent(wl(n))}L.escapeFragment=H0;function wl(n){return typeof n=="number"?`${n}`:n.replace(/~/g,"~0").replace(/\//g,"~1")}L.escapeJsonPointer=wl;function Pf(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}L.unescapeJsonPointer=Pf;function U0(n,e){if(Array.isArray(n))for(let t of n)e(t);else e(n);}L.eachItem=U0;function Ef({mergeNames:n,mergeToName:e,mergeValues:t,resultToName:r}){return (i,a,s,o)=>{let u=s===void 0?a:s instanceof ie.Name?(a instanceof ie.Name?n(i,a,s):e(i,a,s),s):a instanceof ie.Name?(e(i,s,a),a):t(a,s);return o===ie.Name&&!(u instanceof ie.Name)?r(i,u):u}}L.mergeEvaluated={props:Ef({mergeNames:(n,e,t)=>n.if((0, ie._)`${t} !== true && ${e} !== undefined`,()=>{n.if((0, ie._)`${e} === true`,()=>n.assign(t,true),()=>n.assign(t,(0, ie._)`${t} || {}`).code((0, ie._)`Object.assign(${t}, ${e})`));}),mergeToName:(n,e,t)=>n.if((0, ie._)`${t} !== true`,()=>{e===true?n.assign(t,true):(n.assign(t,(0, ie._)`${t} || {}`),El(n,t,e));}),mergeValues:(n,e)=>n===true?true:{...n,...e},resultToName:xf}),items:Ef({mergeNames:(n,e,t)=>n.if((0, ie._)`${t} !== true && ${e} !== undefined`,()=>n.assign(t,(0, ie._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(n,e,t)=>n.if((0, ie._)`${t} !== true`,()=>n.assign(t,e===true?true:(0, ie._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(n,e)=>n===true?true:Math.max(n,e),resultToName:(n,e)=>n.var("items",e)})};function xf(n,e){if(e===true)return n.var("props",true);let t=n.var("props",(0, ie._)`{}`);return e!==void 0&&El(n,t,e),t}L.evaluatedPropsToName=xf;function El(n,e,t){Object.keys(t).forEach(r=>n.assign((0, ie._)`${e}${(0, ie.getProperty)(r)}`,true));}L.setEvaluated=El;var Df={};function K0(n,e){return n.scopeValue("func",{ref:e,code:Df[e.code]||(Df[e.code]=new B0._Code(e.code))})}L.useFunc=K0;var _l;(function(n){n[n.Num=0]="Num",n[n.Str=1]="Str";})(_l||(L.Type=_l={}));function X0(n,e,t){if(n instanceof ie.Name){let r=e===_l.Num;return t?r?(0, ie._)`"[" + ${n} + "]"`:(0, ie._)`"['" + ${n} + "']"`:r?(0, ie._)`"/" + ${n}`:(0, ie._)`"/" + ${n}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0, ie.getProperty)(n).toString():"/"+wl(n)}L.getErrorPath=X0;function Tf(n,e,t=n.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===true)throw new Error(e);n.self.logger.warn(e);}}L.checkStrictMode=Tf;});var ct=_(Dl=>{Object.defineProperty(Dl,"__esModule",{value:true});var Ne=k(),Y0={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};Dl.default=Y0;});var hi=_(Fe=>{Object.defineProperty(Fe,"__esModule",{value:true});Fe.extendErrors=Fe.resetErrorsCount=Fe.reportExtraError=Fe.reportError=Fe.keyword$DataError=Fe.keywordError=void 0;var z=k(),ks=q(),We=ct();Fe.keywordError={message:({keyword:n})=>(0, z.str)`must pass "${n}" keyword validation`};Fe.keyword$DataError={message:({keyword:n,schemaType:e})=>e?(0, z.str)`"${n}" keyword must be ${e} ($data)`:(0, z.str)`"${n}" keyword is invalid ($data)`};function Z0(n,e=Fe.keywordError,t,r){let{it:i}=n,{gen:a,compositeRule:s,allErrors:o}=i,u=If(n,e,t);r??(s||o)?Nf(a,u):Ff(i,(0, z._)`[${u}]`);}Fe.reportError=Z0;function Q0(n,e=Fe.keywordError,t){let{it:r}=n,{gen:i,compositeRule:a,allErrors:s}=r,o=If(n,e,t);Nf(i,o),a||s||Ff(r,We.default.vErrors);}Fe.reportExtraError=Q0;function eC(n,e){n.assign(We.default.errors,e),n.if((0, z._)`${We.default.vErrors} !== null`,()=>n.if(e,()=>n.assign((0, z._)`${We.default.vErrors}.length`,e),()=>n.assign(We.default.vErrors,null)));}Fe.resetErrorsCount=eC;function tC({gen:n,keyword:e,schemaValue:t,data:r,errsCount:i,it:a}){if(i===void 0)throw new Error("ajv implementation error");let s=n.name("err");n.forRange("i",i,We.default.errors,o=>{n.const(s,(0, z._)`${We.default.vErrors}[${o}]`),n.if((0, z._)`${s}.instancePath === undefined`,()=>n.assign((0, z._)`${s}.instancePath`,(0, z.strConcat)(We.default.instancePath,a.errorPath))),n.assign((0, z._)`${s}.schemaPath`,(0, z.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(n.assign((0, z._)`${s}.schema`,t),n.assign((0, z._)`${s}.data`,r));});}Fe.extendErrors=tC;function Nf(n,e){let t=n.const("err",e);n.if((0, z._)`${We.default.vErrors} === null`,()=>n.assign(We.default.vErrors,(0, z._)`[${t}]`),(0, z._)`${We.default.vErrors}.push(${t})`),n.code((0, z._)`${We.default.errors}++`);}function Ff(n,e){let{gen:t,validateName:r,schemaEnv:i}=n;i.$async?t.throw((0, z._)`new ${n.ValidationError}(${e})`):(t.assign((0, z._)`${r}.errors`,e),t.return(false));}var Rn={keyword:new z.Name("keyword"),schemaPath:new z.Name("schemaPath"),params:new z.Name("params"),propertyName:new z.Name("propertyName"),message:new z.Name("message"),schema:new z.Name("schema"),parentSchema:new z.Name("parentSchema")};function If(n,e,t){let{createErrors:r}=n.it;return r===false?(0, z._)`{}`:nC(n,e,t)}function nC(n,e,t={}){let{gen:r,it:i}=n,a=[rC(i,t),iC(n,t)];return sC(n,e,a),r.object(...a)}function rC({errorPath:n},{instancePath:e}){let t=e?(0, z.str)`${n}${(0, ks.getErrorPath)(e,ks.Type.Str)}`:n;return [We.default.instancePath,(0, z.strConcat)(We.default.instancePath,t)]}function iC({keyword:n,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:r}){let i=r?e:(0, z.str)`${e}/${n}`;return t&&(i=(0, z.str)`${i}${(0, ks.getErrorPath)(t,ks.Type.Str)}`),[Rn.schemaPath,i]}function sC(n,{params:e,message:t},r){let{keyword:i,data:a,schemaValue:s,it:o}=n,{opts:u,propertyName:l,topSchemaRef:c,schemaPath:h}=o;r.push([Rn.keyword,i],[Rn.params,typeof e=="function"?e(n):e||(0, z._)`{}`]),u.messages&&r.push([Rn.message,typeof t=="function"?t(n):t]),u.verbose&&r.push([Rn.schema,s],[Rn.parentSchema,(0, z._)`${c}${h}`],[We.default.data,a]),l&&r.push([Rn.propertyName,l]);}});var Vf=_(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.boolOrEmptySchema=lr.topBoolOrEmptySchema=void 0;var aC=hi(),oC=k(),uC=ct(),lC={message:"boolean schema is false"};function cC(n){let{gen:e,schema:t,validateName:r}=n;t===false?kf(n,false):typeof t=="object"&&t.$async===true?e.return(uC.default.data):(e.assign((0, oC._)`${r}.errors`,null),e.return(true));}lr.topBoolOrEmptySchema=cC;function hC(n,e){let{gen:t,schema:r}=n;r===false?(t.var(e,false),kf(n)):t.var(e,true);}lr.boolOrEmptySchema=hC;function kf(n,e){let{gen:t,data:r}=n,i={gen:t,keyword:"false schema",data:r,schema:false,schemaCode:false,schemaValue:false,params:{},it:n};(0, aC.reportError)(i,lC,void 0,e);}});var Al=_(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.getRules=cr.isJSONType=void 0;var dC=["string","number","integer","boolean","null","object","array"],pC=new Set(dC);function fC(n){return typeof n=="string"&&pC.has(n)}cr.isJSONType=fC;function mC(){let n={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return {types:{...n,integer:true,boolean:true,null:true},rules:[{rules:[]},n.number,n.string,n.array,n.object],post:{rules:[]},all:{},keywords:{}}}cr.getRules=mC;});var Ol=_(cn=>{Object.defineProperty(cn,"__esModule",{value:true});cn.shouldUseRule=cn.shouldUseGroup=cn.schemaHasRulesForType=void 0;function gC({schema:n,self:e},t){let r=e.RULES.types[t];return r&&r!==true&&Rf(n,r)}cn.schemaHasRulesForType=gC;function Rf(n,e){return e.rules.some(t=>jf(n,t))}cn.shouldUseGroup=Rf;function jf(n,e){var t;return n[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(r=>n[r]!==void 0))}cn.shouldUseRule=jf;});var di=_(Ie=>{Object.defineProperty(Ie,"__esModule",{value:true});Ie.reportTypeError=Ie.checkDataTypes=Ie.checkDataType=Ie.coerceAndCheckDataType=Ie.getJSONTypes=Ie.getSchemaTypes=Ie.DataType=void 0;var yC=Al(),vC=Ol(),bC=hi(),V=k(),$f=q(),hr;(function(n){n[n.Correct=0]="Correct",n[n.Wrong=1]="Wrong";})(hr||(Ie.DataType=hr={}));function CC(n){let e=Lf(n.type);if(e.includes("null")){if(n.nullable===false)throw new Error("type: null contradicts nullable: false")}else {if(!e.length&&n.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');n.nullable===true&&e.push("null");}return e}Ie.getSchemaTypes=CC;function Lf(n){let e=Array.isArray(n)?n:n?[n]:[];if(e.every(yC.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ie.getJSONTypes=Lf;function SC(n,e){let{gen:t,data:r,opts:i}=n,a=_C(e,i.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0, vC.schemaHasRulesForType)(n,e[0]));if(s){let o=xl(e,r,i.strictNumbers,hr.Wrong);t.if(o,()=>{a.length?wC(n,e,a):Tl(n);});}return s}Ie.coerceAndCheckDataType=SC;var qf=new Set(["string","number","integer","boolean","null"]);function _C(n,e){return e?n.filter(t=>qf.has(t)||e==="array"&&t==="array"):[]}function wC(n,e,t){let{gen:r,data:i,opts:a}=n,s=r.let("dataType",(0, V._)`typeof ${i}`),o=r.let("coerced",(0, V._)`undefined`);a.coerceTypes==="array"&&r.if((0, V._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>r.assign(i,(0, V._)`${i}[0]`).assign(s,(0, V._)`typeof ${i}`).if(xl(e,i,a.strictNumbers),()=>r.assign(o,i))),r.if((0, V._)`${o} !== undefined`);for(let l of t)(qf.has(l)||l==="array"&&a.coerceTypes==="array")&&u(l);r.else(),Tl(n),r.endIf(),r.if((0, V._)`${o} !== undefined`,()=>{r.assign(i,o),EC(n,o);});function u(l){switch(l){case "string":r.elseIf((0, V._)`${s} == "number" || ${s} == "boolean"`).assign(o,(0, V._)`"" + ${i}`).elseIf((0, V._)`${i} === null`).assign(o,(0, V._)`""`);return;case "number":r.elseIf((0, V._)`${s} == "boolean" || ${i} === null
3
3
  || (${s} == "string" && ${i} && ${i} == +${i})`).assign(o,(0, V._)`+${i}`);return;case "integer":r.elseIf((0, V._)`${s} === "boolean" || ${i} === null
4
4
  || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(o,(0, V._)`+${i}`);return;case "boolean":r.elseIf((0, V._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(o,false).elseIf((0, V._)`${i} === "true" || ${i} === 1`).assign(o,true);return;case "null":r.elseIf((0, V._)`${i} === "" || ${i} === 0 || ${i} === false`),r.assign(o,null);return;case "array":r.elseIf((0, V._)`${s} === "string" || ${s} === "number"
5
- || ${s} === "boolean" || ${i} === null`).assign(o,(0, V._)`[${i}]`);}}}function Sb({gen:n,parentData:e,parentDataProperty:t},r){n.if((0, V._)`${e} !== undefined`,()=>n.assign((0, V._)`${e}[${t}]`,r));}function Al(n,e,t,r=lr.Correct){let i=r===lr.Correct?V.operators.EQ:V.operators.NEQ,a;switch(n){case "null":return (0, V._)`${e} ${i} null`;case "array":a=(0, V._)`Array.isArray(${e})`;break;case "object":a=(0, V._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case "integer":a=s((0, V._)`!(${e} % 1) && !isNaN(${e})`);break;case "number":a=s();break;default:return (0, V._)`typeof ${e} ${i} ${n}`}return r===lr.Correct?a:(0, V.not)(a);function s(o=V.nil){return (0, V.and)((0, V._)`typeof ${e} == "number"`,o,t?(0, V._)`isFinite(${e})`:V.nil)}}Fe.checkDataType=Al;function Pl(n,e,t,r){if(n.length===1)return Al(n[0],e,t,r);let i,a=(0, Rp.toHash)(n);if(a.array&&a.object){let s=(0, V._)`typeof ${e} != "object"`;i=a.null?s:(0, V._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object;}else i=V.nil;a.number&&delete a.integer;for(let s in a)i=(0, V.and)(i,Al(s,e,t,r));return i}Fe.checkDataTypes=Pl;var Eb={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:e})=>typeof n=="string"?(0, V._)`{type: ${n}}`:(0, V._)`{type: ${e}}`};function Ol(n){let e=wb(n);(0, yb.reportError)(e,Eb);}Fe.reportTypeError=Ol;function wb(n){let{gen:e,data:t,schema:r}=n,i=(0, Rp.schemaRefOrVal)(n,r,"type");return {gen:e,keyword:"type",data:t,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:n}}});var qp=S(Is=>{Object.defineProperty(Is,"__esModule",{value:true});Is.assignDefaults=void 0;var cr=k(),Db=q();function Ab(n,e){let{properties:t,items:r}=n.schema;if(e==="object"&&t)for(let i in t)Lp(n,i,t[i].default);else e==="array"&&Array.isArray(r)&&r.forEach((i,a)=>Lp(n,a,i.default));}Is.assignDefaults=Ab;function Lp(n,e,t){let{gen:r,compositeRule:i,data:a,opts:s}=n;if(t===void 0)return;let o=(0, cr._)`${a}${(0, cr.getProperty)(e)}`;if(i){(0, Db.checkStrictMode)(n,`default is ignored for: ${o}`);return}let u=(0, cr._)`${o} === undefined`;s.useDefaults==="empty"&&(u=(0, cr._)`${u} || ${o} === null || ${o} === ""`),r.if(u,(0, cr._)`${o} = ${(0, cr.stringify)(t)}`);}});var lt=S(te=>{Object.defineProperty(te,"__esModule",{value:true});te.validateUnion=te.validateArray=te.usePattern=te.callValidateCode=te.schemaProperties=te.allSchemaProperties=te.noPropertyInData=te.propertyInData=te.isOwnProperty=te.hasPropFunc=te.reportMissingProp=te.checkMissingProp=te.checkReportMissingProp=void 0;var ue=k(),xl=q(),ln=ut(),Pb=q();function Ob(n,e){let{gen:t,data:r,it:i}=n;t.if(Nl(t,r,e,i.opts.ownProperties),()=>{n.setParams({missingProperty:(0, ue._)`${e}`},true),n.error();});}te.checkReportMissingProp=Ob;function xb({gen:n,data:e,it:{opts:t}},r,i){return (0, ue.or)(...r.map(a=>(0, ue.and)(Nl(n,e,a,t.ownProperties),(0, ue._)`${i} = ${a}`)))}te.checkMissingProp=xb;function Tb(n,e){n.setParams({missingProperty:e},true),n.error();}te.reportMissingProp=Tb;function Bp(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0, ue._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=Bp;function Tl(n,e,t){return (0, ue._)`${Bp(n)}.call(${e}, ${t})`}te.isOwnProperty=Tl;function Nb(n,e,t,r){let i=(0, ue._)`${e}${(0, ue.getProperty)(t)} !== undefined`;return r?(0, ue._)`${i} && ${Tl(n,e,t)}`:i}te.propertyInData=Nb;function Nl(n,e,t,r){let i=(0, ue._)`${e}${(0, ue.getProperty)(t)} === undefined`;return r?(0, ue.or)(i,(0, ue.not)(Tl(n,e,t))):i}te.noPropertyInData=Nl;function Wp(n){return n?Object.keys(n).filter(e=>e!=="__proto__"):[]}te.allSchemaProperties=Wp;function Fb(n,e){return Wp(e).filter(t=>!(0, xl.alwaysValidSchema)(n,e[t]))}te.schemaProperties=Fb;function Ib({schemaCode:n,data:e,it:{gen:t,topSchemaRef:r,schemaPath:i,errorPath:a},it:s},o,u,l){let c=l?(0, ue._)`${n}, ${e}, ${r}${i}`:e,h=[[ln.default.instancePath,(0, ue.strConcat)(ln.default.instancePath,a)],[ln.default.parentData,s.parentData],[ln.default.parentDataProperty,s.parentDataProperty],[ln.default.rootData,ln.default.rootData]];s.opts.dynamicRef&&h.push([ln.default.dynamicAnchors,ln.default.dynamicAnchors]);let f=(0, ue._)`${c}, ${t.object(...h)}`;return u!==ue.nil?(0, ue._)`${o}.call(${u}, ${f})`:(0, ue._)`${o}(${f})`}te.callValidateCode=Ib;var kb=(0, ue._)`new RegExp`;function Vb({gen:n,it:{opts:e}},t){let r=e.unicodeRegExp?"u":"",{regExp:i}=e.code,a=i(t,r);return n.scopeValue("pattern",{key:a.toString(),ref:a,code:(0, ue._)`${i.code==="new RegExp"?kb:(0, Pb.useFunc)(n,i)}(${t}, ${r})`})}te.usePattern=Vb;function Rb(n){let{gen:e,data:t,keyword:r,it:i}=n,a=e.name("valid");if(i.allErrors){let o=e.let("valid",true);return s(()=>e.assign(o,false)),o}return e.var(a,true),s(()=>e.break()),a;function s(o){let u=e.const("len",(0, ue._)`${t}.length`);e.forRange("i",0,u,l=>{n.subschema({keyword:r,dataProp:l,dataPropType:xl.Type.Num},a),e.if((0, ue.not)(a),o);});}}te.validateArray=Rb;function $b(n){let{gen:e,schema:t,keyword:r,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(u=>(0, xl.alwaysValidSchema)(i,u))&&!i.opts.unevaluated)return;let s=e.let("valid",false),o=e.name("_valid");e.block(()=>t.forEach((u,l)=>{let c=n.subschema({keyword:r,schemaProp:l,compositeRule:true},o);e.assign(s,(0, ue._)`${s} || ${o}`),n.mergeValidEvaluated(c,o)||e.if((0, ue.not)(s));})),n.result(s,()=>n.reset(),()=>n.error(true));}te.validateUnion=$b;});var Jp=S(Nt=>{Object.defineProperty(Nt,"__esModule",{value:true});Nt.validateKeywordUsage=Nt.validSchemaType=Nt.funcKeywordCode=Nt.macroKeywordCode=void 0;var Be=k(),Vn=ut(),jb=lt(),Lb=li();function qb(n,e){let{gen:t,keyword:r,schema:i,parentSchema:a,it:s}=n,o=e.macro.call(s.self,i,a,s),u=Gp(t,r,o);s.opts.validateSchema!==false&&s.self.validateSchema(o,true);let l=t.name("valid");n.subschema({schema:o,schemaPath:Be.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:u,compositeRule:true},l),n.pass(l,()=>n.error(true));}Nt.macroKeywordCode=qb;function Bb(n,e){var t;let{gen:r,keyword:i,schema:a,parentSchema:s,$data:o,it:u}=n;Mb(u,e);let l=!o&&e.compile?e.compile.call(u.self,a,s,u):e.validate,c=Gp(r,i,l),h=r.let("valid");n.block$data(h,f),n.ok((t=e.valid)!==null&&t!==void 0?t:h);function f(){if(e.errors===false)m(),e.modifying&&Mp(n),C(()=>n.error());else {let b=e.async?p():g();e.modifying&&Mp(n),C(()=>Wb(n,b));}}function p(){let b=r.let("ruleErrs",null);return r.try(()=>m((0, Be._)`await `),v=>r.assign(h,false).if((0, Be._)`${v} instanceof ${u.ValidationError}`,()=>r.assign(b,(0, Be._)`${v}.errors`),()=>r.throw(v))),b}function g(){let b=(0, Be._)`${c}.errors`;return r.assign(b,null),m(Be.nil),b}function m(b=e.async?(0, Be._)`await `:Be.nil){let v=u.opts.passContext?Vn.default.this:Vn.default.self,d=!("compile"in e&&!o||e.schema===false);r.assign(h,(0, Be._)`${b}${(0, jb.callValidateCode)(n,c,v,d)}`,e.modifying);}function C(b){var v;r.if((0, Be.not)((v=e.valid)!==null&&v!==void 0?v:h),b);}}Nt.funcKeywordCode=Bb;function Mp(n){let{gen:e,data:t,it:r}=n;e.if(r.parentData,()=>e.assign(t,(0, Be._)`${r.parentData}[${r.parentDataProperty}]`));}function Wb(n,e){let{gen:t}=n;t.if((0, Be._)`Array.isArray(${e})`,()=>{t.assign(Vn.default.vErrors,(0, Be._)`${Vn.default.vErrors} === null ? ${e} : ${Vn.default.vErrors}.concat(${e})`).assign(Vn.default.errors,(0, Be._)`${Vn.default.vErrors}.length`),(0, Lb.extendErrors)(n);},()=>n.error());}function Mb({schemaEnv:n},e){if(e.async&&!n.$async)throw new Error("async keyword in sync schema")}function Gp(n,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return n.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0, Be.stringify)(t)})}function Gb(n,e,t=false){return !e.length||e.some(r=>r==="array"?Array.isArray(n):r==="object"?n&&typeof n=="object"&&!Array.isArray(n):typeof n==r||t&&typeof n>"u")}Nt.validSchemaType=Gb;function Jb({schema:n,opts:e,self:t,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(o=>!Object.prototype.hasOwnProperty.call(n,o)))throw new Error(`parent schema must have dependencies of ${a}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(n[a])){let u=`keyword "${a}" value is invalid at path "${r}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(u);else throw new Error(u)}}Nt.validateKeywordUsage=Jb;});var Hp=S(cn=>{Object.defineProperty(cn,"__esModule",{value:true});cn.extendSubschemaMode=cn.extendSubschemaData=cn.getSubschema=void 0;var Ft=k(),zp=q();function zb(n,{keyword:e,schemaProp:t,schema:r,schemaPath:i,errSchemaPath:a,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let o=n.schema[e];return t===void 0?{schema:o,schemaPath:(0, Ft._)`${n.schemaPath}${(0, Ft.getProperty)(e)}`,errSchemaPath:`${n.errSchemaPath}/${e}`}:{schema:o[t],schemaPath:(0, Ft._)`${n.schemaPath}${(0, Ft.getProperty)(e)}${(0, Ft.getProperty)(t)}`,errSchemaPath:`${n.errSchemaPath}/${e}/${(0, zp.escapeFragment)(t)}`}}if(r!==void 0){if(i===void 0||a===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return {schema:r,schemaPath:i,topSchemaRef:s,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}cn.getSubschema=zb;function Hb(n,e,{dataProp:t,dataPropType:r,data:i,dataTypes:a,propertyName:s}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:o}=e;if(t!==void 0){let{errorPath:l,dataPathArr:c,opts:h}=e,f=o.let("data",(0, Ft._)`${e.data}${(0, Ft.getProperty)(t)}`,true);u(f),n.errorPath=(0, Ft.str)`${l}${(0, zp.getErrorPath)(t,r,h.jsPropertySyntax)}`,n.parentDataProperty=(0, Ft._)`${t}`,n.dataPathArr=[...c,n.parentDataProperty];}if(i!==void 0){let l=i instanceof Ft.Name?i:o.let("data",i,true);u(l),s!==void 0&&(n.propertyName=s);}a&&(n.dataTypes=a);function u(l){n.data=l,n.dataLevel=e.dataLevel+1,n.dataTypes=[],e.definedProperties=new Set,n.parentData=e.data,n.dataNames=[...e.dataNames,l];}}cn.extendSubschemaData=Hb;function Ub(n,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(n.compositeRule=r),i!==void 0&&(n.createErrors=i),a!==void 0&&(n.allErrors=a),n.jtdDiscriminator=e,n.jtdMetadata=t;}cn.extendSubschemaMode=Ub;});var Fl=S((lI,Up)=>{Up.exports=function n(e,t){if(e===t)return true;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return false;var r,i,a;if(Array.isArray(e)){if(r=e.length,r!=t.length)return false;for(i=r;i--!==0;)if(!n(e[i],t[i]))return false;return true}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(a=Object.keys(e),r=a.length,r!==Object.keys(t).length)return false;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[i]))return false;for(i=r;i--!==0;){var s=a[i];if(!n(e[s],t[s]))return false}return true}return e!==e&&t!==t};});var Xp=S((cI,Kp)=>{var hn=Kp.exports=function(n,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var r=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};ks(e,r,i,n,"",n);};hn.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};hn.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};hn.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};hn.skipKeywords={default:true,enum:true,const:true,required:true,maximum:true,minimum:true,exclusiveMaximum:true,exclusiveMinimum:true,multipleOf:true,maxLength:true,minLength:true,pattern:true,format:true,maxItems:true,minItems:true,uniqueItems:true,maxProperties:true,minProperties:true};function ks(n,e,t,r,i,a,s,o,u,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,i,a,s,o,u,l);for(var c in r){var h=r[c];if(Array.isArray(h)){if(c in hn.arrayKeywords)for(var f=0;f<h.length;f++)ks(n,e,t,h[f],i+"/"+c+"/"+f,a,i,c,r,f);}else if(c in hn.propsKeywords){if(h&&typeof h=="object")for(var p in h)ks(n,e,t,h[p],i+"/"+c+"/"+Kb(p),a,i,c,r,p);}else (c in hn.keywords||n.allKeys&&!(c in hn.skipKeywords))&&ks(n,e,t,h,i+"/"+c,a,i,c,r);}t(r,i,a,s,o,u,l);}}function Kb(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}});var hi=S(Ue=>{Object.defineProperty(Ue,"__esModule",{value:true});Ue.getSchemaRefs=Ue.resolveUrl=Ue.normalizeId=Ue._getFullPath=Ue.getFullPath=Ue.inlineRef=void 0;var Xb=q(),Yb=Fl(),Zb=Xp(),Qb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function e_(n,e=true){return typeof n=="boolean"?true:e===true?!Il(n):e?Yp(n)<=e:false}Ue.inlineRef=e_;var t_=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Il(n){for(let e in n){if(t_.has(e))return true;let t=n[e];if(Array.isArray(t)&&t.some(Il)||typeof t=="object"&&Il(t))return true}return false}function Yp(n){let e=0;for(let t in n){if(t==="$ref")return 1/0;if(e++,!Qb.has(t)&&(typeof n[t]=="object"&&(0, Xb.eachItem)(n[t],r=>e+=Yp(r)),e===1/0))return 1/0}return e}function Zp(n,e="",t){t!==false&&(e=hr(e));let r=n.parse(e);return Qp(n,r)}Ue.getFullPath=Zp;function Qp(n,e){return n.serialize(e).split("#")[0]+"#"}Ue._getFullPath=Qp;var n_=/#\/?$/;function hr(n){return n?n.replace(n_,""):""}Ue.normalizeId=hr;function r_(n,e,t){return t=hr(t),n.resolve(e,t)}Ue.resolveUrl=r_;var i_=/^[a-z_][-a-z0-9._]*$/i;function s_(n,e){if(typeof n=="boolean")return {};let{schemaId:t,uriResolver:r}=this.opts,i=hr(n[t]||e),a={"":i},s=Zp(r,i,false),o={},u=new Set;return Zb(n,{allKeys:true},(h,f,p,g)=>{if(g===void 0)return;let m=s+f,C=a[g];typeof h[t]=="string"&&(C=b.call(this,h[t])),v.call(this,h.$anchor),v.call(this,h.$dynamicAnchor),a[f]=C;function b(d){let _=this.opts.uriResolver.resolve;if(d=hr(C?_(C,d):d),u.has(d))throw c(d);u.add(d);let y=this.refs[d];return typeof y=="string"&&(y=this.refs[y]),typeof y=="object"?l(h,y.schema,d):d!==hr(m)&&(d[0]==="#"?(l(h,o[d],d),o[d]=h):this.refs[d]=m),d}function v(d){if(typeof d=="string"){if(!i_.test(d))throw new Error(`invalid anchor "${d}"`);b.call(this,`#${d}`);}}}),o;function l(h,f,p){if(f!==void 0&&!Yb(h,f))throw c(p)}function c(h){return new Error(`reference "${h}" resolves to more than one schema`)}}Ue.getSchemaRefs=s_;});var dr=S(dn=>{Object.defineProperty(dn,"__esModule",{value:true});dn.getData=dn.KeywordCxt=dn.validateFunctionCode=void 0;var im=Ip(),em=ci(),Vl=Dl(),Vs=ci(),a_=qp(),fi=Jp(),kl=Hp(),O=k(),F=ut(),o_=hi(),Yt=q(),di=li();function u_(n){if(om(n)&&(um(n),am(n))){h_(n);return}sm(n,()=>(0, im.topBoolOrEmptySchema)(n));}dn.validateFunctionCode=u_;function sm({gen:n,validateName:e,schema:t,schemaEnv:r,opts:i},a){i.code.es5?n.func(e,(0, O._)`${F.default.data}, ${F.default.valCxt}`,r.$async,()=>{n.code((0, O._)`"use strict"; ${tm(t,i)}`),c_(n,i),n.code(a);}):n.func(e,(0, O._)`${F.default.data}, ${l_(i)}`,r.$async,()=>n.code(tm(t,i)).code(a));}function l_(n){return (0, O._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${n.dynamicRef?(0, O._)`, ${F.default.dynamicAnchors}={}`:O.nil}}={}`}function c_(n,e){n.if(F.default.valCxt,()=>{n.var(F.default.instancePath,(0, O._)`${F.default.valCxt}.${F.default.instancePath}`),n.var(F.default.parentData,(0, O._)`${F.default.valCxt}.${F.default.parentData}`),n.var(F.default.parentDataProperty,(0, O._)`${F.default.valCxt}.${F.default.parentDataProperty}`),n.var(F.default.rootData,(0, O._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&n.var(F.default.dynamicAnchors,(0, O._)`${F.default.valCxt}.${F.default.dynamicAnchors}`);},()=>{n.var(F.default.instancePath,(0, O._)`""`),n.var(F.default.parentData,(0, O._)`undefined`),n.var(F.default.parentDataProperty,(0, O._)`undefined`),n.var(F.default.rootData,F.default.data),e.dynamicRef&&n.var(F.default.dynamicAnchors,(0, O._)`{}`);});}function h_(n){let{schema:e,opts:t,gen:r}=n;sm(n,()=>{t.$comment&&e.$comment&&cm(n),g_(n),r.let(F.default.vErrors,null),r.let(F.default.errors,0),t.unevaluated&&d_(n),lm(n),C_(n);});}function d_(n){let{gen:e,validateName:t}=n;n.evaluated=e.const("evaluated",(0, O._)`${t}.evaluated`),e.if((0, O._)`${n.evaluated}.dynamicProps`,()=>e.assign((0, O._)`${n.evaluated}.props`,(0, O._)`undefined`)),e.if((0, O._)`${n.evaluated}.dynamicItems`,()=>e.assign((0, O._)`${n.evaluated}.items`,(0, O._)`undefined`));}function tm(n,e){let t=typeof n=="object"&&n[e.schemaId];return t&&(e.code.source||e.code.process)?(0, O._)`/*# sourceURL=${t} */`:O.nil}function f_(n,e){if(om(n)&&(um(n),am(n))){p_(n,e);return}(0, im.boolOrEmptySchema)(n,e);}function am({schema:n,self:e}){if(typeof n=="boolean")return !n;for(let t in n)if(e.RULES.all[t])return true;return false}function om(n){return typeof n.schema!="boolean"}function p_(n,e){let{schema:t,gen:r,opts:i}=n;i.$comment&&t.$comment&&cm(n),y_(n),v_(n);let a=r.const("_errs",F.default.errors);lm(n,a),r.var(e,(0, O._)`${a} === ${F.default.errors}`);}function um(n){(0, Yt.checkUnknownRules)(n),m_(n);}function lm(n,e){if(n.opts.jtd)return nm(n,[],false,e);let t=(0, em.getSchemaTypes)(n.schema),r=(0, em.coerceAndCheckDataType)(n,t);nm(n,t,!r,e);}function m_(n){let{schema:e,errSchemaPath:t,opts:r,self:i}=n;e.$ref&&r.ignoreKeywordsWithRef&&(0, Yt.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`);}function g_(n){let{schema:e,opts:t}=n;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0, Yt.checkStrictMode)(n,"default is ignored in the schema root");}function y_(n){let e=n.schema[n.opts.schemaId];e&&(n.baseId=(0, o_.resolveUrl)(n.opts.uriResolver,n.baseId,e));}function v_(n){if(n.schema.$async&&!n.schemaEnv.$async)throw new Error("async schema in sync schema")}function cm({gen:n,schemaEnv:e,schema:t,errSchemaPath:r,opts:i}){let a=t.$comment;if(i.$comment===true)n.code((0, O._)`${F.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let s=(0, O.str)`${r}/$comment`,o=n.scopeValue("root",{ref:e.root});n.code((0, O._)`${F.default.self}.opts.$comment(${a}, ${s}, ${o}.schema)`);}}function C_(n){let{gen:e,schemaEnv:t,validateName:r,ValidationError:i,opts:a}=n;t.$async?e.if((0, O._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0, O._)`new ${i}(${F.default.vErrors})`)):(e.assign((0, O._)`${r}.errors`,F.default.vErrors),a.unevaluated&&b_(n),e.return((0, O._)`${F.default.errors} === 0`));}function b_({gen:n,evaluated:e,props:t,items:r}){t instanceof O.Name&&n.assign((0, O._)`${e}.props`,t),r instanceof O.Name&&n.assign((0, O._)`${e}.items`,r);}function nm(n,e,t,r){let{gen:i,schema:a,data:s,allErrors:o,opts:u,self:l}=n,{RULES:c}=l;if(a.$ref&&(u.ignoreKeywordsWithRef||!(0, Yt.schemaHasRulesButRef)(a,c))){i.block(()=>dm(n,"$ref",c.all.$ref.definition));return}u.jtd||__(n,e),i.block(()=>{for(let f of c.rules)h(f);h(c.post);});function h(f){(0, Vl.shouldUseGroup)(a,f)&&(f.type?(i.if((0, Vs.checkDataType)(f.type,s,u.strictNumbers)),rm(n,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0, Vs.reportTypeError)(n)),i.endIf()):rm(n,f),o||i.if((0, O._)`${F.default.errors} === ${r||0}`));}}function rm(n,e){let{gen:t,schema:r,opts:{useDefaults:i}}=n;i&&(0, a_.assignDefaults)(n,e.type),t.block(()=>{for(let a of e.rules)(0, Vl.shouldUseRule)(r,a)&&dm(n,a.keyword,a.definition,e.type);});}function __(n,e){n.schemaEnv.meta||!n.opts.strictTypes||(S_(n,e),n.opts.allowUnionTypes||E_(n,e),w_(n,n.dataTypes));}function S_(n,e){if(e.length){if(!n.dataTypes.length){n.dataTypes=e;return}e.forEach(t=>{hm(n.dataTypes,t)||Rl(n,`type "${t}" not allowed by context "${n.dataTypes.join(",")}"`);}),A_(n,e);}}function E_(n,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Rl(n,"use allowUnionTypes to allow union type keyword");}function w_(n,e){let t=n.self.RULES.all;for(let r in t){let i=t[r];if(typeof i=="object"&&(0, Vl.shouldUseRule)(n.schema,i)){let{type:a}=i.definition;a.length&&!a.some(s=>D_(e,s))&&Rl(n,`missing type "${a.join(",")}" for keyword "${r}"`);}}}function D_(n,e){return n.includes(e)||e==="number"&&n.includes("integer")}function hm(n,e){return n.includes(e)||e==="integer"&&n.includes("number")}function A_(n,e){let t=[];for(let r of n.dataTypes)hm(e,r)?t.push(r):e.includes("integer")&&r==="number"&&t.push("integer");n.dataTypes=t;}function Rl(n,e){let t=n.schemaEnv.baseId+n.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0, Yt.checkStrictMode)(n,e,n.opts.strictTypes);}var Rs=class{constructor(e,t,r){if((0, fi.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0, Yt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",fm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0, fi.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==false)&&(this.errsCount=e.gen.const("_errs",F.default.errors));}result(e,t,r){this.failResult((0, O.not)(e),t,r);}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else();}pass(e,t){this.failResult((0, O.not)(e),void 0,t);}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(false);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else();}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0, O._)`${t} !== undefined && (${(0, O.or)(this.invalid$data(),e)})`);}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r);}_error(e,t){(e?di.reportExtraError:di.reportError)(this,this.def.error,t);}$dataError(){(0, di.reportError)(this,this.def.$dataError||di.keyword$DataError);}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0, di.resetErrorsCount)(this.gen,this.errsCount);}ok(e){this.allErrors||this.gen.if(e);}setParams(e,t){t?Object.assign(this.params,e):this.params=e;}block$data(e,t,r=O.nil){this.gen.block(()=>{this.check$data(e,r),t();});}check$data(e=O.nil,t=O.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:a,def:s}=this;r.if((0, O.or)((0, O._)`${i} === undefined`,t)),e!==O.nil&&r.assign(e,true),(a.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==O.nil&&r.assign(e,false)),r.else();}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:a}=this;return (0, O.or)(s(),o());function s(){if(r.length){if(!(t instanceof O.Name))throw new Error("ajv implementation error");let u=Array.isArray(r)?r:[r];return (0, O._)`${(0, Vs.checkDataTypes)(u,t,a.opts.strictNumbers,Vs.DataType.Wrong)}`}return O.nil}function o(){if(i.validateSchema){let u=e.scopeValue("validate$data",{ref:i.validateSchema});return (0, O._)`!${u}(${t})`}return O.nil}}subschema(e,t){let r=(0, kl.getSubschema)(this.it,e);(0, kl.extendSubschemaData)(r,this.it,e),(0, kl.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return f_(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;r.opts.unevaluated&&(r.props!==true&&e.props!==void 0&&(r.props=Yt.mergeEvaluated.props(i,e.props,r.props,t)),r.items!==true&&e.items!==void 0&&(r.items=Yt.mergeEvaluated.items(i,e.items,r.items,t)));}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==true||r.items!==true))return i.if(t,()=>this.mergeEvaluated(e,O.Name)),true}};dn.KeywordCxt=Rs;function dm(n,e,t,r){let i=new Rs(n,t,e);"code"in t?t.code(i,r):i.$data&&t.validate?(0, fi.funcKeywordCode)(i,t):"macro"in t?(0, fi.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0, fi.funcKeywordCode)(i,t);}var P_=/^\/(?:[^~]|~0|~1)*$/,O_=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fm(n,{dataLevel:e,dataNames:t,dataPathArr:r}){let i,a;if(n==="")return F.default.rootData;if(n[0]==="/"){if(!P_.test(n))throw new Error(`Invalid JSON-pointer: ${n}`);i=n,a=F.default.rootData;}else {let l=O_.exec(n);if(!l)throw new Error(`Invalid JSON-pointer: ${n}`);let c=+l[1];if(i=l[2],i==="#"){if(c>=e)throw new Error(u("property/index",c));return r[e-c]}if(c>e)throw new Error(u("data",c));if(a=t[e-c],!i)return a}let s=a,o=i.split("/");for(let l of o)l&&(a=(0, O._)`${a}${(0, O.getProperty)((0, Yt.unescapeJsonPointer)(l))}`,s=(0, O._)`${s} && ${a}`);return s;function u(l,c){return `Cannot access ${l} ${c} levels up, current level is ${e}`}}dn.getData=fm;});var pi=S(jl=>{Object.defineProperty(jl,"__esModule",{value:true});var $l=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=true;}};jl.default=$l;});var fr=S(Bl=>{Object.defineProperty(Bl,"__esModule",{value:true});var Ll=hi(),ql=class extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0, Ll.resolveUrl)(e,t,r),this.missingSchema=(0, Ll.normalizeId)((0, Ll.getFullPath)(e,this.missingRef));}};Bl.default=ql;});var mi=S(ct=>{Object.defineProperty(ct,"__esModule",{value:true});ct.resolveSchema=ct.getCompilingSchema=ct.resolveRef=ct.compileSchema=ct.SchemaEnv=void 0;var Et=k(),x_=pi(),Rn=ut(),wt=hi(),pm=q(),T_=dr(),pr=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0, wt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={};}};ct.SchemaEnv=pr;function Ml(n){let e=mm.call(this,n);if(e)return e;let t=(0, wt.getFullPath)(this.opts.uriResolver,n.root.baseId),{es5:r,lines:i}=this.opts.code,{ownProperties:a}=this.opts,s=new Et.CodeGen(this.scope,{es5:r,lines:i,ownProperties:a}),o;n.$async&&(o=s.scopeValue("Error",{ref:x_.default,code:(0, Et._)`require("ajv/dist/runtime/validation_error").default`}));let u=s.scopeName("validate");n.validateName=u;let l={gen:s,allErrors:this.opts.allErrors,data:Rn.default.data,parentData:Rn.default.parentData,parentDataProperty:Rn.default.parentDataProperty,dataNames:[Rn.default.data],dataPathArr:[Et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===true?{ref:n.schema,code:(0, Et.stringify)(n.schema)}:{ref:n.schema}),validateName:u,ValidationError:o,schema:n.schema,schemaEnv:n,rootId:t,baseId:n.baseId||t,schemaPath:Et.nil,errSchemaPath:n.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0, Et._)`""`,opts:this.opts,self:this},c;try{this._compilations.add(n),(0,T_.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let h=s.toString();c=`${s.scopeRefs(Rn.default.scope)}return ${h}`,this.opts.code.process&&(c=this.opts.code.process(c,n));let p=new Function(`${Rn.default.self}`,`${Rn.default.scope}`,c)(this,this.scope.get());if(this.scope.value(u,{ref:p}),p.errors=null,p.schema=n.schema,p.schemaEnv=n,n.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:u,validateCode:h,scopeValues:s._values}),this.opts.unevaluated){let{props:g,items:m}=l;p.evaluated={props:g instanceof Et.Name?void 0:g,items:m instanceof Et.Name?void 0:m,dynamicProps:g instanceof Et.Name,dynamicItems:m instanceof Et.Name},p.source&&(p.source.evaluated=(0,Et.stringify)(p.evaluated));}return n.validate=p,n}catch(h){throw delete n.validate,delete n.validateName,c&&this.logger.error("Error compiling schema, function code:",c),h}finally{this._compilations.delete(n);}}ct.compileSchema=Ml;function N_(n,e,t){var r;t=(0, wt.resolveUrl)(this.opts.uriResolver,e,t);let i=n.refs[t];if(i)return i;let a=k_.call(this,n,t);if(a===void 0){let s=(r=n.localRefs)===null||r===void 0?void 0:r[t],{schemaId:o}=this.opts;s&&(a=new pr({schema:s,schemaId:o,root:n,baseId:e}));}if(a!==void 0)return n.refs[t]=F_.call(this,a)}ct.resolveRef=N_;function F_(n){return (0, wt.inlineRef)(n.schema,this.opts.inlineRefs)?n.schema:n.validate?n:Ml.call(this,n)}function mm(n){for(let e of this._compilations)if(I_(e,n))return e}ct.getCompilingSchema=mm;function I_(n,e){return n.schema===e.schema&&n.root===e.root&&n.baseId===e.baseId}function k_(n,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||$s.call(this,n,e)}function $s(n,e){let t=this.opts.uriResolver.parse(e),r=(0, wt._getFullPath)(this.opts.uriResolver,t),i=(0, wt.getFullPath)(this.opts.uriResolver,n.baseId,void 0);if(Object.keys(n.schema).length>0&&r===i)return Wl.call(this,t,n);let a=(0, wt.normalizeId)(r),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let o=$s.call(this,n,s);return typeof o?.schema!="object"?void 0:Wl.call(this,t,o)}if(typeof s?.schema=="object"){if(s.validate||Ml.call(this,s),a===(0, wt.normalizeId)(e)){let{schema:o}=s,{schemaId:u}=this.opts,l=o[u];return l&&(i=(0, wt.resolveUrl)(this.opts.uriResolver,i,l)),new pr({schema:o,schemaId:u,root:n,baseId:i})}return Wl.call(this,t,s)}}ct.resolveSchema=$s;var V_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Wl(n,{baseId:e,schema:t,root:r}){var i;if(((i=n.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let o of n.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let u=t[(0, pm.unescapeFragment)(o)];if(u===void 0)return;t=u;let l=typeof t=="object"&&t[this.opts.schemaId];!V_.has(o)&&l&&(e=(0, wt.resolveUrl)(this.opts.uriResolver,e,l));}let a;if(typeof t!="boolean"&&t.$ref&&!(0, pm.schemaHasRulesButRef)(t,this.RULES)){let o=(0, wt.resolveUrl)(this.opts.uriResolver,e,t.$ref);a=$s.call(this,r,o);}let{schemaId:s}=this.opts;if(a=a||new pr({schema:t,schemaId:s,root:r,baseId:e}),a.schema!==a.root.schema)return a}});var gm=S((gI,R_)=>{R_.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:false};});var Kl=S((yI,Em)=>{var $_=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Jl=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),j_=RegExp.prototype.test.bind(/^\d*$/u),$n=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),zl=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),vm=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Hl=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),L_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Ke=new Array(256);{let n="0123456789ABCDEF";for(let e=0;e<256;e++)Ke[e]="%"+n[e>>4]+n[e&15];}function Ie(n){return n<2048?Ke[192|n>>6]+Ke[128|n&63]:n<65536?Ke[224|n>>12]+Ke[128|n>>6&63]+Ke[128|n&63]:Ke[240|n>>18]+Ke[128|n>>12&63]+Ke[128|n>>6&63]+Ke[128|n&63]}function q_(n){let e="",t=0,r=0;for(r=0;r<n.length;r++)if(t=n[r].charCodeAt(0),t!==48){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return "";e+=n[r];break}for(r+=1;r<n.length;r++){if(t=n[r].charCodeAt(0),!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return "";e+=n[r];}return e}var B_=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),W_=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),M_=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),G_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function J_(n){if(n.length===0)return false;for(let e=0;e<n.length;e++)if(!M_(n[e])){if(n[e]==="%"&&e+2<n.length&&$n(n.slice(e+1,e+3))){e+=2;continue}return false}return true}function ym(n){let e=-1,t=0,r=-1,i=0;for(let o=0;o<n.length;o++)n[o]==="0"?(r===-1&&(r=o),i++,i>t&&(t=i,e=r)):(r=-1,i=0);if(t<2)return n.join(":");let a=n.slice(0,e).join(":"),s=n.slice(e+t).join(":");return a+"::"+s}function z_(n){let e=n.indexOf("::");if(e!==-1&&n.indexOf("::",e+1)!==-1)return;let t=e===-1?n.split(":"):n.slice(0,e).split(":"),r=e===-1?[]:n.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),r.length===1&&r[0]===""&&(r.length=0));let i=t.concat(r),a=0;for(let o=0;o<i.length;o++){let u=i[o];if(u==="")return;if(u.indexOf(".")!==-1){if(o!==i.length-1||e!==-1&&r.length===0||!Jl(u))return;a+=2;continue}if(!B_(u))return;i[o]=parseInt(u,16).toString(16),a++;}if(e===-1)return a!==8?void 0:ym(i);if(a>=8)return;let s=i.slice(0,t.length);for(let o=a;o<8;o++)s.push("0");for(let o=t.length;o<i.length;o++)s.push(i[o]);return ym(s)}function Gl(n){let e=n[0]==="["&&n[n.length-1]==="]";if((n[0]==="["||n[n.length-1]==="]")&&!e)return {host:n,isIPV6:false,error:true};let r=e?n.slice(1,-1):n;if(e&&W_(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:false,isIPVFuture:true};if(H_(r,":")<2)return {host:n,isIPV6:false,error:e};let i="",a=r.indexOf("%");if(a!==-1){let o=r.slice(a,a+3).toLowerCase()==="%25"?3:1;if(i=r.slice(a+o),!J_(i))return {host:n,isIPV6:false,error:true};r=r.slice(0,a);}let s=z_(r);return s===void 0?{host:n,isIPV6:false,error:true}:{host:s+(i?"%"+i:""),escapedHost:s+(i?"%25"+i:""),isIPV6:true}}function H_(n,e){let t=0;for(let r=0;r<n.length;r++)n[r]===e&&t++;return t}function U_(n){let e=n,t=[],r=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){t.push("/");break}else {t.push(e);break}}else if(i===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){t.push("/");break}}else if(i===3&&e==="/.."){t.length!==0&&t.pop(),t.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),t.length!==0&&t.pop();continue}}if((r=e.indexOf("/",1))===-1){t.push(e);break}else t.push(e.slice(0,r)),e=e.slice(r);}return t.join("")}var K_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},X_=/[@/?#:]/g,Y_=/[@/?#]/g;function Cm(n,e){let t=e?Y_:X_;return t.lastIndex=0,n.replace(t,r=>K_[r])}function bm(n,e=false){if(n.indexOf("%")===-1)return n;let t="";for(let r=0;r<n.length;r++){if(n[r]==="%"&&r+2<n.length){let i=n.slice(r+1,r+3);if($n(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));e&&zl(s)?t+=s:t+="%"+a,r+=2;continue}}t+=n[r];}return t}function Z_(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];if(r==="%"&&t+2<n.length){let i=n.slice(t+1,t+3);if($n(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));s!=="."&&zl(s)?e+=s:e+="%"+a,t+=2;continue}}if(vm(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=Sm(i)?r:Ke[i];else if(i<55296||i>57343)e+=Ie(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=Ie(65536+(i-55296<<10)+(a-56320)),t++):e+=Ie(65533);}else e+=Ie(65533);}}return e}function Q_(n,e=false){let t="",r=e&&n[0]!=="/";for(let i=0;i<n.length;i++){let a=n[i];if(a==="%"&&i+2<n.length){let s=n.slice(i+1,i+3);if($n(s)){t+="%"+s.toUpperCase(),i+=2;continue}}if(a==="/"&&(r=false),vm(a)&&(a!==":"||!r))t+=a;else {let s=n.charCodeAt(i);if(s<128)t+=Ke[s];else if(s<55296||s>57343)t+=Ie(s);else if(s<=56319&&i+1<n.length){let o=n.charCodeAt(i+1);o>=56320&&o<=57343?(t+=Ie(65536+(s-55296<<10)+(o-56320)),i++):t+=Ie(65533);}else t+=Ie(65533);}}return t}function Ul(n,e){let t="";for(let r=0;r<n.length;r++){let i=n[r];if(i==="%"&&r+2<n.length){let a=n.slice(r+1,r+3);if($n(a)){t+="%"+a.toUpperCase(),r+=2;continue}}if(e(i))t+=i;else {let a=n.charCodeAt(r);if(a<128)t+=Ke[a];else if(a<55296||a>57343)t+=Ie(a);else if(a<=56319&&r+1<n.length){let s=n.charCodeAt(r+1);s>=56320&&s<=57343?(t+=Ie(65536+(a-55296<<10)+(s-56320)),r++):t+=Ie(65533);}else t+=Ie(65533);}}return t}function _m(n){return Ul(n,L_)}function eS(n){return Ul(n,Hl)}function tS(n){return Ul(n,Hl)}function Sm(n){return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||n===42||n===43||n===45||n===46||n===47||n===64||n===95}function nS(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];if(r==="%"&&t+2<n.length){let i=n.slice(t+1,t+3);if($n(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));zl(s)?e+=s:e+="%"+a,t+=2;continue}}if(Hl(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=Sm(i)?r:Ke[i];else if(i<55296||i>57343)e+=Ie(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=Ie(65536+(i-55296<<10)+(a-56320)),t++):e+=Ie(65533);}else e+=Ie(65533);}}return e}function rS(n){let e="";for(let t=0;t<n.length;t++){if(n[t]==="%"&&t+2<n.length){let r=n.slice(t+1,t+3);if($n(r)){e+="%"+r.toUpperCase(),t+=2;continue}}e+=escape(n[t]);}return e}function iS(n){let e=[];if(n.userinfo!==void 0&&(e.push(_m(n.userinfo)),e.push("@")),n.host!==void 0){let t=n.host;if(!Jl(t)){let r=Gl(t);r.isIPV6!==true&&r.isIPVFuture!==true&&(t=bm(t,true),r=Gl(t)),r.isIPV6===true||r.isIPVFuture===true?t=`[${r.escapedHost}]`:t=Cm(t,false);}e.push(t);}if(typeof n.port=="number"||typeof n.port=="string"){let t=String(n.port);if(!j_(t))throw new TypeError("URI port is malformed.");e.push(":"),e.push(t);}return e.length?e.join(""):void 0}Em.exports={nonSimpleDomain:G_,recomposeAuthority:iS,reescapeHostDelimiters:Cm,normalizePercentEncoding:bm,normalizePathEncoding:Z_,serializePathEncoding:Q_,normalizeQueryFragmentEncoding:nS,encodeUserinfo:_m,encodeQuery:eS,encodeFragment:tS,escapePreservingEscapes:rS,removeDotSegments:U_,isIPv4:Jl,isUUID:$_,normalizeIPv6:Gl,stringArrayToHexStripped:q_};});var Om=S((vI,Pm)=>{var{isUUID:sS}=Kl(),aS=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,oS=["http","https","ws","wss","urn","urn:uuid"];function uS(n){return oS.indexOf(n)!==-1}function Xl(n){return n.secure===true?true:n.secure===false?false:n.scheme?n.scheme.length===3&&(n.scheme[0]==="w"||n.scheme[0]==="W")&&(n.scheme[1]==="s"||n.scheme[1]==="S")&&(n.scheme[2]==="s"||n.scheme[2]==="S"):false}function wm(n){return n.host||(n.error=n.error||"HTTP URIs must have a host."),n}function Dm(n){let e=String(n.scheme).toLowerCase()==="https";return (n.port===(e?443:80)||n.port==="")&&(n.port=void 0),n.path||(n.path="/"),n}function lS(n){return n.secure=Xl(n),n.resourceName=(n.path||"/")+(n.query?"?"+n.query:""),n.path=void 0,n.query=void 0,n}function cS(n){if((n.port===(Xl(n)?443:80)||n.port==="")&&(n.port=void 0),typeof n.secure=="boolean"&&(n.scheme=n.secure?"wss":"ws",n.secure=void 0),n.resourceName){let e=n.resourceName.indexOf("?"),t=e===-1?n.resourceName:n.resourceName.slice(0,e);n.path=t&&t!=="/"?t:void 0,n.query=e===-1?void 0:n.resourceName.slice(e+1),n.resourceName=void 0;}return n.fragment=void 0,n}function hS(n,e){if(!n.path)return n.error="URN can not be parsed",n;let t=n.path.match(aS);if(t&&t[0]===n.path){let r=e.scheme||n.scheme||"urn";n.nid=t[1].toLowerCase(),n.nss=t[2];let i=`${r}:${e.nid||n.nid}`,a=Yl(i);n.path=void 0,a&&(n=a.parse(n,e));}else n.error=n.error||"URN can not be parsed.";return n}function dS(n,e){if(n.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||n.scheme||"urn",r=n.nid.toLowerCase(),i=`${t}:${e.nid||r}`,a=Yl(i);a&&(n=a.serialize(n,e));let s=n,o=n.nss;return s.path=`${r||e.nid}:${o}`,e.skipEscape=true,s}function fS(n,e){let t=n;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!sS(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function pS(n){let e=n;return e.nss=(n.uuid||"").toLowerCase(),e}var Am={scheme:"http",domainHost:true,parse:wm,serialize:Dm},mS={scheme:"https",domainHost:Am.domainHost,parse:wm,serialize:Dm},js={scheme:"ws",domainHost:true,parse:lS,serialize:cS},gS={scheme:"wss",domainHost:js.domainHost,parse:js.parse,serialize:js.serialize},yS={scheme:"urn",parse:hS,serialize:dS,skipNormalize:true},vS={scheme:"urn:uuid",parse:fS,serialize:pS,skipNormalize:true},Ls={http:Am,https:mS,ws:js,wss:gS,urn:yS,"urn:uuid":vS};Object.setPrototypeOf(Ls,null);function Yl(n){return n&&(Ls[n]||Ls[n.toLowerCase()])||void 0}Pm.exports={wsIsSecure:Xl,SCHEMES:Ls,isValidSchemeName:uS,getSchemeHandler:Yl};});var Bm=S((CI,Ws)=>{var{normalizeIPv6:Im,removeDotSegments:yi,recomposeAuthority:CS,normalizePercentEncoding:Zl,normalizePathEncoding:bS,serializePathEncoding:xm,normalizeQueryFragmentEncoding:Tm,encodeQuery:_S,encodeFragment:SS,reescapeHostDelimiters:ES,isIPv4:km,nonSimpleDomain:wS}=Kl(),{SCHEMES:Vm,getSchemeHandler:Ql}=Om(),Rm=/^[A-Za-z][A-Za-z0-9+.-]*$/u,$m="URI scheme is malformed.";function Nm(n){let e=unescape(String(n));if(!Rm.test(e))throw new TypeError($m);return e}function DS(n,e){return typeof n=="string"?n=IS(n,e):typeof n=="object"&&(n=Bs(jn(n,e),e)),n}function AS(n,e,t){let r=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:a,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:u,malformedScheme:l}=qs(n,r),{parsed:c,malformedAuthorityOrPort:h,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:g,malformedScheme:m}=qs(e,r);if(a||h||s||f||o||p||u||g||l||m)throw new Error(i.error||c.error||"URI is malformed.");let C=jm(i,c,r,true),b=Ql(t&&t.scheme||C.scheme),v=C.host,d=v!==void 0&&v!==""&&(km(v)||Im(v).isIPV6);Lm(C,t||{},b,d);let _=v&&v.indexOf("%")!==-1&&!/\P{ASCII}/u.test(v);if(C.error&&!_)throw new Error(C.error);return r.skipEscape=true,jn(C,r)}function jm(n,e,t,r){let i={};return r||(n=Bs(jn(n,t),t),e=Bs(jn(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=yi(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=yi(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=yi(e.path):((n.userinfo!==void 0||n.host!==void 0||n.port!==void 0)&&!n.path?i.path="/"+e.path:n.path?i.path=n.path.slice(0,n.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=yi(i.path)),i.query=e.query):(i.path=n.path,e.query!==void 0?i.query=e.query:i.query=n.query),i.userinfo=n.userinfo,i.host=n.host,i.port=n.port),i.scheme=n.scheme),i.fragment=e.fragment,i}function PS(n,e,t){let r=Fm(n,t),i=Fm(e,t);return r!==void 0&&i!==void 0&&r===i}function jn(n,e){let t={host:n.host,scheme:n.scheme,userinfo:n.userinfo,port:n.port,path:n.path,query:n.query,nid:n.nid,nss:n.nss,uuid:n.uuid,fragment:n.fragment,reference:n.reference,resourceName:n.resourceName,secure:n.secure,error:""},r=Object.assign({},e),i=[];t.scheme&&(t.scheme=Nm(t.scheme));let a=Ql(r.scheme||t.scheme);a&&a.serialize&&a.serialize(t,r);let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,o=!r.skipEscape&&t.scheme===void 0&&!s;t.path!==void 0&&(r.skipEscape?t.path=Zl(t.path):t.path=xm(t.path,o)),r.reference!=="suffix"&&t.scheme&&(t.scheme=Nm(t.scheme),i.push(t.scheme,":"));let u=CS(t);if(u!==void 0&&(r.reference!=="suffix"&&i.push("//"),i.push(u),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!r.absolutePath&&(!a||!a.absolutePath)&&(l=yi(l)),o&&(l=xm(l,true)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l);}return t.query!==void 0&&i.push("?",_S(t.query)),t.fragment!==void 0&&i.push("#",SS(t.fragment)),i.join("")}var OS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,xS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,TS=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function NS(n,e){if(e[2]!==void 0&&n.path&&n.path[0]!=="/")return 'URI path must start with "/" when authority is present.';if(typeof n.port=="number"&&(n.port<0||n.port>65535))return "URI port is malformed."}function gi(n){if(n===void 0)return false;let e=n.indexOf("%");for(;e!==-1;){if(e+2>=n.length||!/^[\da-f]{2}$/iu.test(n.slice(e+1,e+3)))return true;e=n.indexOf("%",e+3);}return false}function ec(n){return n[0]==="["&&n[n.length-1]==="]"}function FS(n){let e=n[4];return gi(n[3])||e!==void 0&&!ec(e)&&gi(e)||gi(n[6])||gi(n[7])||gi(n[8])}function Lm(n,e,t,r){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&n.host&&!ec(n.host)&&(e.domainHost||t&&t.domainHost)&&r===false&&wS(n.host))try{n.host=new URL("http://"+n.host).hostname;}catch(i){return n.error=n.error||"Host's domain name can not be converted to ASCII: "+i,true}return false}function qs(n,e){let t=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=false,a=false,s=false,o=false,u=false,l=false,c=false;t.reference==="suffix"&&(t.scheme?n=t.scheme+":"+n:n="//"+n);let h=n.match(xS);h!==null&&h[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",i=true);let f=n.match(TS);if(f!==null){let g=f[1],m=g.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",i=true):g.length!==m.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",i=true));}let p=n.match(OS);if(p){if(r.scheme=p[1],r.userinfo=p[3],r.host=p[4],r.port=parseInt(p[5],10),r.path=p[6]||"",r.query=p[7],r.fragment=p[8],r.scheme!==void 0){let C=unescape(r.scheme);Rm.test(C)?r.scheme=C.toLowerCase():(r.error=r.error||$m,l=true);}a=FS(p),a&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=p[5]);let g=NS(r,p);if(g!==void 0&&(r.error=r.error||g,i=true),r.host)if(km(r.host)===false){let b=ec(r.host),v=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,d=Im(r.host);c=d.isIPV6||d.isIPVFuture===true,u=v&&(!b||d.error===true),r.host=c?d.host:d.host.toLowerCase(),u&&(r.error=r.error||"URI host is malformed.",i=true);}else c=true;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");let m=Ql(t.scheme||r.scheme);if(u||(o=Lm(r,t,m,c)),n.indexOf("%")!==-1&&r.host!==void 0&&!u){let C=c?r.host:Zl(r.host,true);c||(C=Zl(C.toLowerCase())),r.host=ES(C,c);}(!m||m&&!m.skipNormalize)&&(r.path&&(r.path=bS(r.path)),r.query&&(r.query=Tm(r.query)),r.fragment&&(r.fragment=Tm(r.fragment))),m&&m.parse&&(m.parse(r,t),m===Vm.urn&&r.nid===void 0&&(s=true));}else r.error=r.error||"URI can not be parsed.";return {parsed:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:l}}function Bs(n,e){return qs(n,e).parsed}function IS(n,e){return qm(n,e).normalized}function qm(n,e){let{parsed:t,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}=qs(n,e);return {normalized:r||i||a||s||o?n:jn(t,e),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}}function Fm(n,e){if(typeof n!="string"&&typeof n!="object")return;let t;try{t=typeof n=="string"?n:jn(n,e);}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:u}=qm(t,e);return i||a||s||o||u?void 0:r}var tc={SCHEMES:Vm,normalize:DS,resolve:AS,resolveComponent:jm,equal:PS,serialize:jn,parse:Bs};Ws.exports=tc;Ws.exports.default=tc;Ws.exports.fastUri=tc;});var Mm=S(nc=>{Object.defineProperty(nc,"__esModule",{value:true});var Wm=Bm();Wm.code='require("ajv/dist/runtime/uri").default';nc.default=Wm;});var sc=S(Pe=>{Object.defineProperty(Pe,"__esModule",{value:true});Pe.CodeGen=Pe.Name=Pe.nil=Pe.stringify=Pe.str=Pe._=Pe.KeywordCxt=void 0;var kS=dr();Object.defineProperty(Pe,"KeywordCxt",{enumerable:true,get:function(){return kS.KeywordCxt}});var mr=k();Object.defineProperty(Pe,"_",{enumerable:true,get:function(){return mr._}});Object.defineProperty(Pe,"str",{enumerable:true,get:function(){return mr.str}});Object.defineProperty(Pe,"stringify",{enumerable:true,get:function(){return mr.stringify}});Object.defineProperty(Pe,"nil",{enumerable:true,get:function(){return mr.nil}});Object.defineProperty(Pe,"Name",{enumerable:true,get:function(){return mr.Name}});Object.defineProperty(Pe,"CodeGen",{enumerable:true,get:function(){return mr.CodeGen}});var VS=pi(),Um=fr(),RS=wl(),vi=mi(),$S=k(),Ci=hi(),Ms=ci(),ic=q(),Gm=gm(),jS=Mm(),Km=(n,e)=>new RegExp(n,e);Km.code="new RegExp";var LS=["removeAdditional","useDefaults","coerceTypes"],qS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),BS={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},WS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Jm=200;function MS(n){var e,t,r,i,a,s,o,u,l,c,h,f,p,g,m,C,b,v,d,_,y,E,w,P,x;let H=n.strict,be=(e=n.code)===null||e===void 0?void 0:e.optimize,Jt=be===true||be===void 0?1:be||0,Kr=(r=(t=n.code)===null||t===void 0?void 0:t.regExp)!==null&&r!==void 0?r:Km,tr=(i=n.uriResolver)!==null&&i!==void 0?i:jS.default;return {strictSchema:(s=(a=n.strictSchema)!==null&&a!==void 0?a:H)!==null&&s!==void 0?s:true,strictNumbers:(u=(o=n.strictNumbers)!==null&&o!==void 0?o:H)!==null&&u!==void 0?u:true,strictTypes:(c=(l=n.strictTypes)!==null&&l!==void 0?l:H)!==null&&c!==void 0?c:"log",strictTuples:(f=(h=n.strictTuples)!==null&&h!==void 0?h:H)!==null&&f!==void 0?f:"log",strictRequired:(g=(p=n.strictRequired)!==null&&p!==void 0?p:H)!==null&&g!==void 0?g:false,code:n.code?{...n.code,optimize:Jt,regExp:Kr}:{optimize:Jt,regExp:Kr},loopRequired:(m=n.loopRequired)!==null&&m!==void 0?m:Jm,loopEnum:(C=n.loopEnum)!==null&&C!==void 0?C:Jm,meta:(b=n.meta)!==null&&b!==void 0?b:true,messages:(v=n.messages)!==null&&v!==void 0?v:true,inlineRefs:(d=n.inlineRefs)!==null&&d!==void 0?d:true,schemaId:(_=n.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(y=n.addUsedSchema)!==null&&y!==void 0?y:true,validateSchema:(E=n.validateSchema)!==null&&E!==void 0?E:true,validateFormats:(w=n.validateFormats)!==null&&w!==void 0?w:true,unicodeRegExp:(P=n.unicodeRegExp)!==null&&P!==void 0?P:true,int32range:(x=n.int32range)!==null&&x!==void 0?x:true,uriResolver:tr}}var bi=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...MS(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new $S.ValueScope({scope:{},prefixes:qS,es5:t,lines:r}),this.logger=KS(e.logger);let i=e.validateFormats;e.validateFormats=false,this.RULES=(0, RS.getRules)(),zm.call(this,BS,e,"NOT SUPPORTED"),zm.call(this,WS,e,"DEPRECATED","warn"),this._metaOpts=HS.call(this),e.formats&&JS.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&zS.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),GS.call(this),e.validateFormats=i;}_addVocabularies(){this.addKeyword("$async");}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=Gm;r==="id"&&(i={...Gm},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[r],false);}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);return "$async"in r||(this.errors=r.errors),i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(c,h){await a.call(this,c.$schema);let f=this._addSchema(c,h);return f.validate||s.call(this,f)}async function a(c){c&&!this.getSchema(c)&&await i.call(this,{$ref:c},true);}async function s(c){try{return this._compileSchemaEnv(c)}catch(h){if(!(h instanceof Um.default))throw h;return o.call(this,h),await u.call(this,h.missingSchema),s.call(this,c)}}function o({missingSchema:c,missingRef:h}){if(this.refs[c])throw new Error(`AnySchema ${c} is loaded but ${h} cannot be resolved`)}async function u(c){let h=await l.call(this,c);this.refs[c]||await a.call(this,h.$schema),this.refs[c]||this.addSchema(h,c,t);}async function l(c){let h=this._loading[c];if(h)return h;try{return await(this._loading[c]=r(c))}finally{delete this._loading[c];}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let a;if(typeof e=="object"){let{schemaId:s}=this.opts;if(a=e[s],a!==void 0&&typeof a!="string")throw new Error(`schema ${s} must be string`)}return t=(0, Ci.normalizeId)(t||a),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,true),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,true,r),this}validateSchema(e,t){if(typeof e=="boolean")return true;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,true;let i=this.validate(r,e);if(!i&&t){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return i}getSchema(e){let t;for(;typeof(t=Hm.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new vi.SchemaEnv({schema:{},schemaId:r});if(t=vi.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t;}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case "undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case "string":{let t=Hm.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case "object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0, Ci.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string")r=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(YS.call(this,r,t),!t)return (0, ic.eachItem)(r,a=>rc.call(this,a)),this;QS.call(this,t);let i={...t,type:(0, Ms.getJSONTypes)(t.type),schemaType:(0, Ms.getJSONTypes)(t.schemaType)};return (0, ic.eachItem)(r,i.type.length===0?a=>rc.call(this,a,i):a=>i.type.forEach(s=>rc.call(this,a,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let i=r.rules.findIndex(a=>a.keyword===e);i>=0&&r.rules.splice(i,1);}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return !e||e.length===0?"No errors":e.map(i=>`${r}${i.instancePath} ${i.message}`).reduce((i,a)=>i+t+a)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let a=i.split("/").slice(1),s=e;for(let o of a)s=s[o];for(let o in r){let u=r[o];if(typeof u!="object")continue;let{$data:l}=u.definition,c=s[o];l&&c&&(s[o]=Xm(c));}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];(!t||t.test(r))&&(typeof i=="string"?delete e[r]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[r]));}}_addSchema(e,t,r,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];else {if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(u!==void 0)return u;r=(0, Ci.normalizeId)(s||r);let l=Ci.getSchemaRefs.call(this,e,r);return u=new vi.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),a&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),i&&this.validateSchema(e,true),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):vi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{vi.compileSchema.call(this,e);}finally{this.opts=t;}}};bi.ValidationError=VS.default;bi.MissingRefError=Um.default;Pe.default=bi;function zm(n,e,t,r="error"){for(let i in n){let a=i;a in e&&this.logger[r](`${t}: option ${i}. ${n[a]}`);}}function Hm(n){return n=(0, Ci.normalizeId)(n),this.schemas[n]||this.refs[n]}function GS(){let n=this.opts.schemas;if(n)if(Array.isArray(n))this.addSchema(n);else for(let e in n)this.addSchema(n[e],e);}function JS(){for(let n in this.opts.formats){let e=this.opts.formats[n];e&&this.addFormat(n,e);}}function zS(n){if(Array.isArray(n)){this.addVocabulary(n);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in n){let t=n[e];t.keyword||(t.keyword=e),this.addKeyword(t);}}function HS(){let n={...this.opts};for(let e of LS)delete n[e];return n}var US={log(){},warn(){},error(){}};function KS(n){if(n===false)return US;if(n===void 0)return console;if(n.log&&n.warn&&n.error)return n;throw new Error("logger must implement log, warn and error methods")}var XS=/^[a-z_$][a-z0-9_$:-]*$/i;function YS(n,e){let{RULES:t}=this;if((0, ic.eachItem)(n,r=>{if(t.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!XS.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function rc(n,e,t){var r;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,s=i?a.post:a.rules.find(({type:u})=>u===t);if(s||(s={type:t,rules:[]},a.rules.push(s)),a.keywords[n]=true,!e)return;let o={keyword:n,definition:{...e,type:(0, Ms.getJSONTypes)(e.type),schemaType:(0, Ms.getJSONTypes)(e.schemaType)}};e.before?ZS.call(this,s,o,e.before):s.rules.push(o),a.all[n]=o,(r=e.implements)===null||r===void 0||r.forEach(u=>this.addKeyword(u));}function ZS(n,e,t){let r=n.rules.findIndex(i=>i.keyword===t);r>=0?n.rules.splice(r,0,e):(n.rules.push(e),this.logger.warn(`rule ${t} is not defined`));}function QS(n){let{metaSchema:e}=n;e!==void 0&&(n.$data&&this.opts.$data&&(e=Xm(e)),n.validateSchema=this.compile(e,true));}var eE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xm(n){return {anyOf:[n,eE]}}});var Ym=S(ac=>{Object.defineProperty(ac,"__esModule",{value:true});var tE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ac.default=tE;});var zs=S(Ln=>{Object.defineProperty(Ln,"__esModule",{value:true});Ln.callRef=Ln.getValidate=void 0;var nE=fr(),Zm=lt(),Xe=k(),gr=ut(),Qm=mi(),Gs=q(),rE={keyword:"$ref",schemaType:"string",code(n){let{gen:e,schema:t,it:r}=n,{baseId:i,schemaEnv:a,validateName:s,opts:o,self:u}=r,{root:l}=a;if((t==="#"||t==="#/")&&i===l.baseId)return h();let c=Qm.resolveRef.call(u,l,i,t);if(c===void 0)throw new nE.default(r.opts.uriResolver,i,t);if(c instanceof Qm.SchemaEnv)return f(c);return p(c);function h(){if(a===l)return Js(n,s,a,a.$async);let g=e.scopeValue("root",{ref:l});return Js(n,(0, Xe._)`${g}.validate`,l,l.$async)}function f(g){let m=eg(n,g);Js(n,m,g,g.$async);}function p(g){let m=e.scopeValue("schema",o.code.source===true?{ref:g,code:(0, Xe.stringify)(g)}:{ref:g}),C=e.name("valid"),b=n.subschema({schema:g,dataTypes:[],schemaPath:Xe.nil,topSchemaRef:m,errSchemaPath:t},C);n.mergeEvaluated(b),n.ok(C);}}};function eg(n,e){let{gen:t}=n;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0, Xe._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Ln.getValidate=eg;function Js(n,e,t,r){let{gen:i,it:a}=n,{allErrors:s,schemaEnv:o,opts:u}=a,l=u.passContext?gr.default.this:Xe.nil;r?c():h();function c(){if(!o.$async)throw new Error("async schema referenced by sync schema");let g=i.let("valid");i.try(()=>{i.code((0, Xe._)`await ${(0, Zm.callValidateCode)(n,e,l)}`),p(e),s||i.assign(g,true);},m=>{i.if((0, Xe._)`!(${m} instanceof ${a.ValidationError})`,()=>i.throw(m)),f(m),s||i.assign(g,false);}),n.ok(g);}function h(){n.result((0, Zm.callValidateCode)(n,e,l),()=>p(e),()=>f(e));}function f(g){let m=(0, Xe._)`${g}.errors`;i.assign(gr.default.vErrors,(0, Xe._)`${gr.default.vErrors} === null ? ${m} : ${gr.default.vErrors}.concat(${m})`),i.assign(gr.default.errors,(0, Xe._)`${gr.default.vErrors}.length`);}function p(g){var m;if(!a.opts.unevaluated)return;let C=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(a.props!==true)if(C&&!C.dynamicProps)C.props!==void 0&&(a.props=Gs.mergeEvaluated.props(i,C.props,a.props));else {let b=i.var("props",(0, Xe._)`${g}.evaluated.props`);a.props=Gs.mergeEvaluated.props(i,b,a.props,Xe.Name);}if(a.items!==true)if(C&&!C.dynamicItems)C.items!==void 0&&(a.items=Gs.mergeEvaluated.items(i,C.items,a.items));else {let b=i.var("items",(0, Xe._)`${g}.evaluated.items`);a.items=Gs.mergeEvaluated.items(i,b,a.items,Xe.Name);}}}Ln.callRef=Js;Ln.default=rE;});var uc=S(oc=>{Object.defineProperty(oc,"__esModule",{value:true});var iE=Ym(),sE=zs(),aE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",iE.default,sE.default];oc.default=aE;});var tg=S(lc=>{Object.defineProperty(lc,"__esModule",{value:true});var Hs=k(),fn=Hs.operators,Us={maximum:{okStr:"<=",ok:fn.LTE,fail:fn.GT},minimum:{okStr:">=",ok:fn.GTE,fail:fn.LT},exclusiveMaximum:{okStr:"<",ok:fn.LT,fail:fn.GTE},exclusiveMinimum:{okStr:">",ok:fn.GT,fail:fn.LTE}},oE={message:({keyword:n,schemaCode:e})=>(0, Hs.str)`must be ${Us[n].okStr} ${e}`,params:({keyword:n,schemaCode:e})=>(0, Hs._)`{comparison: ${Us[n].okStr}, limit: ${e}}`},uE={keyword:Object.keys(Us),type:"number",schemaType:"number",$data:true,error:oE,code(n){let{keyword:e,data:t,schemaCode:r}=n;n.fail$data((0, Hs._)`${t} ${Us[e].fail} ${r} || isNaN(${t})`);}};lc.default=uE;});var ng=S(cc=>{Object.defineProperty(cc,"__esModule",{value:true});var _i=k(),lE={message:({schemaCode:n})=>(0, _i.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0, _i._)`{multipleOf: ${n}}`},cE={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:lE,code(n){let{gen:e,data:t,schemaCode:r,it:i}=n,a=i.opts.multipleOfPrecision,s=e.let("res"),o=a?(0, _i._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0, _i._)`${s} !== parseInt(${s})`;n.fail$data((0, _i._)`(${r} === 0 || (${s} = ${t}/${r}, ${o}))`);}};cc.default=cE;});var ig=S(hc=>{Object.defineProperty(hc,"__esModule",{value:true});function rg(n){let e=n.length,t=0,r=0,i;for(;r<e;)t++,i=n.charCodeAt(r++),i>=55296&&i<=56319&&r<e&&(i=n.charCodeAt(r),(i&64512)===56320&&r++);return t}hc.default=rg;rg.code='require("ajv/dist/runtime/ucs2length").default';});var sg=S(dc=>{Object.defineProperty(dc,"__esModule",{value:true});var qn=k(),hE=q(),dE=ig(),fE={message({keyword:n,schemaCode:e}){let t=n==="maxLength"?"more":"fewer";return (0, qn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:n})=>(0, qn._)`{limit: ${n}}`},pE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:fE,code(n){let{keyword:e,data:t,schemaCode:r,it:i}=n,a=e==="maxLength"?qn.operators.GT:qn.operators.LT,s=i.opts.unicode===false?(0, qn._)`${t}.length`:(0, qn._)`${(0, hE.useFunc)(n.gen,dE.default)}(${t})`;n.fail$data((0, qn._)`${s} ${a} ${r}`);}};dc.default=pE;});var ag=S(fc=>{Object.defineProperty(fc,"__esModule",{value:true});var mE=lt(),gE=q(),yr=k(),yE={message:({schemaCode:n})=>(0, yr.str)`must match pattern "${n}"`,params:({schemaCode:n})=>(0, yr._)`{pattern: ${n}}`},vE={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:yE,code(n){let{gen:e,data:t,$data:r,schema:i,schemaCode:a,it:s}=n,o=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:u}=s.opts.code,l=u.code==="new RegExp"?(0, yr._)`new RegExp`:(0, gE.useFunc)(e,u),c=e.let("valid");e.try(()=>e.assign(c,(0, yr._)`${l}(${a}, ${o}).test(${t})`),()=>e.assign(c,false)),n.fail$data((0, yr._)`!${c}`);}else {let u=(0, mE.usePattern)(n,i);n.fail$data((0, yr._)`!${u}.test(${t})`);}}};fc.default=vE;});var og=S(pc=>{Object.defineProperty(pc,"__esModule",{value:true});var Si=k(),CE={message({keyword:n,schemaCode:e}){let t=n==="maxProperties"?"more":"fewer";return (0, Si.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:n})=>(0, Si._)`{limit: ${n}}`},bE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:CE,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxProperties"?Si.operators.GT:Si.operators.LT;n.fail$data((0, Si._)`Object.keys(${t}).length ${i} ${r}`);}};pc.default=bE;});var ug=S(mc=>{Object.defineProperty(mc,"__esModule",{value:true});var Ei=lt(),wi=k(),_E=q(),SE={message:({params:{missingProperty:n}})=>(0, wi.str)`must have required property '${n}'`,params:({params:{missingProperty:n}})=>(0, wi._)`{missingProperty: ${n}}`},EE={keyword:"required",type:"object",schemaType:"array",$data:true,error:SE,code(n){let{gen:e,schema:t,schemaCode:r,data:i,$data:a,it:s}=n,{opts:o}=s;if(!a&&t.length===0)return;let u=t.length>=o.loopRequired;if(s.allErrors?l():c(),o.strictRequired){let p=n.parentSchema.properties,{definedProperties:g}=n.it;for(let m of t)if(p?.[m]===void 0&&!g.has(m)){let C=s.schemaEnv.baseId+s.errSchemaPath,b=`required property "${m}" is not defined at "${C}" (strictRequired)`;(0, _E.checkStrictMode)(s,b,s.opts.strictRequired);}}function l(){if(u||a)n.block$data(wi.nil,h);else for(let p of t)(0, Ei.checkReportMissingProp)(n,p);}function c(){let p=e.let("missing");if(u||a){let g=e.let("valid",true);n.block$data(g,()=>f(p,g)),n.ok(g);}else e.if((0, Ei.checkMissingProp)(n,t,p)),(0, Ei.reportMissingProp)(n,p),e.else();}function h(){e.forOf("prop",r,p=>{n.setParams({missingProperty:p}),e.if((0, Ei.noPropertyInData)(e,i,p,o.ownProperties),()=>n.error());});}function f(p,g){n.setParams({missingProperty:p}),e.forOf(p,r,()=>{e.assign(g,(0, Ei.propertyInData)(e,i,p,o.ownProperties)),e.if((0, wi.not)(g),()=>{n.error(),e.break();});},wi.nil);}}};mc.default=EE;});var lg=S(gc=>{Object.defineProperty(gc,"__esModule",{value:true});var Di=k(),wE={message({keyword:n,schemaCode:e}){let t=n==="maxItems"?"more":"fewer";return (0, Di.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:n})=>(0, Di._)`{limit: ${n}}`},DE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:wE,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxItems"?Di.operators.GT:Di.operators.LT;n.fail$data((0, Di._)`${t}.length ${i} ${r}`);}};gc.default=DE;});var Ks=S(yc=>{Object.defineProperty(yc,"__esModule",{value:true});var cg=Fl();cg.code='require("ajv/dist/runtime/equal").default';yc.default=cg;});var hg=S(Cc=>{Object.defineProperty(Cc,"__esModule",{value:true});var vc=ci(),Oe=k(),AE=q(),PE=Ks(),OE={message:({params:{i:n,j:e}})=>(0, Oe.str)`must NOT have duplicate items (items ## ${e} and ${n} are identical)`,params:({params:{i:n,j:e}})=>(0, Oe._)`{i: ${n}, j: ${e}}`},xE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:OE,code(n){let{gen:e,data:t,$data:r,schema:i,parentSchema:a,schemaCode:s,it:o}=n;if(!r&&!i)return;let u=e.let("valid"),l=a.items?(0, vc.getSchemaTypes)(a.items):[];n.block$data(u,c,(0, Oe._)`${s} === false`),n.ok(u);function c(){let g=e.let("i",(0, Oe._)`${t}.length`),m=e.let("j");n.setParams({i:g,j:m}),e.assign(u,true),e.if((0, Oe._)`${g} > 1`,()=>(h()?f:p)(g,m));}function h(){return l.length>0&&!l.some(g=>g==="object"||g==="array")}function f(g,m){let C=e.name("item"),b=(0, vc.checkDataTypes)(l,C,o.opts.strictNumbers,vc.DataType.Wrong),v=e.const("indices",(0, Oe._)`{}`);e.for((0, Oe._)`;${g}--;`,()=>{e.let(C,(0, Oe._)`${t}[${g}]`),e.if(b,(0, Oe._)`continue`),l.length>1&&e.if((0, Oe._)`typeof ${C} == "string"`,(0, Oe._)`${C} += "_"`),e.if((0, Oe._)`typeof ${v}[${C}] == "number"`,()=>{e.assign(m,(0, Oe._)`${v}[${C}]`),n.error(),e.assign(u,false).break();}).code((0, Oe._)`${v}[${C}] = ${g}`);});}function p(g,m){let C=(0, AE.useFunc)(e,PE.default),b=e.name("outer");e.label(b).for((0, Oe._)`;${g}--;`,()=>e.for((0, Oe._)`${m} = ${g}; ${m}--;`,()=>e.if((0, Oe._)`${C}(${t}[${g}], ${t}[${m}])`,()=>{n.error(),e.assign(u,false).break(b);})));}}};Cc.default=xE;});var dg=S(_c=>{Object.defineProperty(_c,"__esModule",{value:true});var bc=k(),TE=q(),NE=Ks(),FE={message:"must be equal to constant",params:({schemaCode:n})=>(0, bc._)`{allowedValue: ${n}}`},IE={keyword:"const",$data:true,error:FE,code(n){let{gen:e,data:t,$data:r,schemaCode:i,schema:a}=n;r||a&&typeof a=="object"?n.fail$data((0, bc._)`!${(0, TE.useFunc)(e,NE.default)}(${t}, ${i})`):n.fail((0, bc._)`${a} !== ${t}`);}};_c.default=IE;});var fg=S(Sc=>{Object.defineProperty(Sc,"__esModule",{value:true});var Ai=k(),kE=q(),VE=Ks(),RE={message:"must be equal to one of the allowed values",params:({schemaCode:n})=>(0, Ai._)`{allowedValues: ${n}}`},$E={keyword:"enum",schemaType:"array",$data:true,error:RE,code(n){let{gen:e,data:t,$data:r,schema:i,schemaCode:a,it:s}=n;if(!r&&i.length===0)throw new Error("enum must have non-empty array");let o=i.length>=s.opts.loopEnum,u,l=()=>u??(u=(0, kE.useFunc)(e,VE.default)),c;if(o||r)c=e.let("valid"),n.block$data(c,h);else {if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",a);c=(0, Ai.or)(...i.map((g,m)=>f(p,m)));}n.pass(c);function h(){e.assign(c,false),e.forOf("v",a,p=>e.if((0, Ai._)`${l()}(${t}, ${p})`,()=>e.assign(c,true).break()));}function f(p,g){let m=i[g];return typeof m=="object"&&m!==null?(0, Ai._)`${l()}(${t}, ${p}[${g}])`:(0, Ai._)`${t} === ${m}`}}};Sc.default=$E;});var wc=S(Ec=>{Object.defineProperty(Ec,"__esModule",{value:true});var jE=tg(),LE=ng(),qE=sg(),BE=ag(),WE=og(),ME=ug(),GE=lg(),JE=hg(),zE=dg(),HE=fg(),UE=[jE.default,LE.default,qE.default,BE.default,WE.default,ME.default,GE.default,JE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},zE.default,HE.default];Ec.default=UE;});var Ac=S(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.validateAdditionalItems=void 0;var Bn=k(),Dc=q(),KE={message:({params:{len:n}})=>(0, Bn.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, Bn._)`{limit: ${n}}`},XE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:KE,code(n){let{parentSchema:e,it:t}=n,{items:r}=e;if(!Array.isArray(r)){(0, Dc.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}pg(n,r);}};function pg(n,e){let{gen:t,schema:r,data:i,keyword:a,it:s}=n;s.items=true;let o=t.const("len",(0, Bn._)`${i}.length`);if(r===false)n.setParams({len:e.length}),n.pass((0, Bn._)`${o} <= ${e.length}`);else if(typeof r=="object"&&!(0, Dc.alwaysValidSchema)(s,r)){let l=t.var("valid",(0, Bn._)`${o} <= ${e.length}`);t.if((0, Bn.not)(l),()=>u(l)),n.ok(l);}function u(l){t.forRange("i",e.length,o,c=>{n.subschema({keyword:a,dataProp:c,dataPropType:Dc.Type.Num},l),s.allErrors||t.if((0, Bn.not)(l),()=>t.break());});}}Pi.validateAdditionalItems=pg;Pi.default=XE;});var Pc=S(Oi=>{Object.defineProperty(Oi,"__esModule",{value:true});Oi.validateTuple=void 0;var mg=k(),Xs=q(),YE=lt(),ZE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(n){let{schema:e,it:t}=n;if(Array.isArray(e))return gg(n,"additionalItems",e);t.items=true,!(0, Xs.alwaysValidSchema)(t,e)&&n.ok((0, YE.validateArray)(n));}};function gg(n,e,t=n.schema){let{gen:r,parentSchema:i,data:a,keyword:s,it:o}=n;c(i),o.opts.unevaluated&&t.length&&o.items!==true&&(o.items=Xs.mergeEvaluated.items(r,t.length,o.items));let u=r.name("valid"),l=r.const("len",(0, mg._)`${a}.length`);t.forEach((h,f)=>{(0, Xs.alwaysValidSchema)(o,h)||(r.if((0, mg._)`${l} > ${f}`,()=>n.subschema({keyword:s,schemaProp:f,dataProp:f},u)),n.ok(u));});function c(h){let{opts:f,errSchemaPath:p}=o,g=t.length,m=g===h.minItems&&(g===h.maxItems||h[e]===false);if(f.strictTuples&&!m){let C=`"${s}" is ${g}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0, Xs.checkStrictMode)(o,C,f.strictTuples);}}}Oi.validateTuple=gg;Oi.default=ZE;});var yg=S(Oc=>{Object.defineProperty(Oc,"__esModule",{value:true});var QE=Pc(),ew={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0, QE.validateTuple)(n,"items")};Oc.default=ew;});var Cg=S(xc=>{Object.defineProperty(xc,"__esModule",{value:true});var vg=k(),tw=q(),nw=lt(),rw=Ac(),iw={message:({params:{len:n}})=>(0, vg.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, vg._)`{limit: ${n}}`},sw={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:iw,code(n){let{schema:e,parentSchema:t,it:r}=n,{prefixItems:i}=t;r.items=true,!(0, tw.alwaysValidSchema)(r,e)&&(i?(0, rw.validateAdditionalItems)(n,i):n.ok((0, nw.validateArray)(n)));}};xc.default=sw;});var bg=S(Tc=>{Object.defineProperty(Tc,"__esModule",{value:true});var ht=k(),Ys=q(),aw={message:({params:{min:n,max:e}})=>e===void 0?(0, ht.str)`must contain at least ${n} valid item(s)`:(0, ht.str)`must contain at least ${n} and no more than ${e} valid item(s)`,params:({params:{min:n,max:e}})=>e===void 0?(0, ht._)`{minContains: ${n}}`:(0, ht._)`{minContains: ${n}, maxContains: ${e}}`},ow={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:aw,code(n){let{gen:e,schema:t,parentSchema:r,data:i,it:a}=n,s,o,{minContains:u,maxContains:l}=r;a.opts.next?(s=u===void 0?1:u,o=l):s=1;let c=e.const("len",(0, ht._)`${i}.length`);if(n.setParams({min:s,max:o}),o===void 0&&s===0){(0, Ys.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(o!==void 0&&s>o){(0, Ys.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),n.fail();return}if((0, Ys.alwaysValidSchema)(a,t)){let m=(0, ht._)`${c} >= ${s}`;o!==void 0&&(m=(0, ht._)`${m} && ${c} <= ${o}`),n.pass(m);return}a.items=true;let h=e.name("valid");o===void 0&&s===1?p(h,()=>e.if(h,()=>e.break())):s===0?(e.let(h,true),o!==void 0&&e.if((0, ht._)`${i}.length > 0`,f)):(e.let(h,false),f()),n.result(h,()=>n.reset());function f(){let m=e.name("_valid"),C=e.let("count",0);p(m,()=>e.if(m,()=>g(C)));}function p(m,C){e.forRange("i",0,c,b=>{n.subschema({keyword:"contains",dataProp:b,dataPropType:Ys.Type.Num,compositeRule:true},m),C();});}function g(m){e.code((0, ht._)`${m}++`),o===void 0?e.if((0, ht._)`${m} >= ${s}`,()=>e.assign(h,true).break()):(e.if((0, ht._)`${m} > ${o}`,()=>e.assign(h,false).break()),s===1?e.assign(h,true):e.if((0, ht._)`${m} >= ${s}`,()=>e.assign(h,true)));}}};Tc.default=ow;});var Zs=S(It=>{Object.defineProperty(It,"__esModule",{value:true});It.validateSchemaDeps=It.validatePropertyDeps=It.error=void 0;var Nc=k(),uw=q(),xi=lt();It.error={message:({params:{property:n,depsCount:e,deps:t}})=>{let r=e===1?"property":"properties";return (0, Nc.str)`must have ${r} ${t} when property ${n} is present`},params:({params:{property:n,depsCount:e,deps:t,missingProperty:r}})=>(0, Nc._)`{property: ${n},
5
+ || ${s} === "boolean" || ${i} === null`).assign(o,(0, V._)`[${i}]`);}}}function EC({gen:n,parentData:e,parentDataProperty:t},r){n.if((0, V._)`${e} !== undefined`,()=>n.assign((0, V._)`${e}[${t}]`,r));}function Pl(n,e,t,r=hr.Correct){let i=r===hr.Correct?V.operators.EQ:V.operators.NEQ,a;switch(n){case "null":return (0, V._)`${e} ${i} null`;case "array":a=(0, V._)`Array.isArray(${e})`;break;case "object":a=(0, V._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case "integer":a=s((0, V._)`!(${e} % 1) && !isNaN(${e})`);break;case "number":a=s();break;default:return (0, V._)`typeof ${e} ${i} ${n}`}return r===hr.Correct?a:(0, V.not)(a);function s(o=V.nil){return (0, V.and)((0, V._)`typeof ${e} == "number"`,o,t?(0, V._)`isFinite(${e})`:V.nil)}}Ie.checkDataType=Pl;function xl(n,e,t,r){if(n.length===1)return Pl(n[0],e,t,r);let i,a=(0, $f.toHash)(n);if(a.array&&a.object){let s=(0, V._)`typeof ${e} != "object"`;i=a.null?s:(0, V._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object;}else i=V.nil;a.number&&delete a.integer;for(let s in a)i=(0, V.and)(i,Pl(s,e,t,r));return i}Ie.checkDataTypes=xl;var DC={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:e})=>typeof n=="string"?(0, V._)`{type: ${n}}`:(0, V._)`{type: ${e}}`};function Tl(n){let e=AC(n);(0, bC.reportError)(e,DC);}Ie.reportTypeError=Tl;function AC(n){let{gen:e,data:t,schema:r}=n,i=(0, $f.schemaRefOrVal)(n,r,"type");return {gen:e,keyword:"type",data:t,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:n}}});var Wf=_(Vs=>{Object.defineProperty(Vs,"__esModule",{value:true});Vs.assignDefaults=void 0;var dr=k(),OC=q();function PC(n,e){let{properties:t,items:r}=n.schema;if(e==="object"&&t)for(let i in t)Bf(n,i,t[i].default);else e==="array"&&Array.isArray(r)&&r.forEach((i,a)=>Bf(n,a,i.default));}Vs.assignDefaults=PC;function Bf(n,e,t){let{gen:r,compositeRule:i,data:a,opts:s}=n;if(t===void 0)return;let o=(0, dr._)`${a}${(0, dr.getProperty)(e)}`;if(i){(0, OC.checkStrictMode)(n,`default is ignored for: ${o}`);return}let u=(0, dr._)`${o} === undefined`;s.useDefaults==="empty"&&(u=(0, dr._)`${u} || ${o} === null || ${o} === ""`),r.if(u,(0, dr._)`${o} = ${(0, dr.stringify)(t)}`);}});var ht=_(ne=>{Object.defineProperty(ne,"__esModule",{value:true});ne.validateUnion=ne.validateArray=ne.usePattern=ne.callValidateCode=ne.schemaProperties=ne.allSchemaProperties=ne.noPropertyInData=ne.propertyInData=ne.isOwnProperty=ne.hasPropFunc=ne.reportMissingProp=ne.checkMissingProp=ne.checkReportMissingProp=void 0;var le=k(),Nl=q(),hn=ct(),xC=q();function TC(n,e){let{gen:t,data:r,it:i}=n;t.if(Il(t,r,e,i.opts.ownProperties),()=>{n.setParams({missingProperty:(0, le._)`${e}`},true),n.error();});}ne.checkReportMissingProp=TC;function NC({gen:n,data:e,it:{opts:t}},r,i){return (0, le.or)(...r.map(a=>(0, le.and)(Il(n,e,a,t.ownProperties),(0, le._)`${i} = ${a}`)))}ne.checkMissingProp=NC;function FC(n,e){n.setParams({missingProperty:e},true),n.error();}ne.reportMissingProp=FC;function Mf(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0, le._)`Object.prototype.hasOwnProperty`})}ne.hasPropFunc=Mf;function Fl(n,e,t){return (0, le._)`${Mf(n)}.call(${e}, ${t})`}ne.isOwnProperty=Fl;function IC(n,e,t,r){let i=(0, le._)`${e}${(0, le.getProperty)(t)} !== undefined`;return r?(0, le._)`${i} && ${Fl(n,e,t)}`:i}ne.propertyInData=IC;function Il(n,e,t,r){let i=(0, le._)`${e}${(0, le.getProperty)(t)} === undefined`;return r?(0, le.or)(i,(0, le.not)(Fl(n,e,t))):i}ne.noPropertyInData=Il;function Gf(n){return n?Object.keys(n).filter(e=>e!=="__proto__"):[]}ne.allSchemaProperties=Gf;function kC(n,e){return Gf(e).filter(t=>!(0, Nl.alwaysValidSchema)(n,e[t]))}ne.schemaProperties=kC;function VC({schemaCode:n,data:e,it:{gen:t,topSchemaRef:r,schemaPath:i,errorPath:a},it:s},o,u,l){let c=l?(0, le._)`${n}, ${e}, ${r}${i}`:e,h=[[hn.default.instancePath,(0, le.strConcat)(hn.default.instancePath,a)],[hn.default.parentData,s.parentData],[hn.default.parentDataProperty,s.parentDataProperty],[hn.default.rootData,hn.default.rootData]];s.opts.dynamicRef&&h.push([hn.default.dynamicAnchors,hn.default.dynamicAnchors]);let p=(0, le._)`${c}, ${t.object(...h)}`;return u!==le.nil?(0, le._)`${o}.call(${u}, ${p})`:(0, le._)`${o}(${p})`}ne.callValidateCode=VC;var RC=(0, le._)`new RegExp`;function jC({gen:n,it:{opts:e}},t){let r=e.unicodeRegExp?"u":"",{regExp:i}=e.code,a=i(t,r);return n.scopeValue("pattern",{key:a.toString(),ref:a,code:(0, le._)`${i.code==="new RegExp"?RC:(0, xC.useFunc)(n,i)}(${t}, ${r})`})}ne.usePattern=jC;function $C(n){let{gen:e,data:t,keyword:r,it:i}=n,a=e.name("valid");if(i.allErrors){let o=e.let("valid",true);return s(()=>e.assign(o,false)),o}return e.var(a,true),s(()=>e.break()),a;function s(o){let u=e.const("len",(0, le._)`${t}.length`);e.forRange("i",0,u,l=>{n.subschema({keyword:r,dataProp:l,dataPropType:Nl.Type.Num},a),e.if((0, le.not)(a),o);});}}ne.validateArray=$C;function LC(n){let{gen:e,schema:t,keyword:r,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(u=>(0, Nl.alwaysValidSchema)(i,u))&&!i.opts.unevaluated)return;let s=e.let("valid",false),o=e.name("_valid");e.block(()=>t.forEach((u,l)=>{let c=n.subschema({keyword:r,schemaProp:l,compositeRule:true},o);e.assign(s,(0, le._)`${s} || ${o}`),n.mergeValidEvaluated(c,o)||e.if((0, le.not)(s));})),n.result(s,()=>n.reset(),()=>n.error(true));}ne.validateUnion=LC;});var Hf=_(It=>{Object.defineProperty(It,"__esModule",{value:true});It.validateKeywordUsage=It.validSchemaType=It.funcKeywordCode=It.macroKeywordCode=void 0;var Me=k(),jn=ct(),qC=ht(),BC=hi();function WC(n,e){let{gen:t,keyword:r,schema:i,parentSchema:a,it:s}=n,o=e.macro.call(s.self,i,a,s),u=zf(t,r,o);s.opts.validateSchema!==false&&s.self.validateSchema(o,true);let l=t.name("valid");n.subschema({schema:o,schemaPath:Me.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:u,compositeRule:true},l),n.pass(l,()=>n.error(true));}It.macroKeywordCode=WC;function MC(n,e){var t;let{gen:r,keyword:i,schema:a,parentSchema:s,$data:o,it:u}=n;JC(u,e);let l=!o&&e.compile?e.compile.call(u.self,a,s,u):e.validate,c=zf(r,i,l),h=r.let("valid");n.block$data(h,p),n.ok((t=e.valid)!==null&&t!==void 0?t:h);function p(){if(e.errors===false)m(),e.modifying&&Jf(n),b(()=>n.error());else {let C=e.async?f():g();e.modifying&&Jf(n),b(()=>GC(n,C));}}function f(){let C=r.let("ruleErrs",null);return r.try(()=>m((0, Me._)`await `),v=>r.assign(h,false).if((0, Me._)`${v} instanceof ${u.ValidationError}`,()=>r.assign(C,(0, Me._)`${v}.errors`),()=>r.throw(v))),C}function g(){let C=(0, Me._)`${c}.errors`;return r.assign(C,null),m(Me.nil),C}function m(C=e.async?(0, Me._)`await `:Me.nil){let v=u.opts.passContext?jn.default.this:jn.default.self,d=!("compile"in e&&!o||e.schema===false);r.assign(h,(0, Me._)`${C}${(0, qC.callValidateCode)(n,c,v,d)}`,e.modifying);}function b(C){var v;r.if((0, Me.not)((v=e.valid)!==null&&v!==void 0?v:h),C);}}It.funcKeywordCode=MC;function Jf(n){let{gen:e,data:t,it:r}=n;e.if(r.parentData,()=>e.assign(t,(0, Me._)`${r.parentData}[${r.parentDataProperty}]`));}function GC(n,e){let{gen:t}=n;t.if((0, Me._)`Array.isArray(${e})`,()=>{t.assign(jn.default.vErrors,(0, Me._)`${jn.default.vErrors} === null ? ${e} : ${jn.default.vErrors}.concat(${e})`).assign(jn.default.errors,(0, Me._)`${jn.default.vErrors}.length`),(0, BC.extendErrors)(n);},()=>n.error());}function JC({schemaEnv:n},e){if(e.async&&!n.$async)throw new Error("async keyword in sync schema")}function zf(n,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return n.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0, Me.stringify)(t)})}function zC(n,e,t=false){return !e.length||e.some(r=>r==="array"?Array.isArray(n):r==="object"?n&&typeof n=="object"&&!Array.isArray(n):typeof n==r||t&&typeof n>"u")}It.validSchemaType=zC;function HC({schema:n,opts:e,self:t,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(o=>!Object.prototype.hasOwnProperty.call(n,o)))throw new Error(`parent schema must have dependencies of ${a}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(n[a])){let u=`keyword "${a}" value is invalid at path "${r}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(u);else throw new Error(u)}}It.validateKeywordUsage=HC;});var Kf=_(dn=>{Object.defineProperty(dn,"__esModule",{value:true});dn.extendSubschemaMode=dn.extendSubschemaData=dn.getSubschema=void 0;var kt=k(),Uf=q();function UC(n,{keyword:e,schemaProp:t,schema:r,schemaPath:i,errSchemaPath:a,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let o=n.schema[e];return t===void 0?{schema:o,schemaPath:(0, kt._)`${n.schemaPath}${(0, kt.getProperty)(e)}`,errSchemaPath:`${n.errSchemaPath}/${e}`}:{schema:o[t],schemaPath:(0, kt._)`${n.schemaPath}${(0, kt.getProperty)(e)}${(0, kt.getProperty)(t)}`,errSchemaPath:`${n.errSchemaPath}/${e}/${(0, Uf.escapeFragment)(t)}`}}if(r!==void 0){if(i===void 0||a===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return {schema:r,schemaPath:i,topSchemaRef:s,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}dn.getSubschema=UC;function KC(n,e,{dataProp:t,dataPropType:r,data:i,dataTypes:a,propertyName:s}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:o}=e;if(t!==void 0){let{errorPath:l,dataPathArr:c,opts:h}=e,p=o.let("data",(0, kt._)`${e.data}${(0, kt.getProperty)(t)}`,true);u(p),n.errorPath=(0, kt.str)`${l}${(0, Uf.getErrorPath)(t,r,h.jsPropertySyntax)}`,n.parentDataProperty=(0, kt._)`${t}`,n.dataPathArr=[...c,n.parentDataProperty];}if(i!==void 0){let l=i instanceof kt.Name?i:o.let("data",i,true);u(l),s!==void 0&&(n.propertyName=s);}a&&(n.dataTypes=a);function u(l){n.data=l,n.dataLevel=e.dataLevel+1,n.dataTypes=[],e.definedProperties=new Set,n.parentData=e.data,n.dataNames=[...e.dataNames,l];}}dn.extendSubschemaData=KC;function XC(n,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(n.compositeRule=r),i!==void 0&&(n.createErrors=i),a!==void 0&&(n.allErrors=a),n.jtdDiscriminator=e,n.jtdMetadata=t;}dn.extendSubschemaMode=XC;});var kl=_((eI,Xf)=>{Xf.exports=function n(e,t){if(e===t)return true;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return false;var r,i,a;if(Array.isArray(e)){if(r=e.length,r!=t.length)return false;for(i=r;i--!==0;)if(!n(e[i],t[i]))return false;return true}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(a=Object.keys(e),r=a.length,r!==Object.keys(t).length)return false;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[i]))return false;for(i=r;i--!==0;){var s=a[i];if(!n(e[s],t[s]))return false}return true}return e!==e&&t!==t};});var Zf=_((tI,Yf)=>{var pn=Yf.exports=function(n,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var r=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};Rs(e,r,i,n,"",n);};pn.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};pn.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};pn.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};pn.skipKeywords={default:true,enum:true,const:true,required:true,maximum:true,minimum:true,exclusiveMaximum:true,exclusiveMinimum:true,multipleOf:true,maxLength:true,minLength:true,pattern:true,format:true,maxItems:true,minItems:true,uniqueItems:true,maxProperties:true,minProperties:true};function Rs(n,e,t,r,i,a,s,o,u,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,i,a,s,o,u,l);for(var c in r){var h=r[c];if(Array.isArray(h)){if(c in pn.arrayKeywords)for(var p=0;p<h.length;p++)Rs(n,e,t,h[p],i+"/"+c+"/"+p,a,i,c,r,p);}else if(c in pn.propsKeywords){if(h&&typeof h=="object")for(var f in h)Rs(n,e,t,h[f],i+"/"+c+"/"+YC(f),a,i,c,r,f);}else (c in pn.keywords||n.allKeys&&!(c in pn.skipKeywords))&&Rs(n,e,t,h,i+"/"+c,a,i,c,r);}t(r,i,a,s,o,u,l);}}function YC(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}});var pi=_(Xe=>{Object.defineProperty(Xe,"__esModule",{value:true});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var ZC=q(),QC=kl(),eS=Zf(),tS=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function nS(n,e=true){return typeof n=="boolean"?true:e===true?!Vl(n):e?Qf(n)<=e:false}Xe.inlineRef=nS;var rS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Vl(n){for(let e in n){if(rS.has(e))return true;let t=n[e];if(Array.isArray(t)&&t.some(Vl)||typeof t=="object"&&Vl(t))return true}return false}function Qf(n){let e=0;for(let t in n){if(t==="$ref")return 1/0;if(e++,!tS.has(t)&&(typeof n[t]=="object"&&(0, ZC.eachItem)(n[t],r=>e+=Qf(r)),e===1/0))return 1/0}return e}function em(n,e="",t){t!==false&&(e=pr(e));let r=n.parse(e);return tm(n,r)}Xe.getFullPath=em;function tm(n,e){return n.serialize(e).split("#")[0]+"#"}Xe._getFullPath=tm;var iS=/#\/?$/;function pr(n){return n?n.replace(iS,""):""}Xe.normalizeId=pr;function sS(n,e,t){return t=pr(t),n.resolve(e,t)}Xe.resolveUrl=sS;var aS=/^[a-z_][-a-z0-9._]*$/i;function oS(n,e){if(typeof n=="boolean")return {};let{schemaId:t,uriResolver:r}=this.opts,i=pr(n[t]||e),a={"":i},s=em(r,i,false),o={},u=new Set;return eS(n,{allKeys:true},(h,p,f,g)=>{if(g===void 0)return;let m=s+p,b=a[g];typeof h[t]=="string"&&(b=C.call(this,h[t])),v.call(this,h.$anchor),v.call(this,h.$dynamicAnchor),a[p]=b;function C(d){let S=this.opts.uriResolver.resolve;if(d=pr(b?S(b,d):d),u.has(d))throw c(d);u.add(d);let y=this.refs[d];return typeof y=="string"&&(y=this.refs[y]),typeof y=="object"?l(h,y.schema,d):d!==pr(m)&&(d[0]==="#"?(l(h,o[d],d),o[d]=h):this.refs[d]=m),d}function v(d){if(typeof d=="string"){if(!aS.test(d))throw new Error(`invalid anchor "${d}"`);C.call(this,`#${d}`);}}}),o;function l(h,p,f){if(p!==void 0&&!QC(h,p))throw c(f)}function c(h){return new Error(`reference "${h}" resolves to more than one schema`)}}Xe.getSchemaRefs=oS;});var fr=_(fn=>{Object.defineProperty(fn,"__esModule",{value:true});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var am=Vf(),nm=di(),jl=Ol(),js=di(),uS=Wf(),mi=Hf(),Rl=Kf(),P=k(),F=ct(),lS=pi(),Qt=q(),fi=hi();function cS(n){if(lm(n)&&(cm(n),um(n))){pS(n);return}om(n,()=>(0, am.topBoolOrEmptySchema)(n));}fn.validateFunctionCode=cS;function om({gen:n,validateName:e,schema:t,schemaEnv:r,opts:i},a){i.code.es5?n.func(e,(0, P._)`${F.default.data}, ${F.default.valCxt}`,r.$async,()=>{n.code((0, P._)`"use strict"; ${rm(t,i)}`),dS(n,i),n.code(a);}):n.func(e,(0, P._)`${F.default.data}, ${hS(i)}`,r.$async,()=>n.code(rm(t,i)).code(a));}function hS(n){return (0, P._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${n.dynamicRef?(0, P._)`, ${F.default.dynamicAnchors}={}`:P.nil}}={}`}function dS(n,e){n.if(F.default.valCxt,()=>{n.var(F.default.instancePath,(0, P._)`${F.default.valCxt}.${F.default.instancePath}`),n.var(F.default.parentData,(0, P._)`${F.default.valCxt}.${F.default.parentData}`),n.var(F.default.parentDataProperty,(0, P._)`${F.default.valCxt}.${F.default.parentDataProperty}`),n.var(F.default.rootData,(0, P._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&n.var(F.default.dynamicAnchors,(0, P._)`${F.default.valCxt}.${F.default.dynamicAnchors}`);},()=>{n.var(F.default.instancePath,(0, P._)`""`),n.var(F.default.parentData,(0, P._)`undefined`),n.var(F.default.parentDataProperty,(0, P._)`undefined`),n.var(F.default.rootData,F.default.data),e.dynamicRef&&n.var(F.default.dynamicAnchors,(0, P._)`{}`);});}function pS(n){let{schema:e,opts:t,gen:r}=n;om(n,()=>{t.$comment&&e.$comment&&dm(n),vS(n),r.let(F.default.vErrors,null),r.let(F.default.errors,0),t.unevaluated&&fS(n),hm(n),SS(n);});}function fS(n){let{gen:e,validateName:t}=n;n.evaluated=e.const("evaluated",(0, P._)`${t}.evaluated`),e.if((0, P._)`${n.evaluated}.dynamicProps`,()=>e.assign((0, P._)`${n.evaluated}.props`,(0, P._)`undefined`)),e.if((0, P._)`${n.evaluated}.dynamicItems`,()=>e.assign((0, P._)`${n.evaluated}.items`,(0, P._)`undefined`));}function rm(n,e){let t=typeof n=="object"&&n[e.schemaId];return t&&(e.code.source||e.code.process)?(0, P._)`/*# sourceURL=${t} */`:P.nil}function mS(n,e){if(lm(n)&&(cm(n),um(n))){gS(n,e);return}(0, am.boolOrEmptySchema)(n,e);}function um({schema:n,self:e}){if(typeof n=="boolean")return !n;for(let t in n)if(e.RULES.all[t])return true;return false}function lm(n){return typeof n.schema!="boolean"}function gS(n,e){let{schema:t,gen:r,opts:i}=n;i.$comment&&t.$comment&&dm(n),bS(n),CS(n);let a=r.const("_errs",F.default.errors);hm(n,a),r.var(e,(0, P._)`${a} === ${F.default.errors}`);}function cm(n){(0, Qt.checkUnknownRules)(n),yS(n);}function hm(n,e){if(n.opts.jtd)return im(n,[],false,e);let t=(0, nm.getSchemaTypes)(n.schema),r=(0, nm.coerceAndCheckDataType)(n,t);im(n,t,!r,e);}function yS(n){let{schema:e,errSchemaPath:t,opts:r,self:i}=n;e.$ref&&r.ignoreKeywordsWithRef&&(0, Qt.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`);}function vS(n){let{schema:e,opts:t}=n;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0, Qt.checkStrictMode)(n,"default is ignored in the schema root");}function bS(n){let e=n.schema[n.opts.schemaId];e&&(n.baseId=(0, lS.resolveUrl)(n.opts.uriResolver,n.baseId,e));}function CS(n){if(n.schema.$async&&!n.schemaEnv.$async)throw new Error("async schema in sync schema")}function dm({gen:n,schemaEnv:e,schema:t,errSchemaPath:r,opts:i}){let a=t.$comment;if(i.$comment===true)n.code((0, P._)`${F.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let s=(0, P.str)`${r}/$comment`,o=n.scopeValue("root",{ref:e.root});n.code((0, P._)`${F.default.self}.opts.$comment(${a}, ${s}, ${o}.schema)`);}}function SS(n){let{gen:e,schemaEnv:t,validateName:r,ValidationError:i,opts:a}=n;t.$async?e.if((0, P._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0, P._)`new ${i}(${F.default.vErrors})`)):(e.assign((0, P._)`${r}.errors`,F.default.vErrors),a.unevaluated&&_S(n),e.return((0, P._)`${F.default.errors} === 0`));}function _S({gen:n,evaluated:e,props:t,items:r}){t instanceof P.Name&&n.assign((0, P._)`${e}.props`,t),r instanceof P.Name&&n.assign((0, P._)`${e}.items`,r);}function im(n,e,t,r){let{gen:i,schema:a,data:s,allErrors:o,opts:u,self:l}=n,{RULES:c}=l;if(a.$ref&&(u.ignoreKeywordsWithRef||!(0, Qt.schemaHasRulesButRef)(a,c))){i.block(()=>fm(n,"$ref",c.all.$ref.definition));return}u.jtd||wS(n,e),i.block(()=>{for(let p of c.rules)h(p);h(c.post);});function h(p){(0, jl.shouldUseGroup)(a,p)&&(p.type?(i.if((0, js.checkDataType)(p.type,s,u.strictNumbers)),sm(n,p),e.length===1&&e[0]===p.type&&t&&(i.else(),(0, js.reportTypeError)(n)),i.endIf()):sm(n,p),o||i.if((0, P._)`${F.default.errors} === ${r||0}`));}}function sm(n,e){let{gen:t,schema:r,opts:{useDefaults:i}}=n;i&&(0, uS.assignDefaults)(n,e.type),t.block(()=>{for(let a of e.rules)(0, jl.shouldUseRule)(r,a)&&fm(n,a.keyword,a.definition,e.type);});}function wS(n,e){n.schemaEnv.meta||!n.opts.strictTypes||(ES(n,e),n.opts.allowUnionTypes||DS(n,e),AS(n,n.dataTypes));}function ES(n,e){if(e.length){if(!n.dataTypes.length){n.dataTypes=e;return}e.forEach(t=>{pm(n.dataTypes,t)||$l(n,`type "${t}" not allowed by context "${n.dataTypes.join(",")}"`);}),PS(n,e);}}function DS(n,e){e.length>1&&!(e.length===2&&e.includes("null"))&&$l(n,"use allowUnionTypes to allow union type keyword");}function AS(n,e){let t=n.self.RULES.all;for(let r in t){let i=t[r];if(typeof i=="object"&&(0, jl.shouldUseRule)(n.schema,i)){let{type:a}=i.definition;a.length&&!a.some(s=>OS(e,s))&&$l(n,`missing type "${a.join(",")}" for keyword "${r}"`);}}}function OS(n,e){return n.includes(e)||e==="number"&&n.includes("integer")}function pm(n,e){return n.includes(e)||e==="integer"&&n.includes("number")}function PS(n,e){let t=[];for(let r of n.dataTypes)pm(e,r)?t.push(r):e.includes("integer")&&r==="number"&&t.push("integer");n.dataTypes=t;}function $l(n,e){let t=n.schemaEnv.baseId+n.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0, Qt.checkStrictMode)(n,e,n.opts.strictTypes);}var $s=class{constructor(e,t,r){if((0, mi.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0, Qt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",mm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0, mi.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==false)&&(this.errsCount=e.gen.const("_errs",F.default.errors));}result(e,t,r){this.failResult((0, P.not)(e),t,r);}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else();}pass(e,t){this.failResult((0, P.not)(e),void 0,t);}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(false);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else();}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0, P._)`${t} !== undefined && (${(0, P.or)(this.invalid$data(),e)})`);}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r);}_error(e,t){(e?fi.reportExtraError:fi.reportError)(this,this.def.error,t);}$dataError(){(0, fi.reportError)(this,this.def.$dataError||fi.keyword$DataError);}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0, fi.resetErrorsCount)(this.gen,this.errsCount);}ok(e){this.allErrors||this.gen.if(e);}setParams(e,t){t?Object.assign(this.params,e):this.params=e;}block$data(e,t,r=P.nil){this.gen.block(()=>{this.check$data(e,r),t();});}check$data(e=P.nil,t=P.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:a,def:s}=this;r.if((0, P.or)((0, P._)`${i} === undefined`,t)),e!==P.nil&&r.assign(e,true),(a.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==P.nil&&r.assign(e,false)),r.else();}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:a}=this;return (0, P.or)(s(),o());function s(){if(r.length){if(!(t instanceof P.Name))throw new Error("ajv implementation error");let u=Array.isArray(r)?r:[r];return (0, P._)`${(0, js.checkDataTypes)(u,t,a.opts.strictNumbers,js.DataType.Wrong)}`}return P.nil}function o(){if(i.validateSchema){let u=e.scopeValue("validate$data",{ref:i.validateSchema});return (0, P._)`!${u}(${t})`}return P.nil}}subschema(e,t){let r=(0, Rl.getSubschema)(this.it,e);(0, Rl.extendSubschemaData)(r,this.it,e),(0, Rl.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return mS(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;r.opts.unevaluated&&(r.props!==true&&e.props!==void 0&&(r.props=Qt.mergeEvaluated.props(i,e.props,r.props,t)),r.items!==true&&e.items!==void 0&&(r.items=Qt.mergeEvaluated.items(i,e.items,r.items,t)));}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==true||r.items!==true))return i.if(t,()=>this.mergeEvaluated(e,P.Name)),true}};fn.KeywordCxt=$s;function fm(n,e,t,r){let i=new $s(n,t,e);"code"in t?t.code(i,r):i.$data&&t.validate?(0, mi.funcKeywordCode)(i,t):"macro"in t?(0, mi.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0, mi.funcKeywordCode)(i,t);}var xS=/^\/(?:[^~]|~0|~1)*$/,TS=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function mm(n,{dataLevel:e,dataNames:t,dataPathArr:r}){let i,a;if(n==="")return F.default.rootData;if(n[0]==="/"){if(!xS.test(n))throw new Error(`Invalid JSON-pointer: ${n}`);i=n,a=F.default.rootData;}else {let l=TS.exec(n);if(!l)throw new Error(`Invalid JSON-pointer: ${n}`);let c=+l[1];if(i=l[2],i==="#"){if(c>=e)throw new Error(u("property/index",c));return r[e-c]}if(c>e)throw new Error(u("data",c));if(a=t[e-c],!i)return a}let s=a,o=i.split("/");for(let l of o)l&&(a=(0, P._)`${a}${(0, P.getProperty)((0, Qt.unescapeJsonPointer)(l))}`,s=(0, P._)`${s} && ${a}`);return s;function u(l,c){return `Cannot access ${l} ${c} levels up, current level is ${e}`}}fn.getData=mm;});var gi=_(ql=>{Object.defineProperty(ql,"__esModule",{value:true});var Ll=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=true;}};ql.default=Ll;});var mr=_(Ml=>{Object.defineProperty(Ml,"__esModule",{value:true});var Bl=pi(),Wl=class extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0, Bl.resolveUrl)(e,t,r),this.missingSchema=(0, Bl.normalizeId)((0, Bl.getFullPath)(e,this.missingRef));}};Ml.default=Wl;});var yi=_(dt=>{Object.defineProperty(dt,"__esModule",{value:true});dt.resolveSchema=dt.getCompilingSchema=dt.resolveRef=dt.compileSchema=dt.SchemaEnv=void 0;var Dt=k(),NS=gi(),$n=ct(),At=pi(),gm=q(),FS=fr(),gr=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0, At.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={};}};dt.SchemaEnv=gr;function Jl(n){let e=ym.call(this,n);if(e)return e;let t=(0, At.getFullPath)(this.opts.uriResolver,n.root.baseId),{es5:r,lines:i}=this.opts.code,{ownProperties:a}=this.opts,s=new Dt.CodeGen(this.scope,{es5:r,lines:i,ownProperties:a}),o;n.$async&&(o=s.scopeValue("Error",{ref:NS.default,code:(0, Dt._)`require("ajv/dist/runtime/validation_error").default`}));let u=s.scopeName("validate");n.validateName=u;let l={gen:s,allErrors:this.opts.allErrors,data:$n.default.data,parentData:$n.default.parentData,parentDataProperty:$n.default.parentDataProperty,dataNames:[$n.default.data],dataPathArr:[Dt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===true?{ref:n.schema,code:(0, Dt.stringify)(n.schema)}:{ref:n.schema}),validateName:u,ValidationError:o,schema:n.schema,schemaEnv:n,rootId:t,baseId:n.baseId||t,schemaPath:Dt.nil,errSchemaPath:n.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0, Dt._)`""`,opts:this.opts,self:this},c;try{this._compilations.add(n),(0,FS.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let h=s.toString();c=`${s.scopeRefs($n.default.scope)}return ${h}`,this.opts.code.process&&(c=this.opts.code.process(c,n));let f=new Function(`${$n.default.self}`,`${$n.default.scope}`,c)(this,this.scope.get());if(this.scope.value(u,{ref:f}),f.errors=null,f.schema=n.schema,f.schemaEnv=n,n.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:u,validateCode:h,scopeValues:s._values}),this.opts.unevaluated){let{props:g,items:m}=l;f.evaluated={props:g instanceof Dt.Name?void 0:g,items:m instanceof Dt.Name?void 0:m,dynamicProps:g instanceof Dt.Name,dynamicItems:m instanceof Dt.Name},f.source&&(f.source.evaluated=(0,Dt.stringify)(f.evaluated));}return n.validate=f,n}catch(h){throw delete n.validate,delete n.validateName,c&&this.logger.error("Error compiling schema, function code:",c),h}finally{this._compilations.delete(n);}}dt.compileSchema=Jl;function IS(n,e,t){var r;t=(0, At.resolveUrl)(this.opts.uriResolver,e,t);let i=n.refs[t];if(i)return i;let a=RS.call(this,n,t);if(a===void 0){let s=(r=n.localRefs)===null||r===void 0?void 0:r[t],{schemaId:o}=this.opts;s&&(a=new gr({schema:s,schemaId:o,root:n,baseId:e}));}if(a!==void 0)return n.refs[t]=kS.call(this,a)}dt.resolveRef=IS;function kS(n){return (0, At.inlineRef)(n.schema,this.opts.inlineRefs)?n.schema:n.validate?n:Jl.call(this,n)}function ym(n){for(let e of this._compilations)if(VS(e,n))return e}dt.getCompilingSchema=ym;function VS(n,e){return n.schema===e.schema&&n.root===e.root&&n.baseId===e.baseId}function RS(n,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ls.call(this,n,e)}function Ls(n,e){let t=this.opts.uriResolver.parse(e),r=(0, At._getFullPath)(this.opts.uriResolver,t),i=(0, At.getFullPath)(this.opts.uriResolver,n.baseId,void 0);if(Object.keys(n.schema).length>0&&r===i)return Gl.call(this,t,n);let a=(0, At.normalizeId)(r),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let o=Ls.call(this,n,s);return typeof o?.schema!="object"?void 0:Gl.call(this,t,o)}if(typeof s?.schema=="object"){if(s.validate||Jl.call(this,s),a===(0, At.normalizeId)(e)){let{schema:o}=s,{schemaId:u}=this.opts,l=o[u];return l&&(i=(0, At.resolveUrl)(this.opts.uriResolver,i,l)),new gr({schema:o,schemaId:u,root:n,baseId:i})}return Gl.call(this,t,s)}}dt.resolveSchema=Ls;var jS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gl(n,{baseId:e,schema:t,root:r}){var i;if(((i=n.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let o of n.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let u=t[(0, gm.unescapeFragment)(o)];if(u===void 0)return;t=u;let l=typeof t=="object"&&t[this.opts.schemaId];!jS.has(o)&&l&&(e=(0, At.resolveUrl)(this.opts.uriResolver,e,l));}let a;if(typeof t!="boolean"&&t.$ref&&!(0, gm.schemaHasRulesButRef)(t,this.RULES)){let o=(0, At.resolveUrl)(this.opts.uriResolver,e,t.$ref);a=Ls.call(this,r,o);}let{schemaId:s}=this.opts;if(a=a||new gr({schema:t,schemaId:s,root:r,baseId:e}),a.schema!==a.root.schema)return a}});var vm=_((oI,$S)=>{$S.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:false};});var Yl=_((uI,Dm)=>{var LS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Hl=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),qS=RegExp.prototype.test.bind(/^\d*$/u),Ln=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ul=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Cm=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Kl=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),BS=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Ye=new Array(256);{let n="0123456789ABCDEF";for(let e=0;e<256;e++)Ye[e]="%"+n[e>>4]+n[e&15];}function ke(n){return n<2048?Ye[192|n>>6]+Ye[128|n&63]:n<65536?Ye[224|n>>12]+Ye[128|n>>6&63]+Ye[128|n&63]:Ye[240|n>>18]+Ye[128|n>>12&63]+Ye[128|n>>6&63]+Ye[128|n&63]}function WS(n){let e="",t=0,r=0;for(r=0;r<n.length;r++)if(t=n[r].charCodeAt(0),t!==48){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return "";e+=n[r];break}for(r+=1;r<n.length;r++){if(t=n[r].charCodeAt(0),!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return "";e+=n[r];}return e}var MS=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),GS=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),JS=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),zS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function HS(n){if(n.length===0)return false;for(let e=0;e<n.length;e++)if(!JS(n[e])){if(n[e]==="%"&&e+2<n.length&&Ln(n.slice(e+1,e+3))){e+=2;continue}return false}return true}function bm(n){let e=-1,t=0,r=-1,i=0;for(let o=0;o<n.length;o++)n[o]==="0"?(r===-1&&(r=o),i++,i>t&&(t=i,e=r)):(r=-1,i=0);if(t<2)return n.join(":");let a=n.slice(0,e).join(":"),s=n.slice(e+t).join(":");return a+"::"+s}function US(n){let e=n.indexOf("::");if(e!==-1&&n.indexOf("::",e+1)!==-1)return;let t=e===-1?n.split(":"):n.slice(0,e).split(":"),r=e===-1?[]:n.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),r.length===1&&r[0]===""&&(r.length=0));let i=t.concat(r),a=0;for(let o=0;o<i.length;o++){let u=i[o];if(u==="")return;if(u.indexOf(".")!==-1){if(o!==i.length-1||e!==-1&&r.length===0||!Hl(u))return;a+=2;continue}if(!MS(u))return;i[o]=parseInt(u,16).toString(16),a++;}if(e===-1)return a!==8?void 0:bm(i);if(a>=8)return;let s=i.slice(0,t.length);for(let o=a;o<8;o++)s.push("0");for(let o=t.length;o<i.length;o++)s.push(i[o]);return bm(s)}function zl(n){let e=n[0]==="["&&n[n.length-1]==="]";if((n[0]==="["||n[n.length-1]==="]")&&!e)return {host:n,isIPV6:false,error:true};let r=e?n.slice(1,-1):n;if(e&&GS(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:false,isIPVFuture:true};if(KS(r,":")<2)return {host:n,isIPV6:false,error:e};let i="",a=r.indexOf("%");if(a!==-1){let o=r.slice(a,a+3).toLowerCase()==="%25"?3:1;if(i=r.slice(a+o),!HS(i))return {host:n,isIPV6:false,error:true};r=r.slice(0,a);}let s=US(r);return s===void 0?{host:n,isIPV6:false,error:true}:{host:s+(i?"%"+i:""),escapedHost:s+(i?"%25"+i:""),isIPV6:true}}function KS(n,e){let t=0;for(let r=0;r<n.length;r++)n[r]===e&&t++;return t}function XS(n){let e=n,t=[],r=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){t.push("/");break}else {t.push(e);break}}else if(i===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){t.push("/");break}}else if(i===3&&e==="/.."){t.length!==0&&t.pop(),t.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),t.length!==0&&t.pop();continue}}if((r=e.indexOf("/",1))===-1){t.push(e);break}else t.push(e.slice(0,r)),e=e.slice(r);}return t.join("")}var YS={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ZS=/[@/?#:]/g,QS=/[@/?#]/g;function Sm(n,e){let t=e?QS:ZS;return t.lastIndex=0,n.replace(t,r=>YS[r])}function _m(n,e=false){if(n.indexOf("%")===-1)return n;let t="";for(let r=0;r<n.length;r++){if(n[r]==="%"&&r+2<n.length){let i=n.slice(r+1,r+3);if(Ln(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));e&&Ul(s)?t+=s:t+="%"+a,r+=2;continue}}t+=n[r];}return t}function e_(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];if(r==="%"&&t+2<n.length){let i=n.slice(t+1,t+3);if(Ln(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));s!=="."&&Ul(s)?e+=s:e+="%"+a,t+=2;continue}}if(Cm(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=Em(i)?r:Ye[i];else if(i<55296||i>57343)e+=ke(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=ke(65536+(i-55296<<10)+(a-56320)),t++):e+=ke(65533);}else e+=ke(65533);}}return e}function t_(n,e=false){let t="",r=e&&n[0]!=="/";for(let i=0;i<n.length;i++){let a=n[i];if(a==="%"&&i+2<n.length){let s=n.slice(i+1,i+3);if(Ln(s)){t+="%"+s.toUpperCase(),i+=2;continue}}if(a==="/"&&(r=false),Cm(a)&&(a!==":"||!r))t+=a;else {let s=n.charCodeAt(i);if(s<128)t+=Ye[s];else if(s<55296||s>57343)t+=ke(s);else if(s<=56319&&i+1<n.length){let o=n.charCodeAt(i+1);o>=56320&&o<=57343?(t+=ke(65536+(s-55296<<10)+(o-56320)),i++):t+=ke(65533);}else t+=ke(65533);}}return t}function Xl(n,e){let t="";for(let r=0;r<n.length;r++){let i=n[r];if(i==="%"&&r+2<n.length){let a=n.slice(r+1,r+3);if(Ln(a)){t+="%"+a.toUpperCase(),r+=2;continue}}if(e(i))t+=i;else {let a=n.charCodeAt(r);if(a<128)t+=Ye[a];else if(a<55296||a>57343)t+=ke(a);else if(a<=56319&&r+1<n.length){let s=n.charCodeAt(r+1);s>=56320&&s<=57343?(t+=ke(65536+(a-55296<<10)+(s-56320)),r++):t+=ke(65533);}else t+=ke(65533);}}return t}function wm(n){return Xl(n,BS)}function n_(n){return Xl(n,Kl)}function r_(n){return Xl(n,Kl)}function Em(n){return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||n===42||n===43||n===45||n===46||n===47||n===64||n===95}function i_(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];if(r==="%"&&t+2<n.length){let i=n.slice(t+1,t+3);if(Ln(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));Ul(s)?e+=s:e+="%"+a,t+=2;continue}}if(Kl(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=Em(i)?r:Ye[i];else if(i<55296||i>57343)e+=ke(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=ke(65536+(i-55296<<10)+(a-56320)),t++):e+=ke(65533);}else e+=ke(65533);}}return e}function s_(n){let e="";for(let t=0;t<n.length;t++){if(n[t]==="%"&&t+2<n.length){let r=n.slice(t+1,t+3);if(Ln(r)){e+="%"+r.toUpperCase(),t+=2;continue}}e+=escape(n[t]);}return e}function a_(n){let e=[];if(n.userinfo!==void 0&&(e.push(wm(n.userinfo)),e.push("@")),n.host!==void 0){let t=n.host;if(!Hl(t)){let r=zl(t);r.isIPV6!==true&&r.isIPVFuture!==true&&(t=_m(t,true),r=zl(t)),r.isIPV6===true||r.isIPVFuture===true?t=`[${r.escapedHost}]`:t=Sm(t,false);}e.push(t);}if(typeof n.port=="number"||typeof n.port=="string"){let t=String(n.port);if(!qS(t))throw new TypeError("URI port is malformed.");e.push(":"),e.push(t);}return e.length?e.join(""):void 0}Dm.exports={nonSimpleDomain:zS,recomposeAuthority:a_,reescapeHostDelimiters:Sm,normalizePercentEncoding:_m,normalizePathEncoding:e_,serializePathEncoding:t_,normalizeQueryFragmentEncoding:i_,encodeUserinfo:wm,encodeQuery:n_,encodeFragment:r_,escapePreservingEscapes:s_,removeDotSegments:XS,isIPv4:Hl,isUUID:LS,normalizeIPv6:zl,stringArrayToHexStripped:WS};});var Tm=_((lI,xm)=>{var{isUUID:o_}=Yl(),u_=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,l_=["http","https","ws","wss","urn","urn:uuid"];function c_(n){return l_.indexOf(n)!==-1}function Zl(n){return n.secure===true?true:n.secure===false?false:n.scheme?n.scheme.length===3&&(n.scheme[0]==="w"||n.scheme[0]==="W")&&(n.scheme[1]==="s"||n.scheme[1]==="S")&&(n.scheme[2]==="s"||n.scheme[2]==="S"):false}function Am(n){return n.host||(n.error=n.error||"HTTP URIs must have a host."),n}function Om(n){let e=String(n.scheme).toLowerCase()==="https";return (n.port===(e?443:80)||n.port==="")&&(n.port=void 0),n.path||(n.path="/"),n}function h_(n){return n.secure=Zl(n),n.resourceName=(n.path||"/")+(n.query?"?"+n.query:""),n.path=void 0,n.query=void 0,n}function d_(n){if((n.port===(Zl(n)?443:80)||n.port==="")&&(n.port=void 0),typeof n.secure=="boolean"&&(n.scheme=n.secure?"wss":"ws",n.secure=void 0),n.resourceName){let e=n.resourceName.indexOf("?"),t=e===-1?n.resourceName:n.resourceName.slice(0,e);n.path=t&&t!=="/"?t:void 0,n.query=e===-1?void 0:n.resourceName.slice(e+1),n.resourceName=void 0;}return n.fragment=void 0,n}function p_(n,e){if(!n.path)return n.error="URN can not be parsed",n;let t=n.path.match(u_);if(t&&t[0]===n.path){let r=e.scheme||n.scheme||"urn";n.nid=t[1].toLowerCase(),n.nss=t[2];let i=`${r}:${e.nid||n.nid}`,a=Ql(i);n.path=void 0,a&&(n=a.parse(n,e));}else n.error=n.error||"URN can not be parsed.";return n}function f_(n,e){if(n.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||n.scheme||"urn",r=n.nid.toLowerCase(),i=`${t}:${e.nid||r}`,a=Ql(i);a&&(n=a.serialize(n,e));let s=n,o=n.nss;return s.path=`${r||e.nid}:${o}`,e.skipEscape=true,s}function m_(n,e){let t=n;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!o_(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function g_(n){let e=n;return e.nss=(n.uuid||"").toLowerCase(),e}var Pm={scheme:"http",domainHost:true,parse:Am,serialize:Om},y_={scheme:"https",domainHost:Pm.domainHost,parse:Am,serialize:Om},qs={scheme:"ws",domainHost:true,parse:h_,serialize:d_},v_={scheme:"wss",domainHost:qs.domainHost,parse:qs.parse,serialize:qs.serialize},b_={scheme:"urn",parse:p_,serialize:f_,skipNormalize:true},C_={scheme:"urn:uuid",parse:m_,serialize:g_,skipNormalize:true},Bs={http:Pm,https:y_,ws:qs,wss:v_,urn:b_,"urn:uuid":C_};Object.setPrototypeOf(Bs,null);function Ql(n){return n&&(Bs[n]||Bs[n.toLowerCase()])||void 0}xm.exports={wsIsSecure:Zl,SCHEMES:Bs,isValidSchemeName:c_,getSchemeHandler:Ql};});var Mm=_((cI,Gs)=>{var{normalizeIPv6:Vm,removeDotSegments:bi,recomposeAuthority:S_,normalizePercentEncoding:ec,normalizePathEncoding:__,serializePathEncoding:Nm,normalizeQueryFragmentEncoding:Fm,encodeQuery:w_,encodeFragment:E_,reescapeHostDelimiters:D_,isIPv4:Rm,nonSimpleDomain:A_}=Yl(),{SCHEMES:jm,getSchemeHandler:tc}=Tm(),$m=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Lm="URI scheme is malformed.";function Im(n){let e=unescape(String(n));if(!$m.test(e))throw new TypeError(Lm);return e}function O_(n,e){return typeof n=="string"?n=V_(n,e):typeof n=="object"&&(n=Ms(qn(n,e),e)),n}function P_(n,e,t){let r=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:a,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:u,malformedScheme:l}=Ws(n,r),{parsed:c,malformedAuthorityOrPort:h,malformedPercentEncoding:p,malformedSchemeSpecific:f,malformedHost:g,malformedScheme:m}=Ws(e,r);if(a||h||s||p||o||f||u||g||l||m)throw new Error(i.error||c.error||"URI is malformed.");let b=qm(i,c,r,true),C=tc(t&&t.scheme||b.scheme),v=b.host,d=v!==void 0&&v!==""&&(Rm(v)||Vm(v).isIPV6);Bm(b,t||{},C,d);let S=v&&v.indexOf("%")!==-1&&!/\P{ASCII}/u.test(v);if(b.error&&!S)throw new Error(b.error);return r.skipEscape=true,qn(b,r)}function qm(n,e,t,r){let i={};return r||(n=Ms(qn(n,t),t),e=Ms(qn(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=bi(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=bi(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=bi(e.path):((n.userinfo!==void 0||n.host!==void 0||n.port!==void 0)&&!n.path?i.path="/"+e.path:n.path?i.path=n.path.slice(0,n.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=bi(i.path)),i.query=e.query):(i.path=n.path,e.query!==void 0?i.query=e.query:i.query=n.query),i.userinfo=n.userinfo,i.host=n.host,i.port=n.port),i.scheme=n.scheme),i.fragment=e.fragment,i}function x_(n,e,t){let r=km(n,t),i=km(e,t);return r!==void 0&&i!==void 0&&r===i}function qn(n,e){let t={host:n.host,scheme:n.scheme,userinfo:n.userinfo,port:n.port,path:n.path,query:n.query,nid:n.nid,nss:n.nss,uuid:n.uuid,fragment:n.fragment,reference:n.reference,resourceName:n.resourceName,secure:n.secure,error:""},r=Object.assign({},e),i=[];t.scheme&&(t.scheme=Im(t.scheme));let a=tc(r.scheme||t.scheme);a&&a.serialize&&a.serialize(t,r);let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,o=!r.skipEscape&&t.scheme===void 0&&!s;t.path!==void 0&&(r.skipEscape?t.path=ec(t.path):t.path=Nm(t.path,o)),r.reference!=="suffix"&&t.scheme&&(t.scheme=Im(t.scheme),i.push(t.scheme,":"));let u=S_(t);if(u!==void 0&&(r.reference!=="suffix"&&i.push("//"),i.push(u),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!r.absolutePath&&(!a||!a.absolutePath)&&(l=bi(l)),o&&(l=Nm(l,true)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l);}return t.query!==void 0&&i.push("?",w_(t.query)),t.fragment!==void 0&&i.push("#",E_(t.fragment)),i.join("")}var T_=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,N_=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,F_=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function I_(n,e){if(e[2]!==void 0&&n.path&&n.path[0]!=="/")return 'URI path must start with "/" when authority is present.';if(typeof n.port=="number"&&(n.port<0||n.port>65535))return "URI port is malformed."}function vi(n){if(n===void 0)return false;let e=n.indexOf("%");for(;e!==-1;){if(e+2>=n.length||!/^[\da-f]{2}$/iu.test(n.slice(e+1,e+3)))return true;e=n.indexOf("%",e+3);}return false}function nc(n){return n[0]==="["&&n[n.length-1]==="]"}function k_(n){let e=n[4];return vi(n[3])||e!==void 0&&!nc(e)&&vi(e)||vi(n[6])||vi(n[7])||vi(n[8])}function Bm(n,e,t,r){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&n.host&&!nc(n.host)&&(e.domainHost||t&&t.domainHost)&&r===false&&A_(n.host))try{n.host=new URL("http://"+n.host).hostname;}catch(i){return n.error=n.error||"Host's domain name can not be converted to ASCII: "+i,true}return false}function Ws(n,e){let t=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=false,a=false,s=false,o=false,u=false,l=false,c=false;t.reference==="suffix"&&(t.scheme?n=t.scheme+":"+n:n="//"+n);let h=n.match(N_);h!==null&&h[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",i=true);let p=n.match(F_);if(p!==null){let g=p[1],m=g.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",i=true):g.length!==m.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",i=true));}let f=n.match(T_);if(f){if(r.scheme=f[1],r.userinfo=f[3],r.host=f[4],r.port=parseInt(f[5],10),r.path=f[6]||"",r.query=f[7],r.fragment=f[8],r.scheme!==void 0){let b=unescape(r.scheme);$m.test(b)?r.scheme=b.toLowerCase():(r.error=r.error||Lm,l=true);}a=k_(f),a&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=f[5]);let g=I_(r,f);if(g!==void 0&&(r.error=r.error||g,i=true),r.host)if(Rm(r.host)===false){let C=nc(r.host),v=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,d=Vm(r.host);c=d.isIPV6||d.isIPVFuture===true,u=v&&(!C||d.error===true),r.host=c?d.host:d.host.toLowerCase(),u&&(r.error=r.error||"URI host is malformed.",i=true);}else c=true;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");let m=tc(t.scheme||r.scheme);if(u||(o=Bm(r,t,m,c)),n.indexOf("%")!==-1&&r.host!==void 0&&!u){let b=c?r.host:ec(r.host,true);c||(b=ec(b.toLowerCase())),r.host=D_(b,c);}(!m||m&&!m.skipNormalize)&&(r.path&&(r.path=__(r.path)),r.query&&(r.query=Fm(r.query)),r.fragment&&(r.fragment=Fm(r.fragment))),m&&m.parse&&(m.parse(r,t),m===jm.urn&&r.nid===void 0&&(s=true));}else r.error=r.error||"URI can not be parsed.";return {parsed:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:l}}function Ms(n,e){return Ws(n,e).parsed}function V_(n,e){return Wm(n,e).normalized}function Wm(n,e){let{parsed:t,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}=Ws(n,e);return {normalized:r||i||a||s||o?n:qn(t,e),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}}function km(n,e){if(typeof n!="string"&&typeof n!="object")return;let t;try{t=typeof n=="string"?n:qn(n,e);}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:u}=Wm(t,e);return i||a||s||o||u?void 0:r}var rc={SCHEMES:jm,normalize:O_,resolve:P_,resolveComponent:qm,equal:x_,serialize:qn,parse:Ms};Gs.exports=rc;Gs.exports.default=rc;Gs.exports.fastUri=rc;});var Jm=_(ic=>{Object.defineProperty(ic,"__esModule",{value:true});var Gm=Mm();Gm.code='require("ajv/dist/runtime/uri").default';ic.default=Gm;});var oc=_(Pe=>{Object.defineProperty(Pe,"__esModule",{value:true});Pe.CodeGen=Pe.Name=Pe.nil=Pe.stringify=Pe.str=Pe._=Pe.KeywordCxt=void 0;var R_=fr();Object.defineProperty(Pe,"KeywordCxt",{enumerable:true,get:function(){return R_.KeywordCxt}});var yr=k();Object.defineProperty(Pe,"_",{enumerable:true,get:function(){return yr._}});Object.defineProperty(Pe,"str",{enumerable:true,get:function(){return yr.str}});Object.defineProperty(Pe,"stringify",{enumerable:true,get:function(){return yr.stringify}});Object.defineProperty(Pe,"nil",{enumerable:true,get:function(){return yr.nil}});Object.defineProperty(Pe,"Name",{enumerable:true,get:function(){return yr.Name}});Object.defineProperty(Pe,"CodeGen",{enumerable:true,get:function(){return yr.CodeGen}});var j_=gi(),Xm=mr(),$_=Al(),Ci=yi(),L_=k(),Si=pi(),Js=di(),ac=q(),zm=vm(),q_=Jm(),Ym=(n,e)=>new RegExp(n,e);Ym.code="new RegExp";var B_=["removeAdditional","useDefaults","coerceTypes"],W_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),M_={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},G_={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Hm=200;function J_(n){var e,t,r,i,a,s,o,u,l,c,h,p,f,g,m,b,C,v,d,S,y,w,E,O,x;let U=n.strict,Se=(e=n.code)===null||e===void 0?void 0:e.optimize,Ht=Se===true||Se===void 0?1:Se||0,Yr=(r=(t=n.code)===null||t===void 0?void 0:t.regExp)!==null&&r!==void 0?r:Ym,rr=(i=n.uriResolver)!==null&&i!==void 0?i:q_.default;return {strictSchema:(s=(a=n.strictSchema)!==null&&a!==void 0?a:U)!==null&&s!==void 0?s:true,strictNumbers:(u=(o=n.strictNumbers)!==null&&o!==void 0?o:U)!==null&&u!==void 0?u:true,strictTypes:(c=(l=n.strictTypes)!==null&&l!==void 0?l:U)!==null&&c!==void 0?c:"log",strictTuples:(p=(h=n.strictTuples)!==null&&h!==void 0?h:U)!==null&&p!==void 0?p:"log",strictRequired:(g=(f=n.strictRequired)!==null&&f!==void 0?f:U)!==null&&g!==void 0?g:false,code:n.code?{...n.code,optimize:Ht,regExp:Yr}:{optimize:Ht,regExp:Yr},loopRequired:(m=n.loopRequired)!==null&&m!==void 0?m:Hm,loopEnum:(b=n.loopEnum)!==null&&b!==void 0?b:Hm,meta:(C=n.meta)!==null&&C!==void 0?C:true,messages:(v=n.messages)!==null&&v!==void 0?v:true,inlineRefs:(d=n.inlineRefs)!==null&&d!==void 0?d:true,schemaId:(S=n.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(y=n.addUsedSchema)!==null&&y!==void 0?y:true,validateSchema:(w=n.validateSchema)!==null&&w!==void 0?w:true,validateFormats:(E=n.validateFormats)!==null&&E!==void 0?E:true,unicodeRegExp:(O=n.unicodeRegExp)!==null&&O!==void 0?O:true,int32range:(x=n.int32range)!==null&&x!==void 0?x:true,uriResolver:rr}}var _i=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...J_(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new L_.ValueScope({scope:{},prefixes:W_,es5:t,lines:r}),this.logger=Y_(e.logger);let i=e.validateFormats;e.validateFormats=false,this.RULES=(0, $_.getRules)(),Um.call(this,M_,e,"NOT SUPPORTED"),Um.call(this,G_,e,"DEPRECATED","warn"),this._metaOpts=K_.call(this),e.formats&&H_.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&U_.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),z_.call(this),e.validateFormats=i;}_addVocabularies(){this.addKeyword("$async");}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=zm;r==="id"&&(i={...zm},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[r],false);}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);return "$async"in r||(this.errors=r.errors),i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(c,h){await a.call(this,c.$schema);let p=this._addSchema(c,h);return p.validate||s.call(this,p)}async function a(c){c&&!this.getSchema(c)&&await i.call(this,{$ref:c},true);}async function s(c){try{return this._compileSchemaEnv(c)}catch(h){if(!(h instanceof Xm.default))throw h;return o.call(this,h),await u.call(this,h.missingSchema),s.call(this,c)}}function o({missingSchema:c,missingRef:h}){if(this.refs[c])throw new Error(`AnySchema ${c} is loaded but ${h} cannot be resolved`)}async function u(c){let h=await l.call(this,c);this.refs[c]||await a.call(this,h.$schema),this.refs[c]||this.addSchema(h,c,t);}async function l(c){let h=this._loading[c];if(h)return h;try{return await(this._loading[c]=r(c))}finally{delete this._loading[c];}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let a;if(typeof e=="object"){let{schemaId:s}=this.opts;if(a=e[s],a!==void 0&&typeof a!="string")throw new Error(`schema ${s} must be string`)}return t=(0, Si.normalizeId)(t||a),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,true),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,true,r),this}validateSchema(e,t){if(typeof e=="boolean")return true;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,true;let i=this.validate(r,e);if(!i&&t){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return i}getSchema(e){let t;for(;typeof(t=Km.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new Ci.SchemaEnv({schema:{},schemaId:r});if(t=Ci.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t;}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case "undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case "string":{let t=Km.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case "object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0, Si.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string")r=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Q_.call(this,r,t),!t)return (0, ac.eachItem)(r,a=>sc.call(this,a)),this;tw.call(this,t);let i={...t,type:(0, Js.getJSONTypes)(t.type),schemaType:(0, Js.getJSONTypes)(t.schemaType)};return (0, ac.eachItem)(r,i.type.length===0?a=>sc.call(this,a,i):a=>i.type.forEach(s=>sc.call(this,a,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let i=r.rules.findIndex(a=>a.keyword===e);i>=0&&r.rules.splice(i,1);}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return !e||e.length===0?"No errors":e.map(i=>`${r}${i.instancePath} ${i.message}`).reduce((i,a)=>i+t+a)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let a=i.split("/").slice(1),s=e;for(let o of a)s=s[o];for(let o in r){let u=r[o];if(typeof u!="object")continue;let{$data:l}=u.definition,c=s[o];l&&c&&(s[o]=Zm(c));}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];(!t||t.test(r))&&(typeof i=="string"?delete e[r]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[r]));}}_addSchema(e,t,r,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];else {if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(u!==void 0)return u;r=(0, Si.normalizeId)(s||r);let l=Si.getSchemaRefs.call(this,e,r);return u=new Ci.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),a&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),i&&this.validateSchema(e,true),u}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Ci.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Ci.compileSchema.call(this,e);}finally{this.opts=t;}}};_i.ValidationError=j_.default;_i.MissingRefError=Xm.default;Pe.default=_i;function Um(n,e,t,r="error"){for(let i in n){let a=i;a in e&&this.logger[r](`${t}: option ${i}. ${n[a]}`);}}function Km(n){return n=(0, Si.normalizeId)(n),this.schemas[n]||this.refs[n]}function z_(){let n=this.opts.schemas;if(n)if(Array.isArray(n))this.addSchema(n);else for(let e in n)this.addSchema(n[e],e);}function H_(){for(let n in this.opts.formats){let e=this.opts.formats[n];e&&this.addFormat(n,e);}}function U_(n){if(Array.isArray(n)){this.addVocabulary(n);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in n){let t=n[e];t.keyword||(t.keyword=e),this.addKeyword(t);}}function K_(){let n={...this.opts};for(let e of B_)delete n[e];return n}var X_={log(){},warn(){},error(){}};function Y_(n){if(n===false)return X_;if(n===void 0)return console;if(n.log&&n.warn&&n.error)return n;throw new Error("logger must implement log, warn and error methods")}var Z_=/^[a-z_$][a-z0-9_$:-]*$/i;function Q_(n,e){let{RULES:t}=this;if((0, ac.eachItem)(n,r=>{if(t.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Z_.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function sc(n,e,t){var r;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,s=i?a.post:a.rules.find(({type:u})=>u===t);if(s||(s={type:t,rules:[]},a.rules.push(s)),a.keywords[n]=true,!e)return;let o={keyword:n,definition:{...e,type:(0, Js.getJSONTypes)(e.type),schemaType:(0, Js.getJSONTypes)(e.schemaType)}};e.before?ew.call(this,s,o,e.before):s.rules.push(o),a.all[n]=o,(r=e.implements)===null||r===void 0||r.forEach(u=>this.addKeyword(u));}function ew(n,e,t){let r=n.rules.findIndex(i=>i.keyword===t);r>=0?n.rules.splice(r,0,e):(n.rules.push(e),this.logger.warn(`rule ${t} is not defined`));}function tw(n){let{metaSchema:e}=n;e!==void 0&&(n.$data&&this.opts.$data&&(e=Zm(e)),n.validateSchema=this.compile(e,true));}var nw={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Zm(n){return {anyOf:[n,nw]}}});var Qm=_(uc=>{Object.defineProperty(uc,"__esModule",{value:true});var rw={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};uc.default=rw;});var Us=_(Bn=>{Object.defineProperty(Bn,"__esModule",{value:true});Bn.callRef=Bn.getValidate=void 0;var iw=mr(),eg=ht(),Ze=k(),vr=ct(),tg=yi(),zs=q(),sw={keyword:"$ref",schemaType:"string",code(n){let{gen:e,schema:t,it:r}=n,{baseId:i,schemaEnv:a,validateName:s,opts:o,self:u}=r,{root:l}=a;if((t==="#"||t==="#/")&&i===l.baseId)return h();let c=tg.resolveRef.call(u,l,i,t);if(c===void 0)throw new iw.default(r.opts.uriResolver,i,t);if(c instanceof tg.SchemaEnv)return p(c);return f(c);function h(){if(a===l)return Hs(n,s,a,a.$async);let g=e.scopeValue("root",{ref:l});return Hs(n,(0, Ze._)`${g}.validate`,l,l.$async)}function p(g){let m=ng(n,g);Hs(n,m,g,g.$async);}function f(g){let m=e.scopeValue("schema",o.code.source===true?{ref:g,code:(0, Ze.stringify)(g)}:{ref:g}),b=e.name("valid"),C=n.subschema({schema:g,dataTypes:[],schemaPath:Ze.nil,topSchemaRef:m,errSchemaPath:t},b);n.mergeEvaluated(C),n.ok(b);}}};function ng(n,e){let{gen:t}=n;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0, Ze._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Bn.getValidate=ng;function Hs(n,e,t,r){let{gen:i,it:a}=n,{allErrors:s,schemaEnv:o,opts:u}=a,l=u.passContext?vr.default.this:Ze.nil;r?c():h();function c(){if(!o.$async)throw new Error("async schema referenced by sync schema");let g=i.let("valid");i.try(()=>{i.code((0, Ze._)`await ${(0, eg.callValidateCode)(n,e,l)}`),f(e),s||i.assign(g,true);},m=>{i.if((0, Ze._)`!(${m} instanceof ${a.ValidationError})`,()=>i.throw(m)),p(m),s||i.assign(g,false);}),n.ok(g);}function h(){n.result((0, eg.callValidateCode)(n,e,l),()=>f(e),()=>p(e));}function p(g){let m=(0, Ze._)`${g}.errors`;i.assign(vr.default.vErrors,(0, Ze._)`${vr.default.vErrors} === null ? ${m} : ${vr.default.vErrors}.concat(${m})`),i.assign(vr.default.errors,(0, Ze._)`${vr.default.vErrors}.length`);}function f(g){var m;if(!a.opts.unevaluated)return;let b=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(a.props!==true)if(b&&!b.dynamicProps)b.props!==void 0&&(a.props=zs.mergeEvaluated.props(i,b.props,a.props));else {let C=i.var("props",(0, Ze._)`${g}.evaluated.props`);a.props=zs.mergeEvaluated.props(i,C,a.props,Ze.Name);}if(a.items!==true)if(b&&!b.dynamicItems)b.items!==void 0&&(a.items=zs.mergeEvaluated.items(i,b.items,a.items));else {let C=i.var("items",(0, Ze._)`${g}.evaluated.items`);a.items=zs.mergeEvaluated.items(i,C,a.items,Ze.Name);}}}Bn.callRef=Hs;Bn.default=sw;});var cc=_(lc=>{Object.defineProperty(lc,"__esModule",{value:true});var aw=Qm(),ow=Us(),uw=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",aw.default,ow.default];lc.default=uw;});var rg=_(hc=>{Object.defineProperty(hc,"__esModule",{value:true});var Ks=k(),mn=Ks.operators,Xs={maximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},minimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},exclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},exclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},lw={message:({keyword:n,schemaCode:e})=>(0, Ks.str)`must be ${Xs[n].okStr} ${e}`,params:({keyword:n,schemaCode:e})=>(0, Ks._)`{comparison: ${Xs[n].okStr}, limit: ${e}}`},cw={keyword:Object.keys(Xs),type:"number",schemaType:"number",$data:true,error:lw,code(n){let{keyword:e,data:t,schemaCode:r}=n;n.fail$data((0, Ks._)`${t} ${Xs[e].fail} ${r} || isNaN(${t})`);}};hc.default=cw;});var ig=_(dc=>{Object.defineProperty(dc,"__esModule",{value:true});var wi=k(),hw={message:({schemaCode:n})=>(0, wi.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0, wi._)`{multipleOf: ${n}}`},dw={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:hw,code(n){let{gen:e,data:t,schemaCode:r,it:i}=n,a=i.opts.multipleOfPrecision,s=e.let("res"),o=a?(0, wi._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0, wi._)`${s} !== parseInt(${s})`;n.fail$data((0, wi._)`(${r} === 0 || (${s} = ${t}/${r}, ${o}))`);}};dc.default=dw;});var ag=_(pc=>{Object.defineProperty(pc,"__esModule",{value:true});function sg(n){let e=n.length,t=0,r=0,i;for(;r<e;)t++,i=n.charCodeAt(r++),i>=55296&&i<=56319&&r<e&&(i=n.charCodeAt(r),(i&64512)===56320&&r++);return t}pc.default=sg;sg.code='require("ajv/dist/runtime/ucs2length").default';});var og=_(fc=>{Object.defineProperty(fc,"__esModule",{value:true});var Wn=k(),pw=q(),fw=ag(),mw={message({keyword:n,schemaCode:e}){let t=n==="maxLength"?"more":"fewer";return (0, Wn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:n})=>(0, Wn._)`{limit: ${n}}`},gw={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:mw,code(n){let{keyword:e,data:t,schemaCode:r,it:i}=n,a=e==="maxLength"?Wn.operators.GT:Wn.operators.LT,s=i.opts.unicode===false?(0, Wn._)`${t}.length`:(0, Wn._)`${(0, pw.useFunc)(n.gen,fw.default)}(${t})`;n.fail$data((0, Wn._)`${s} ${a} ${r}`);}};fc.default=gw;});var ug=_(mc=>{Object.defineProperty(mc,"__esModule",{value:true});var yw=ht(),vw=q(),br=k(),bw={message:({schemaCode:n})=>(0, br.str)`must match pattern "${n}"`,params:({schemaCode:n})=>(0, br._)`{pattern: ${n}}`},Cw={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:bw,code(n){let{gen:e,data:t,$data:r,schema:i,schemaCode:a,it:s}=n,o=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:u}=s.opts.code,l=u.code==="new RegExp"?(0, br._)`new RegExp`:(0, vw.useFunc)(e,u),c=e.let("valid");e.try(()=>e.assign(c,(0, br._)`${l}(${a}, ${o}).test(${t})`),()=>e.assign(c,false)),n.fail$data((0, br._)`!${c}`);}else {let u=(0, yw.usePattern)(n,i);n.fail$data((0, br._)`!${u}.test(${t})`);}}};mc.default=Cw;});var lg=_(gc=>{Object.defineProperty(gc,"__esModule",{value:true});var Ei=k(),Sw={message({keyword:n,schemaCode:e}){let t=n==="maxProperties"?"more":"fewer";return (0, Ei.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:n})=>(0, Ei._)`{limit: ${n}}`},_w={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:Sw,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxProperties"?Ei.operators.GT:Ei.operators.LT;n.fail$data((0, Ei._)`Object.keys(${t}).length ${i} ${r}`);}};gc.default=_w;});var cg=_(yc=>{Object.defineProperty(yc,"__esModule",{value:true});var Di=ht(),Ai=k(),ww=q(),Ew={message:({params:{missingProperty:n}})=>(0, Ai.str)`must have required property '${n}'`,params:({params:{missingProperty:n}})=>(0, Ai._)`{missingProperty: ${n}}`},Dw={keyword:"required",type:"object",schemaType:"array",$data:true,error:Ew,code(n){let{gen:e,schema:t,schemaCode:r,data:i,$data:a,it:s}=n,{opts:o}=s;if(!a&&t.length===0)return;let u=t.length>=o.loopRequired;if(s.allErrors?l():c(),o.strictRequired){let f=n.parentSchema.properties,{definedProperties:g}=n.it;for(let m of t)if(f?.[m]===void 0&&!g.has(m)){let b=s.schemaEnv.baseId+s.errSchemaPath,C=`required property "${m}" is not defined at "${b}" (strictRequired)`;(0, ww.checkStrictMode)(s,C,s.opts.strictRequired);}}function l(){if(u||a)n.block$data(Ai.nil,h);else for(let f of t)(0, Di.checkReportMissingProp)(n,f);}function c(){let f=e.let("missing");if(u||a){let g=e.let("valid",true);n.block$data(g,()=>p(f,g)),n.ok(g);}else e.if((0, Di.checkMissingProp)(n,t,f)),(0, Di.reportMissingProp)(n,f),e.else();}function h(){e.forOf("prop",r,f=>{n.setParams({missingProperty:f}),e.if((0, Di.noPropertyInData)(e,i,f,o.ownProperties),()=>n.error());});}function p(f,g){n.setParams({missingProperty:f}),e.forOf(f,r,()=>{e.assign(g,(0, Di.propertyInData)(e,i,f,o.ownProperties)),e.if((0, Ai.not)(g),()=>{n.error(),e.break();});},Ai.nil);}}};yc.default=Dw;});var hg=_(vc=>{Object.defineProperty(vc,"__esModule",{value:true});var Oi=k(),Aw={message({keyword:n,schemaCode:e}){let t=n==="maxItems"?"more":"fewer";return (0, Oi.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:n})=>(0, Oi._)`{limit: ${n}}`},Ow={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:Aw,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxItems"?Oi.operators.GT:Oi.operators.LT;n.fail$data((0, Oi._)`${t}.length ${i} ${r}`);}};vc.default=Ow;});var Ys=_(bc=>{Object.defineProperty(bc,"__esModule",{value:true});var dg=kl();dg.code='require("ajv/dist/runtime/equal").default';bc.default=dg;});var pg=_(Sc=>{Object.defineProperty(Sc,"__esModule",{value:true});var Cc=di(),xe=k(),Pw=q(),xw=Ys(),Tw={message:({params:{i:n,j:e}})=>(0, xe.str)`must NOT have duplicate items (items ## ${e} and ${n} are identical)`,params:({params:{i:n,j:e}})=>(0, xe._)`{i: ${n}, j: ${e}}`},Nw={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:Tw,code(n){let{gen:e,data:t,$data:r,schema:i,parentSchema:a,schemaCode:s,it:o}=n;if(!r&&!i)return;let u=e.let("valid"),l=a.items?(0, Cc.getSchemaTypes)(a.items):[];n.block$data(u,c,(0, xe._)`${s} === false`),n.ok(u);function c(){let g=e.let("i",(0, xe._)`${t}.length`),m=e.let("j");n.setParams({i:g,j:m}),e.assign(u,true),e.if((0, xe._)`${g} > 1`,()=>(h()?p:f)(g,m));}function h(){return l.length>0&&!l.some(g=>g==="object"||g==="array")}function p(g,m){let b=e.name("item"),C=(0, Cc.checkDataTypes)(l,b,o.opts.strictNumbers,Cc.DataType.Wrong),v=e.const("indices",(0, xe._)`{}`);e.for((0, xe._)`;${g}--;`,()=>{e.let(b,(0, xe._)`${t}[${g}]`),e.if(C,(0, xe._)`continue`),l.length>1&&e.if((0, xe._)`typeof ${b} == "string"`,(0, xe._)`${b} += "_"`),e.if((0, xe._)`typeof ${v}[${b}] == "number"`,()=>{e.assign(m,(0, xe._)`${v}[${b}]`),n.error(),e.assign(u,false).break();}).code((0, xe._)`${v}[${b}] = ${g}`);});}function f(g,m){let b=(0, Pw.useFunc)(e,xw.default),C=e.name("outer");e.label(C).for((0, xe._)`;${g}--;`,()=>e.for((0, xe._)`${m} = ${g}; ${m}--;`,()=>e.if((0, xe._)`${b}(${t}[${g}], ${t}[${m}])`,()=>{n.error(),e.assign(u,false).break(C);})));}}};Sc.default=Nw;});var fg=_(wc=>{Object.defineProperty(wc,"__esModule",{value:true});var _c=k(),Fw=q(),Iw=Ys(),kw={message:"must be equal to constant",params:({schemaCode:n})=>(0, _c._)`{allowedValue: ${n}}`},Vw={keyword:"const",$data:true,error:kw,code(n){let{gen:e,data:t,$data:r,schemaCode:i,schema:a}=n;r||a&&typeof a=="object"?n.fail$data((0, _c._)`!${(0, Fw.useFunc)(e,Iw.default)}(${t}, ${i})`):n.fail((0, _c._)`${a} !== ${t}`);}};wc.default=Vw;});var mg=_(Ec=>{Object.defineProperty(Ec,"__esModule",{value:true});var Pi=k(),Rw=q(),jw=Ys(),$w={message:"must be equal to one of the allowed values",params:({schemaCode:n})=>(0, Pi._)`{allowedValues: ${n}}`},Lw={keyword:"enum",schemaType:"array",$data:true,error:$w,code(n){let{gen:e,data:t,$data:r,schema:i,schemaCode:a,it:s}=n;if(!r&&i.length===0)throw new Error("enum must have non-empty array");let o=i.length>=s.opts.loopEnum,u,l=()=>u??(u=(0, Rw.useFunc)(e,jw.default)),c;if(o||r)c=e.let("valid"),n.block$data(c,h);else {if(!Array.isArray(i))throw new Error("ajv implementation error");let f=e.const("vSchema",a);c=(0, Pi.or)(...i.map((g,m)=>p(f,m)));}n.pass(c);function h(){e.assign(c,false),e.forOf("v",a,f=>e.if((0, Pi._)`${l()}(${t}, ${f})`,()=>e.assign(c,true).break()));}function p(f,g){let m=i[g];return typeof m=="object"&&m!==null?(0, Pi._)`${l()}(${t}, ${f}[${g}])`:(0, Pi._)`${t} === ${m}`}}};Ec.default=Lw;});var Ac=_(Dc=>{Object.defineProperty(Dc,"__esModule",{value:true});var qw=rg(),Bw=ig(),Ww=og(),Mw=ug(),Gw=lg(),Jw=cg(),zw=hg(),Hw=pg(),Uw=fg(),Kw=mg(),Xw=[qw.default,Bw.default,Ww.default,Mw.default,Gw.default,Jw.default,zw.default,Hw.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Uw.default,Kw.default];Dc.default=Xw;});var Pc=_(xi=>{Object.defineProperty(xi,"__esModule",{value:true});xi.validateAdditionalItems=void 0;var Mn=k(),Oc=q(),Yw={message:({params:{len:n}})=>(0, Mn.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, Mn._)`{limit: ${n}}`},Zw={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Yw,code(n){let{parentSchema:e,it:t}=n,{items:r}=e;if(!Array.isArray(r)){(0, Oc.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}gg(n,r);}};function gg(n,e){let{gen:t,schema:r,data:i,keyword:a,it:s}=n;s.items=true;let o=t.const("len",(0, Mn._)`${i}.length`);if(r===false)n.setParams({len:e.length}),n.pass((0, Mn._)`${o} <= ${e.length}`);else if(typeof r=="object"&&!(0, Oc.alwaysValidSchema)(s,r)){let l=t.var("valid",(0, Mn._)`${o} <= ${e.length}`);t.if((0, Mn.not)(l),()=>u(l)),n.ok(l);}function u(l){t.forRange("i",e.length,o,c=>{n.subschema({keyword:a,dataProp:c,dataPropType:Oc.Type.Num},l),s.allErrors||t.if((0, Mn.not)(l),()=>t.break());});}}xi.validateAdditionalItems=gg;xi.default=Zw;});var xc=_(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.validateTuple=void 0;var yg=k(),Zs=q(),Qw=ht(),eE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(n){let{schema:e,it:t}=n;if(Array.isArray(e))return vg(n,"additionalItems",e);t.items=true,!(0, Zs.alwaysValidSchema)(t,e)&&n.ok((0, Qw.validateArray)(n));}};function vg(n,e,t=n.schema){let{gen:r,parentSchema:i,data:a,keyword:s,it:o}=n;c(i),o.opts.unevaluated&&t.length&&o.items!==true&&(o.items=Zs.mergeEvaluated.items(r,t.length,o.items));let u=r.name("valid"),l=r.const("len",(0, yg._)`${a}.length`);t.forEach((h,p)=>{(0, Zs.alwaysValidSchema)(o,h)||(r.if((0, yg._)`${l} > ${p}`,()=>n.subschema({keyword:s,schemaProp:p,dataProp:p},u)),n.ok(u));});function c(h){let{opts:p,errSchemaPath:f}=o,g=t.length,m=g===h.minItems&&(g===h.maxItems||h[e]===false);if(p.strictTuples&&!m){let b=`"${s}" is ${g}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0, Zs.checkStrictMode)(o,b,p.strictTuples);}}}Ti.validateTuple=vg;Ti.default=eE;});var bg=_(Tc=>{Object.defineProperty(Tc,"__esModule",{value:true});var tE=xc(),nE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0, tE.validateTuple)(n,"items")};Tc.default=nE;});var Sg=_(Nc=>{Object.defineProperty(Nc,"__esModule",{value:true});var Cg=k(),rE=q(),iE=ht(),sE=Pc(),aE={message:({params:{len:n}})=>(0, Cg.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, Cg._)`{limit: ${n}}`},oE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:aE,code(n){let{schema:e,parentSchema:t,it:r}=n,{prefixItems:i}=t;r.items=true,!(0, rE.alwaysValidSchema)(r,e)&&(i?(0, sE.validateAdditionalItems)(n,i):n.ok((0, iE.validateArray)(n)));}};Nc.default=oE;});var _g=_(Fc=>{Object.defineProperty(Fc,"__esModule",{value:true});var pt=k(),Qs=q(),uE={message:({params:{min:n,max:e}})=>e===void 0?(0, pt.str)`must contain at least ${n} valid item(s)`:(0, pt.str)`must contain at least ${n} and no more than ${e} valid item(s)`,params:({params:{min:n,max:e}})=>e===void 0?(0, pt._)`{minContains: ${n}}`:(0, pt._)`{minContains: ${n}, maxContains: ${e}}`},lE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:uE,code(n){let{gen:e,schema:t,parentSchema:r,data:i,it:a}=n,s,o,{minContains:u,maxContains:l}=r;a.opts.next?(s=u===void 0?1:u,o=l):s=1;let c=e.const("len",(0, pt._)`${i}.length`);if(n.setParams({min:s,max:o}),o===void 0&&s===0){(0, Qs.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(o!==void 0&&s>o){(0, Qs.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),n.fail();return}if((0, Qs.alwaysValidSchema)(a,t)){let m=(0, pt._)`${c} >= ${s}`;o!==void 0&&(m=(0, pt._)`${m} && ${c} <= ${o}`),n.pass(m);return}a.items=true;let h=e.name("valid");o===void 0&&s===1?f(h,()=>e.if(h,()=>e.break())):s===0?(e.let(h,true),o!==void 0&&e.if((0, pt._)`${i}.length > 0`,p)):(e.let(h,false),p()),n.result(h,()=>n.reset());function p(){let m=e.name("_valid"),b=e.let("count",0);f(m,()=>e.if(m,()=>g(b)));}function f(m,b){e.forRange("i",0,c,C=>{n.subschema({keyword:"contains",dataProp:C,dataPropType:Qs.Type.Num,compositeRule:true},m),b();});}function g(m){e.code((0, pt._)`${m}++`),o===void 0?e.if((0, pt._)`${m} >= ${s}`,()=>e.assign(h,true).break()):(e.if((0, pt._)`${m} > ${o}`,()=>e.assign(h,false).break()),s===1?e.assign(h,true):e.if((0, pt._)`${m} >= ${s}`,()=>e.assign(h,true)));}}};Fc.default=lE;});var ea=_(Vt=>{Object.defineProperty(Vt,"__esModule",{value:true});Vt.validateSchemaDeps=Vt.validatePropertyDeps=Vt.error=void 0;var Ic=k(),cE=q(),Ni=ht();Vt.error={message:({params:{property:n,depsCount:e,deps:t}})=>{let r=e===1?"property":"properties";return (0, Ic.str)`must have ${r} ${t} when property ${n} is present`},params:({params:{property:n,depsCount:e,deps:t,missingProperty:r}})=>(0, Ic._)`{property: ${n},
6
6
  missingProperty: ${r},
7
7
  depsCount: ${e},
8
- deps: ${t}}`};var lw={keyword:"dependencies",type:"object",schemaType:"object",error:It.error,code(n){let[e,t]=cw(n);_g(n,e),Sg(n,t);}};function cw({schema:n}){let e={},t={};for(let r in n){if(r==="__proto__")continue;let i=Array.isArray(n[r])?e:t;i[r]=n[r];}return [e,t]}function _g(n,e=n.schema){let{gen:t,data:r,it:i}=n;if(Object.keys(e).length===0)return;let a=t.let("missing");for(let s in e){let o=e[s];if(o.length===0)continue;let u=(0, xi.propertyInData)(t,r,s,i.opts.ownProperties);n.setParams({property:s,depsCount:o.length,deps:o.join(", ")}),i.allErrors?t.if(u,()=>{for(let l of o)(0, xi.checkReportMissingProp)(n,l);}):(t.if((0, Nc._)`${u} && (${(0, xi.checkMissingProp)(n,o,a)})`),(0, xi.reportMissingProp)(n,a),t.else());}}It.validatePropertyDeps=_g;function Sg(n,e=n.schema){let{gen:t,data:r,keyword:i,it:a}=n,s=t.name("valid");for(let o in e)(0, uw.alwaysValidSchema)(a,e[o])||(t.if((0, xi.propertyInData)(t,r,o,a.opts.ownProperties),()=>{let u=n.subschema({keyword:i,schemaProp:o},s);n.mergeValidEvaluated(u,s);},()=>t.var(s,true)),n.ok(s));}It.validateSchemaDeps=Sg;It.default=lw;});var wg=S(Fc=>{Object.defineProperty(Fc,"__esModule",{value:true});var Eg=k(),hw=q(),dw={message:"property name must be valid",params:({params:n})=>(0, Eg._)`{propertyName: ${n.propertyName}}`},fw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:dw,code(n){let{gen:e,schema:t,data:r,it:i}=n;if((0, hw.alwaysValidSchema)(i,t))return;let a=e.name("valid");e.forIn("key",r,s=>{n.setParams({propertyName:s}),n.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:true},a),e.if((0, Eg.not)(a),()=>{n.error(true),i.allErrors||e.break();});}),n.ok(a);}};Fc.default=fw;});var kc=S(Ic=>{Object.defineProperty(Ic,"__esModule",{value:true});var Qs=lt(),Dt=k(),pw=ut(),ea=q(),mw={message:"must NOT have additional properties",params:({params:n})=>(0, Dt._)`{additionalProperty: ${n.additionalProperty}}`},gw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:mw,code(n){let{gen:e,schema:t,parentSchema:r,data:i,errsCount:a,it:s}=n;if(!a)throw new Error("ajv implementation error");let{allErrors:o,opts:u}=s;if(s.props=true,u.removeAdditional!=="all"&&(0, ea.alwaysValidSchema)(s,t))return;let l=(0, Qs.allSchemaProperties)(r.properties),c=(0, Qs.allSchemaProperties)(r.patternProperties);h(),n.ok((0, Dt._)`${a} === ${pw.default.errors}`);function h(){e.forIn("key",i,C=>{!l.length&&!c.length?g(C):e.if(f(C),()=>g(C));});}function f(C){let b;if(l.length>8){let v=(0, ea.schemaRefOrVal)(s,r.properties,"properties");b=(0, Qs.isOwnProperty)(e,v,C);}else l.length?b=(0, Dt.or)(...l.map(v=>(0, Dt._)`${C} === ${v}`)):b=Dt.nil;return c.length&&(b=(0, Dt.or)(b,...c.map(v=>(0, Dt._)`${(0, Qs.usePattern)(n,v)}.test(${C})`))),(0, Dt.not)(b)}function p(C){e.code((0, Dt._)`delete ${i}[${C}]`);}function g(C){if(u.removeAdditional==="all"||u.removeAdditional&&t===false){p(C);return}if(t===false){n.setParams({additionalProperty:C}),n.error(),o||e.break();return}if(typeof t=="object"&&!(0, ea.alwaysValidSchema)(s,t)){let b=e.name("valid");u.removeAdditional==="failing"?(m(C,b,false),e.if((0, Dt.not)(b),()=>{n.reset(),p(C);})):(m(C,b),o||e.if((0, Dt.not)(b),()=>e.break()));}}function m(C,b,v){let d={keyword:"additionalProperties",dataProp:C,dataPropType:ea.Type.Str};v===false&&Object.assign(d,{compositeRule:true,createErrors:false,allErrors:false}),n.subschema(d,b);}}};Ic.default=gw;});var Pg=S(Rc=>{Object.defineProperty(Rc,"__esModule",{value:true});var yw=dr(),Dg=lt(),Vc=q(),Ag=kc(),vw={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:e,schema:t,parentSchema:r,data:i,it:a}=n;a.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Ag.default.code(new yw.KeywordCxt(a,Ag.default,"additionalProperties"));let s=(0, Dg.allSchemaProperties)(t);for(let h of s)a.definedProperties.add(h);a.opts.unevaluated&&s.length&&a.props!==true&&(a.props=Vc.mergeEvaluated.props(e,(0, Vc.toHash)(s),a.props));let o=s.filter(h=>!(0, Vc.alwaysValidSchema)(a,t[h]));if(o.length===0)return;let u=e.name("valid");for(let h of o)l(h)?c(h):(e.if((0, Dg.propertyInData)(e,i,h,a.opts.ownProperties)),c(h),a.allErrors||e.else().var(u,true),e.endIf()),n.it.definedProperties.add(h),n.ok(u);function l(h){return a.opts.useDefaults&&!a.compositeRule&&t[h].default!==void 0}function c(h){n.subschema({keyword:"properties",schemaProp:h,dataProp:h},u);}}};Rc.default=vw;});var Ng=S($c=>{Object.defineProperty($c,"__esModule",{value:true});var Og=lt(),ta=k(),xg=q(),Tg=q(),Cw={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:e,schema:t,data:r,parentSchema:i,it:a}=n,{opts:s}=a,o=(0, Og.allSchemaProperties)(t),u=o.filter(m=>(0, xg.alwaysValidSchema)(a,t[m]));if(o.length===0||u.length===o.length&&(!a.opts.unevaluated||a.props===true))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,c=e.name("valid");a.props!==true&&!(a.props instanceof ta.Name)&&(a.props=(0, Tg.evaluatedPropsToName)(e,a.props));let{props:h}=a;f();function f(){for(let m of o)l&&p(m),a.allErrors?g(m):(e.var(c,true),g(m),e.if(c));}function p(m){for(let C in l)new RegExp(m).test(C)&&(0, xg.checkStrictMode)(a,`property ${C} matches pattern ${m} (use allowMatchingProperties)`);}function g(m){e.forIn("key",r,C=>{e.if((0, ta._)`${(0, Og.usePattern)(n,m)}.test(${C})`,()=>{let b=u.includes(m);b||n.subschema({keyword:"patternProperties",schemaProp:m,dataProp:C,dataPropType:Tg.Type.Str},c),a.opts.unevaluated&&h!==true?e.assign((0, ta._)`${h}[${C}]`,true):!b&&!a.allErrors&&e.if((0, ta.not)(c),()=>e.break());});});}}};$c.default=Cw;});var Fg=S(jc=>{Object.defineProperty(jc,"__esModule",{value:true});var bw=q(),_w={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(n){let{gen:e,schema:t,it:r}=n;if((0, bw.alwaysValidSchema)(r,t)){n.fail();return}let i=e.name("valid");n.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},i),n.failResult(i,()=>n.reset(),()=>n.error());},error:{message:"must NOT be valid"}};jc.default=_w;});var Ig=S(Lc=>{Object.defineProperty(Lc,"__esModule",{value:true});var Sw=lt(),Ew={keyword:"anyOf",schemaType:"array",trackErrors:true,code:Sw.validateUnion,error:{message:"must match a schema in anyOf"}};Lc.default=Ew;});var kg=S(qc=>{Object.defineProperty(qc,"__esModule",{value:true});var na=k(),ww=q(),Dw={message:"must match exactly one schema in oneOf",params:({params:n})=>(0, na._)`{passingSchemas: ${n.passing}}`},Aw={keyword:"oneOf",schemaType:"array",trackErrors:true,error:Dw,code(n){let{gen:e,schema:t,parentSchema:r,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&r.discriminator)return;let a=t,s=e.let("valid",false),o=e.let("passing",null),u=e.name("_valid");n.setParams({passing:o}),e.block(l),n.result(s,()=>n.reset(),()=>n.error(true));function l(){a.forEach((c,h)=>{let f;(0, ww.alwaysValidSchema)(i,c)?e.var(u,true):f=n.subschema({keyword:"oneOf",schemaProp:h,compositeRule:true},u),h>0&&e.if((0, na._)`${u} && ${s}`).assign(s,false).assign(o,(0, na._)`[${o}, ${h}]`).else(),e.if(u,()=>{e.assign(s,true),e.assign(o,h),f&&n.mergeEvaluated(f,na.Name);});});}}};qc.default=Aw;});var Vg=S(Bc=>{Object.defineProperty(Bc,"__esModule",{value:true});var Pw=q(),Ow={keyword:"allOf",schemaType:"array",code(n){let{gen:e,schema:t,it:r}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((a,s)=>{if((0, Pw.alwaysValidSchema)(r,a))return;let o=n.subschema({keyword:"allOf",schemaProp:s},i);n.ok(i),n.mergeEvaluated(o);});}};Bc.default=Ow;});var jg=S(Wc=>{Object.defineProperty(Wc,"__esModule",{value:true});var ra=k(),$g=q(),xw={message:({params:n})=>(0, ra.str)`must match "${n.ifClause}" schema`,params:({params:n})=>(0, ra._)`{failingKeyword: ${n.ifClause}}`},Tw={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:xw,code(n){let{gen:e,parentSchema:t,it:r}=n;t.then===void 0&&t.else===void 0&&(0, $g.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let i=Rg(r,"then"),a=Rg(r,"else");if(!i&&!a)return;let s=e.let("valid",true),o=e.name("_valid");if(u(),n.reset(),i&&a){let c=e.let("ifClause");n.setParams({ifClause:c}),e.if(o,l("then",c),l("else",c));}else i?e.if(o,l("then")):e.if((0, ra.not)(o),l("else"));n.pass(s,()=>n.error(true));function u(){let c=n.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},o);n.mergeEvaluated(c);}function l(c,h){return ()=>{let f=n.subschema({keyword:c},o);e.assign(s,o),n.mergeValidEvaluated(f,s),h?e.assign(h,(0, ra._)`${c}`):n.setParams({ifClause:c});}}}};function Rg(n,e){let t=n.schema[e];return t!==void 0&&!(0, $g.alwaysValidSchema)(n,t)}Wc.default=Tw;});var Lg=S(Mc=>{Object.defineProperty(Mc,"__esModule",{value:true});var Nw=q(),Fw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:e,it:t}){e.if===void 0&&(0, Nw.checkStrictMode)(t,`"${n}" without "if" is ignored`);}};Mc.default=Fw;});var Jc=S(Gc=>{Object.defineProperty(Gc,"__esModule",{value:true});var Iw=Ac(),kw=yg(),Vw=Pc(),Rw=Cg(),$w=bg(),jw=Zs(),Lw=wg(),qw=kc(),Bw=Pg(),Ww=Ng(),Mw=Fg(),Gw=Ig(),Jw=kg(),zw=Vg(),Hw=jg(),Uw=Lg();function Kw(n=false){let e=[Mw.default,Gw.default,Jw.default,zw.default,Hw.default,Uw.default,Lw.default,qw.default,jw.default,Bw.default,Ww.default];return n?e.push(kw.default,Rw.default):e.push(Iw.default,Vw.default),e.push($w.default),e}Gc.default=Kw;});var qg=S(zc=>{Object.defineProperty(zc,"__esModule",{value:true});var ge=k(),Xw={message:({schemaCode:n})=>(0, ge.str)`must match format "${n}"`,params:({schemaCode:n})=>(0, ge._)`{format: ${n}}`},Yw={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:Xw,code(n,e){let{gen:t,data:r,$data:i,schema:a,schemaCode:s,it:o}=n,{opts:u,errSchemaPath:l,schemaEnv:c,self:h}=o;if(!u.validateFormats)return;i?f():p();function f(){let g=t.scopeValue("formats",{ref:h.formats,code:u.code.formats}),m=t.const("fDef",(0, ge._)`${g}[${s}]`),C=t.let("fType"),b=t.let("format");t.if((0, ge._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(C,(0, ge._)`${m}.type || "string"`).assign(b,(0, ge._)`${m}.validate`),()=>t.assign(C,(0, ge._)`"string"`).assign(b,m)),n.fail$data((0, ge.or)(v(),d()));function v(){return u.strictSchema===false?ge.nil:(0, ge._)`${s} && !${b}`}function d(){let _=c.$async?(0, ge._)`(${m}.async ? await ${b}(${r}) : ${b}(${r}))`:(0, ge._)`${b}(${r})`,y=(0, ge._)`(typeof ${b} == "function" ? ${_} : ${b}.test(${r}))`;return (0, ge._)`${b} && ${b} !== true && ${C} === ${e} && !${y}`}}function p(){let g=h.formats[a];if(!g){v();return}if(g===true)return;let[m,C,b]=d(g);m===e&&n.pass(_());function v(){if(u.strictSchema===false){h.logger.warn(y());return}throw new Error(y());function y(){return `unknown format "${a}" ignored in schema at path "${l}"`}}function d(y){let E=y instanceof RegExp?(0, ge.regexpCode)(y):u.code.formats?(0, ge._)`${u.code.formats}${(0, ge.getProperty)(a)}`:void 0,w=t.scopeValue("formats",{key:a,ref:y,code:E});return typeof y=="object"&&!(y instanceof RegExp)?[y.type||"string",y.validate,(0, ge._)`${w}.validate`]:["string",y,w]}function _(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!c.$async)throw new Error("async format in sync schema");return (0, ge._)`await ${b}(${r})`}return typeof C=="function"?(0, ge._)`${b}(${r})`:(0, ge._)`${b}.test(${r})`}}}};zc.default=Yw;});var Uc=S(Hc=>{Object.defineProperty(Hc,"__esModule",{value:true});var Zw=qg(),Qw=[Zw.default];Hc.default=Qw;});var Kc=S(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.contentVocabulary=vr.metadataVocabulary=void 0;vr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];vr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];});var Wg=S(Xc=>{Object.defineProperty(Xc,"__esModule",{value:true});var eD=uc(),tD=wc(),nD=Jc(),rD=Uc(),Bg=Kc(),iD=[eD.default,tD.default,(0, nD.default)(),rD.default,Bg.metadataVocabulary,Bg.contentVocabulary];Xc.default=iD;});var Gg=S(ia=>{Object.defineProperty(ia,"__esModule",{value:true});ia.DiscrError=void 0;var Mg;(function(n){n.Tag="tag",n.Mapping="mapping";})(Mg||(ia.DiscrError=Mg={}));});var Qc=S(Zc=>{Object.defineProperty(Zc,"__esModule",{value:true});var Cr=k(),Yc=Gg(),Jg=mi(),sD=fr(),aD=q(),oD={message:({params:{discrError:n,tagName:e}})=>n===Yc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:n,tag:e,tagName:t}})=>(0, Cr._)`{error: ${n}, tag: ${t}, tagValue: ${e}}`},uD={keyword:"discriminator",type:"object",schemaType:"object",error:oD,code(n){let{gen:e,data:t,schema:r,parentSchema:i,it:a}=n,{oneOf:s}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let o=r.propertyName;if(typeof o!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let u=e.let("valid",false),l=e.const("tag",(0, Cr._)`${t}${(0, Cr.getProperty)(o)}`);e.if((0, Cr._)`typeof ${l} == "string"`,()=>c(),()=>n.error(false,{discrError:Yc.DiscrError.Tag,tag:l,tagName:o})),n.ok(u);function c(){let p=f();e.if(false);for(let g in p)e.elseIf((0, Cr._)`${l} === ${g}`),e.assign(u,h(p[g]));e.else(),n.error(false,{discrError:Yc.DiscrError.Mapping,tag:l,tagName:o}),e.endIf();}function h(p){let g=e.name("valid"),m=n.subschema({keyword:"oneOf",schemaProp:p},g);return n.mergeEvaluated(m,Cr.Name),g}function f(){var p;let g={},m=b(i),C=true;for(let _=0;_<s.length;_++){let y=s[_];if(y?.$ref&&!(0, aD.schemaHasRulesButRef)(y,a.self.RULES)){let w=y.$ref;if(y=Jg.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,w),y instanceof Jg.SchemaEnv&&(y=y.schema),y===void 0)throw new sD.default(a.opts.uriResolver,a.baseId,w)}let E=(p=y?.properties)===null||p===void 0?void 0:p[o];if(typeof E!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);C=C&&(m||b(y)),v(E,_);}if(!C)throw new Error(`discriminator: "${o}" must be required`);return g;function b({required:_}){return Array.isArray(_)&&_.includes(o)}function v(_,y){if(_.const)d(_.const,y);else if(_.enum)for(let E of _.enum)d(E,y);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function d(_,y){if(typeof _!="string"||_ in g)throw new Error(`discriminator: "${o}" values must be unique strings`);g[_]=y;}}}};Zc.default=uD;});var zg=S((ok,lD)=>{lD.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true};});var Ug=S((le,eh)=>{Object.defineProperty(le,"__esModule",{value:true});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var cD=sc(),hD=Wg(),dD=Qc(),Hg=zg(),fD=["/properties"],sa="http://json-schema.org/draft-07/schema",br=class extends cD.default{_addVocabularies(){super._addVocabularies(),hD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(dD.default);}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Hg,fD):Hg;this.addMetaSchema(e,sa,false),this.refs["http://json-schema.org/schema"]=sa;}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(sa)?sa:void 0)}};le.Ajv=br;eh.exports=le=br;eh.exports.Ajv=br;Object.defineProperty(le,"__esModule",{value:true});le.default=br;var pD=dr();Object.defineProperty(le,"KeywordCxt",{enumerable:true,get:function(){return pD.KeywordCxt}});var _r=k();Object.defineProperty(le,"_",{enumerable:true,get:function(){return _r._}});Object.defineProperty(le,"str",{enumerable:true,get:function(){return _r.str}});Object.defineProperty(le,"stringify",{enumerable:true,get:function(){return _r.stringify}});Object.defineProperty(le,"nil",{enumerable:true,get:function(){return _r.nil}});Object.defineProperty(le,"Name",{enumerable:true,get:function(){return _r.Name}});Object.defineProperty(le,"CodeGen",{enumerable:true,get:function(){return _r.CodeGen}});var mD=pi();Object.defineProperty(le,"ValidationError",{enumerable:true,get:function(){return mD.default}});var gD=fr();Object.defineProperty(le,"MissingRefError",{enumerable:true,get:function(){return gD.default}});});var nh=S(Ti=>{Object.defineProperty(Ti,"__esModule",{value:true});Ti.dynamicAnchor=void 0;var th=k(),yD=ut(),Kg=mi(),vD=zs(),CD={keyword:"$dynamicAnchor",schemaType:"string",code:n=>Xg(n,n.schema)};function Xg(n,e){let{gen:t,it:r}=n;r.schemaEnv.root.dynamicAnchors[e]=true;let i=(0, th._)`${yD.default.dynamicAnchors}${(0, th.getProperty)(e)}`,a=r.errSchemaPath==="#"?r.validateName:bD(n);t.if((0, th._)`!${i}`,()=>t.assign(i,a));}Ti.dynamicAnchor=Xg;function bD(n){let{schemaEnv:e,schema:t,self:r}=n.it,{root:i,baseId:a,localRefs:s,meta:o}=e.root,{schemaId:u}=r.opts,l=new Kg.SchemaEnv({schema:t,schemaId:u,root:i,baseId:a,localRefs:s,meta:o});return Kg.compileSchema.call(r,l),(0, vD.getValidate)(n,l)}Ti.default=CD;});var rh=S(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.dynamicRef=void 0;var Yg=k(),_D=ut(),Zg=zs(),SD={keyword:"$dynamicRef",schemaType:"string",code:n=>Qg(n,n.schema)};function Qg(n,e){let{gen:t,keyword:r,it:i}=n;if(e[0]!=="#")throw new Error(`"${r}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)s();else {let u=t.let("valid",false);s(u),n.ok(u);}function s(u){if(i.schemaEnv.root.dynamicAnchors[a]){let l=t.let("_v",(0, Yg._)`${_D.default.dynamicAnchors}${(0, Yg.getProperty)(a)}`);t.if(l,o(l,u),o(i.validateName,u));}else o(i.validateName,u)();}function o(u,l){return l?()=>t.block(()=>{(0, Zg.callRef)(n,u),t.let(l,true);}):()=>(0, Zg.callRef)(n,u)}}Ni.dynamicRef=Qg;Ni.default=SD;});var ey=S(ih=>{Object.defineProperty(ih,"__esModule",{value:true});var ED=nh(),wD=q(),DD={keyword:"$recursiveAnchor",schemaType:"boolean",code(n){n.schema?(0, ED.dynamicAnchor)(n,""):(0, wD.checkStrictMode)(n.it,"$recursiveAnchor: false is ignored");}};ih.default=DD;});var ty=S(sh=>{Object.defineProperty(sh,"__esModule",{value:true});var AD=rh(),PD={keyword:"$recursiveRef",schemaType:"string",code:n=>(0, AD.dynamicRef)(n,n.schema)};sh.default=PD;});var ny=S(ah=>{Object.defineProperty(ah,"__esModule",{value:true});var OD=nh(),xD=rh(),TD=ey(),ND=ty(),FD=[OD.default,xD.default,TD.default,ND.default];ah.default=FD;});var iy=S(oh=>{Object.defineProperty(oh,"__esModule",{value:true});var ry=Zs(),ID={keyword:"dependentRequired",type:"object",schemaType:"object",error:ry.error,code:n=>(0, ry.validatePropertyDeps)(n)};oh.default=ID;});var sy=S(uh=>{Object.defineProperty(uh,"__esModule",{value:true});var kD=Zs(),VD={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0, kD.validateSchemaDeps)(n)};uh.default=VD;});var ay=S(lh=>{Object.defineProperty(lh,"__esModule",{value:true});var RD=q(),$D={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:e,it:t}){e.contains===void 0&&(0, RD.checkStrictMode)(t,`"${n}" without "contains" is ignored`);}};lh.default=$D;});var oy=S(ch=>{Object.defineProperty(ch,"__esModule",{value:true});var jD=iy(),LD=sy(),qD=ay(),BD=[jD.default,LD.default,qD.default];ch.default=BD;});var ly=S(hh=>{Object.defineProperty(hh,"__esModule",{value:true});var pn=k(),uy=q(),WD=ut(),MD={message:"must NOT have unevaluated properties",params:({params:n})=>(0, pn._)`{unevaluatedProperty: ${n.unevaluatedProperty}}`},GD={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:true,error:MD,code(n){let{gen:e,schema:t,data:r,errsCount:i,it:a}=n;if(!i)throw new Error("ajv implementation error");let{allErrors:s,props:o}=a;o instanceof pn.Name?e.if((0, pn._)`${o} !== true`,()=>e.forIn("key",r,h=>e.if(l(o,h),()=>u(h)))):o!==true&&e.forIn("key",r,h=>o===void 0?u(h):e.if(c(o,h),()=>u(h))),a.props=true,n.ok((0, pn._)`${i} === ${WD.default.errors}`);function u(h){if(t===false){n.setParams({unevaluatedProperty:h}),n.error(),s||e.break();return}if(!(0, uy.alwaysValidSchema)(a,t)){let f=e.name("valid");n.subschema({keyword:"unevaluatedProperties",dataProp:h,dataPropType:uy.Type.Str},f),s||e.if((0, pn.not)(f),()=>e.break());}}function l(h,f){return (0, pn._)`!${h} || !${h}[${f}]`}function c(h,f){let p=[];for(let g in h)h[g]===true&&p.push((0, pn._)`${f} !== ${g}`);return (0, pn.and)(...p)}}};hh.default=GD;});var hy=S(dh=>{Object.defineProperty(dh,"__esModule",{value:true});var Wn=k(),cy=q(),JD={message:({params:{len:n}})=>(0, Wn.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, Wn._)`{limit: ${n}}`},zD={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:JD,code(n){let{gen:e,schema:t,data:r,it:i}=n,a=i.items||0;if(a===true)return;let s=e.const("len",(0, Wn._)`${r}.length`);if(t===false)n.setParams({len:a}),n.fail((0, Wn._)`${s} > ${a}`);else if(typeof t=="object"&&!(0, cy.alwaysValidSchema)(i,t)){let u=e.var("valid",(0, Wn._)`${s} <= ${a}`);e.if((0, Wn.not)(u),()=>o(u,a)),n.ok(u);}i.items=true;function o(u,l){e.forRange("i",l,s,c=>{n.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:cy.Type.Num},u),i.allErrors||e.if((0, Wn.not)(u),()=>e.break());});}}};dh.default=zD;});var dy=S(fh=>{Object.defineProperty(fh,"__esModule",{value:true});var HD=ly(),UD=hy(),KD=[HD.default,UD.default];fh.default=KD;});var py=S(ph=>{Object.defineProperty(ph,"__esModule",{value:true});var XD=uc(),YD=wc(),ZD=Jc(),QD=ny(),eA=oy(),tA=dy(),nA=Uc(),fy=Kc(),rA=[QD.default,XD.default,YD.default,(0, ZD.default)(true),nA.default,fy.metadataVocabulary,fy.contentVocabulary,eA.default,tA.default];ph.default=rA;});var my=S((_k,iA)=>{iA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:true,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:true,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:true},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:true}}};});var gy=S((Sk,sA)=>{sA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":true},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}};});var yy=S((Ek,aA)=>{aA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}};});var vy=S((wk,oA)=>{oA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}};});var Cy=S((Dk,uA)=>{uA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}};});var by=S((Ak,lA)=>{lA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}};});var _y=S((Pk,cA)=>{cA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:true,deprecated:{type:"boolean",default:false},readOnly:{type:"boolean",default:false},writeOnly:{type:"boolean",default:false},examples:{type:"array",items:true}}};});var Sy=S((Ok,hA)=>{hA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":true},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:true}]},const:true,enum:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}}};});var Ey=S(mh=>{Object.defineProperty(mh,"__esModule",{value:true});var dA=my(),fA=gy(),pA=yy(),mA=vy(),gA=Cy(),yA=by(),vA=_y(),CA=Sy(),bA=["/properties"];function _A(n){return [dA,fA,pA,mA,gA,e(this,yA),vA,e(this,CA)].forEach(t=>this.addMetaSchema(t,void 0,false)),this;function e(t,r){return n?t.$dataMetaSchema(r,bA):r}}mh.default=_A;});var wy=S((ce,yh)=>{Object.defineProperty(ce,"__esModule",{value:true});ce.MissingRefError=ce.ValidationError=ce.CodeGen=ce.Name=ce.nil=ce.stringify=ce.str=ce._=ce.KeywordCxt=ce.Ajv2020=void 0;var SA=sc(),EA=py(),wA=Qc(),DA=Ey(),gh="https://json-schema.org/draft/2020-12/schema",Sr=class extends SA.default{constructor(e={}){super({...e,dynamicRef:true,next:true,unevaluated:true});}_addVocabularies(){super._addVocabularies(),EA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(wA.default);}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(DA.default.call(this,e),this.refs["http://json-schema.org/schema"]=gh);}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(gh)?gh:void 0)}};ce.Ajv2020=Sr;yh.exports=ce=Sr;yh.exports.Ajv2020=Sr;Object.defineProperty(ce,"__esModule",{value:true});ce.default=Sr;var AA=dr();Object.defineProperty(ce,"KeywordCxt",{enumerable:true,get:function(){return AA.KeywordCxt}});var Er=k();Object.defineProperty(ce,"_",{enumerable:true,get:function(){return Er._}});Object.defineProperty(ce,"str",{enumerable:true,get:function(){return Er.str}});Object.defineProperty(ce,"stringify",{enumerable:true,get:function(){return Er.stringify}});Object.defineProperty(ce,"nil",{enumerable:true,get:function(){return Er.nil}});Object.defineProperty(ce,"Name",{enumerable:true,get:function(){return Er.Name}});Object.defineProperty(ce,"CodeGen",{enumerable:true,get:function(){return Er.CodeGen}});var PA=pi();Object.defineProperty(ce,"ValidationError",{enumerable:true,get:function(){return PA.default}});var OA=fr();Object.defineProperty(ce,"MissingRefError",{enumerable:true,get:function(){return OA.default}});});var Ch=S(aa=>{Object.defineProperty(aa,"__esModule",{value:true});aa.CompilerOptions=void 0;var vh=class{constructor(e=null,t=[],r=false,i=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=r,this.errorHandler=i,this.fileHandler=a;}};aa.CompilerOptions=vh;});var Dy=S(oa=>{Object.defineProperty(oa,"__esModule",{value:true});oa.DebugSourceRange=void 0;var bh=class{constructor(e,t,r){this.length=e,this.debugMetadata=t,this.text=r;}};oa.DebugSourceRange=bh;});var wr=S(ua=>{Object.defineProperty(ua,"__esModule",{value:true});ua.ErrorType=void 0;var Ay;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(Ay||(ua.ErrorType=Ay={}));});var Py=S(la=>{Object.defineProperty(la,"__esModule",{value:true});la.Argument=void 0;var _h=class{constructor(e=null,t=null,r=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=r;}get typeName(){return "Argument"}};la.Argument=_h;});var ne=S(Ee=>{Object.defineProperty(Ee,"__esModule",{value:true});Ee.filterUndef=Ee.isEquatable=Ee.nullIfUndefined=Ee.asINamedContentOrNull=Ee.asBooleanOrThrows=Ee.asNumberOrThrows=Ee.asOrThrows=Ee.asOrNull=void 0;function xA(n,e){return n instanceof e?Oy(n):null}Ee.asOrNull=xA;function TA(n,e){if(n instanceof e)return Oy(n);throw new Error(`${n} is not of type ${e}`)}Ee.asOrThrows=TA;function NA(n){if(typeof n=="number")return n;throw new Error(`${n} is not a number`)}Ee.asNumberOrThrows=NA;function FA(n){if(typeof n=="boolean")return n;throw new Error(`${n} is not a boolean`)}Ee.asBooleanOrThrows=FA;function IA(n){return n.hasValidName&&n.name?n:null}Ee.asINamedContentOrNull=IA;function kA(n){return typeof n>"u"?null:n}Ee.nullIfUndefined=kA;function VA(n){return typeof n=="object"&&typeof n.Equals=="function"}Ee.isEquatable=VA;function Oy(n,e){return n}function RA(n){return n!=null}Ee.filterUndef=RA;});var de=S(ca=>{Object.defineProperty(ca,"__esModule",{value:true});ca.ParsedObject=void 0;var xy=ne(),Sh=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let r of t)r.hasOwnProperty("parent")&&(r.parent=this),this.content.push(r);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let r=(0, xy.asOrNull)(this,e);if(r!==null&&(t===null||t(r)===true))return r;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,r)=>{let i=Array.isArray(r)?r:[],a=(0, xy.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&i.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,r=false){if(t===null&&(t=this),!(t._alreadyHadError&&!r||t._alreadyHadWarning&&r)){if(this.parent)this.parent.Error(e,t,r);else throw new Error(`No parent object to send error to: ${e}`);r?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};ca.ParsedObject=Sh;});var da=S(ha=>{Object.defineProperty(ha,"__esModule",{value:true});ha.AuthorWarning=void 0;var $A=de(),Eh=class extends $A.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};ha.AuthorWarning=Eh;});var Ye=S(Fi=>{Object.defineProperty(Fi,"__esModule",{value:true});Fi.Path=void 0;var Dr=class n{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof n.Component&&arguments[1]instanceof n){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new n(e)}else return n.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new n;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new n,r=0;for(let i=0;i<e._components.length&&e._components[i].isParent;++i)r++;for(let i=0;i<this._components.length-r;++i)t._components.push(this._components[i]);for(let i=r;i<e._components.length;++i)t._components.push(e._components[i]);return t}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let t=this._componentsString.split(".");for(let r of t)/^(\-|\+)?([0-9]+|Infinity)$/.test(r)?this._components.push(new n.Component(parseInt(r))):this._components.push(new n.Component(r));}toString(){return this.componentsString}Equals(e){if(e==null||e._components.length!=this._components.length||e.isRelative!=this.isRelative)return false;for(let t=0,r=e._components.length;t<r;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new n;return t._components.push(...this._components),t._components.push(e),t}};Fi.Path=Dr;Dr.parentId="^";(function(n){class e{constructor(r){this.index=-1,this.name=null,typeof r=="string"?this.name=r:this.index=r;}get isIndex(){return this.index>=0}get isParent(){return this.name==n.parentId}static ToParent(){return new e(n.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(r){return r!=null&&r.isIndex==this.isIndex?this.isIndex?this.index==r.index:this.name==r.name:false}}n.Component=e;})(Dr||(Fi.Path=Dr={}));});var Ii=S(fa=>{Object.defineProperty(fa,"__esModule",{value:true});fa.Debug=void 0;var Ty;(function(n){function e(r,i,a){t(r instanceof i,a);}n.AssertType=e;function t(r,i){if(!r)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}n.Assert=t;})(Ty||(fa.Debug=Ty={}));});var ke=S(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.throwNullException=Ar.NullException=void 0;var pa=class extends Error{};Ar.NullException=pa;function jA(n){throw new pa(`${n} is null or undefined`)}Ar.throwNullException=jA;});var Ze=S(ga=>{Object.defineProperty(ga,"__esModule",{value:true});ga.InkObject=void 0;var Pr=Ye(),ki=ye(),wh=Ii(),Or=ne(),ma=ke(),Dh=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let r=t.ContentAtPath(e).obj;if(r){let i=r.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Pr.Path;else {let e=[],t=this,r=(0, Or.asOrNull)(t.parent,ki.Container);for(;r!==null;){let i=(0, Or.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, ma.throwNullException)("namedChild.name");e.unshift(new Pr.Path.Component(i.name));}else e.unshift(new Pr.Path.Component(r.content.indexOf(t)));t=r,r=(0, Or.asOrNull)(r.parent,ki.Container);}this._path=new Pr.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, ma.throwNullException)("path");if(e.isRelative){let t=(0, Or.asOrNull)(this,ki.Container);return t===null&&(wh.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, Or.asOrNull)(this.parent,ki.Container),wh.Debug.Assert(t!==null,"Expected parent to be a container"),wh.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, ma.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, ma.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,r=Math.min(e.length,t.length),i=-1;for(let u=0;u<r;++u){let l=t.GetComponent(u),c=e.GetComponent(u);if(l.Equals(c))i=u;else break}if(i==-1)return e;let a=t.componentCount-1-i,s=[];for(let u=0;u<a;++u)s.push(Pr.Path.Component.ToParent());for(let u=i+1;u<e.componentCount;++u)s.push(e.GetComponent(u));return new Pr.Path(s,true)}CompactPathString(e){let t=null,r=null;return e.isRelative?(r=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(r=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),r.length<t.length?r:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, Or.asOrNull)(e,ki.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,r){e[t]&&(e[t]=null),e[t]=r,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};ga.InkObject=Dh;});var Mn=S(ya=>{Object.defineProperty(ya,"__esModule",{value:true});ya.StringBuilder=void 0;var Ah=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=`
9
- `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(r,i)=>typeof t[i]<"u"?t[i]:r);}toString(){return this.string}Clear(){this.string="";}};ya.StringBuilder=Ah;});var et=S(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.InkList=xr.InkListItem=void 0;var kt=ke(),LA=Mn(),Qe=class n{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new n(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(e){if(e instanceof n){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new n(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!n.isLikeInkListItem(t))return n.Null;let r=t;return new n(r.originName,r.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};xr.InkListItem=Qe;var Ph=class n extends Map{constructor(){if(super(arguments[0]instanceof n?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof n){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, kt.throwNullException)("originStory.listDefinitions");let r=t.listDefinitions.TryListGetDefinition(e,null);if(r.exists){if(r.result===null)return (0, kt.throwNullException)("def.result");this.origins=[r.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var r;if(e==null||e=="")return new n;let i=(r=t.listDefinitions)===null||r===void 0?void 0:r.FindSingleItemListWithName(e);if(i)return i.value===null?(0, kt.throwNullException)("listValue.value"):new n(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof Qe){let r=e;if(r.originName==null){this.AddItem(r.itemName);return}if(this.origins===null)return (0, kt.throwNullException)("this.origins");for(let i of this.origins)if(i.name==r.originName){let a=i.TryGetValueForItem(r,0);if(a.exists){this.Add(r,a.result);return}else throw new Error("Could not add the item "+r+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let r=e,i=null;if(this.origins===null)return (0, kt.throwNullException)("this.origins");for(let a of this.origins){if(r===null)return (0, kt.throwNullException)("itemName");if(a.ContainsItemWithName(r)){if(i!=null)throw new Error("Could not add the item "+r+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+r+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=n.FromString(r,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new Qe(i.name,r),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(Qe.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let r=e.serialized();if(this.has(r))throw new Error(`The Map already contains an entry for ${e}`);this.set(r,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(r=>r.name==e?(t=r,false):true),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=Qe.fromSerializedKey(e);if(t.originName===null)return (0, kt.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:Qe.Null,Value:0};for(let[t,r]of this){let i=Qe.fromSerializedKey(t);(e.Key.isNull||r>e.Value)&&(e={Key:i,Value:r});}return e}get minItem(){let e={Key:Qe.Null,Value:0};for(let[t,r]of this){let i=Qe.fromSerializedKey(t);(e.Key.isNull||r<e.Value)&&(e={Key:i,Value:r});}return e}get inverse(){let e=new n;if(this.origins!=null)for(let t of this.origins)for(let[r,i]of t.items){let a=Qe.fromSerializedKey(r);this.ContainsKey(a)||e.Add(a,i);}return e}get all(){let e=new n;if(this.origins!=null)for(let t of this.origins)for(let[r,i]of t.items){let a=Qe.fromSerializedKey(r);e.set(a.serialized(),i);}return e}Union(e){let t=new n(this);for(let[r,i]of e)t.set(r,i);return t}Intersect(e){let t=new n;for(let[r,i]of this)e.has(r)&&t.set(r,i);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new n(this);for(let[r]of e)t.delete(r);return t}Contains(e){if(typeof e=="string")return this.ContainsItemNamed(e);let t=e;if(t.size==0||this.size==0)return false;for(let[r]of t)if(!this.has(r))return false;return true}GreaterThan(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>e.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<e.minItem.Value}LessThanOrEquals(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<=e.maxItem.Value&&this.minItem.Value<=e.minItem.Value}MaxAsList(){return this.Count>0?new n(this.maxItem):new n}MinAsList(){return this.Count>0?new n(this.minItem):new n}ListWithSubRange(e,t){if(this.Count==0)return new n;let r=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof n&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof n&&t.Count>0&&(a=t.maxItem.Value);let s=new n;s.SetInitialOriginNames(this.originNames);for(let o of r)o.Value>=i&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(e){if(!(e instanceof n)||e.Count!=this.Count)return false;for(let[t]of this)if(!e.has(t))return false;return true}get orderedItems(){let e=new Array;for(let[t,r]of this){let i=Qe.fromSerializedKey(t);e.push({Key:i,Value:r});}return e.sort((t,r)=>t.Key.originName===null?(0, kt.throwNullException)("x.Key.originName"):r.Key.originName===null?(0, kt.throwNullException)("y.Key.originName"):t.Value==r.Value?t.Key.originName.localeCompare(r.Key.originName):t.Value<r.Value?-1:t.Value>r.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new LA.StringBuilder;for(let r=0;r<e.length;r++){r>0&&t.Append(", ");let i=e[r].Key;if(i.itemName===null)return (0, kt.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};xr.InkList=Ph;});var Vi=S(va=>{Object.defineProperty(va,"__esModule",{value:true});va.StoryException=void 0;var Oh=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};va.StoryException=Oh;});var Tr=S(mn=>{Object.defineProperty(mn,"__esModule",{value:true});mn.tryParseFloat=mn.tryParseInt=mn.tryGetValueFromMap=void 0;function qA(n,e,t){if(n===null)return {result:t,exists:false};let r=n.get(e);return typeof r>"u"?{result:t,exists:false}:{result:r,exists:true}}mn.tryGetValueFromMap=qA;function BA(n,e=0){let t=parseInt(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}mn.tryParseInt=BA;function WA(n,e=0){let t=parseFloat(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}mn.tryParseFloat=WA;});var fe=S(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.ValueType=pe.ListValue=pe.VariablePointerValue=pe.DivertTargetValue=pe.StringValue=pe.FloatValue=pe.IntValue=pe.BoolValue=pe.Value=pe.AbstractValue=void 0;var Ny=Ze(),Fy=Ye(),Gn=et(),MA=Vi(),Ri=ne(),Iy=Tr(),dt=ke(),Ca=class n extends Ny.InkObject{static Create(e,t){if(t){if(t===he.Int&&Number.isInteger(Number(e)))return new Rt(Number(e));if(t===he.Float&&!isNaN(e))return new $t(Number(e))}if(typeof e=="boolean")return new Nr(!!e);if(typeof e=="string")return new Zt(String(e));if(Number.isInteger(Number(e)))return new Rt(Number(e));if(isNaN(e)){if(e instanceof Fy.Path)return new ba((0, Ri.asOrThrows)(e,Fy.Path));if(e instanceof Gn.InkList)return new _a((0, Ri.asOrThrows)(e,Gn.InkList))}else return new $t(Number(e));return null}Copy(){return (0, Ri.asOrThrows)(n.Create(this.valueObject),Ny.InkObject)}BadCastException(e){return new MA.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};pe.AbstractValue=Ca;var Vt=class extends Ca{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, dt.throwNullException)("Value.value"):this.value.toString()}};pe.Value=Vt;var Nr=class extends Vt{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return he.Bool}Cast(e){if(this.value===null)return (0, dt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==he.Int)return new Rt(this.value?1:0);if(e==he.Float)return new $t(this.value?1:0);if(e==he.String)return new Zt(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};pe.BoolValue=Nr;var Rt=class extends Vt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return he.Int}Cast(e){if(this.value===null)return (0, dt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==he.Bool)return new Nr(this.value!==0);if(e==he.Float)return new $t(this.value);if(e==he.String)return new Zt(""+this.value);throw this.BadCastException(e)}};pe.IntValue=Rt;var $t=class extends Vt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return he.Float}Cast(e){if(this.value===null)return (0, dt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==he.Bool)return new Nr(this.value!==0);if(e==he.Int)return new Rt(this.value);if(e==he.String)return new Zt(""+this.value);throw this.BadCastException(e)}};pe.FloatValue=$t;var Zt=class extends Vt{constructor(e){if(super(e||""),this._isNewline=this.value==`
10
- `,this._isInlineWhitespace=true,this.value===null)return (0, dt.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return he.String}get isTruthy(){return this.value===null?(0, dt.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==he.Int){let t=(0, Iy.tryParseInt)(this.value);if(t.exists)return new Rt(t.result);throw this.BadCastException(e)}if(e==he.Float){let t=(0, Iy.tryParseFloat)(this.value);if(t.exists)return new $t(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};pe.StringValue=Zt;var ba=class extends Vt{constructor(e=null){super(e);}get valueType(){return he.DivertTarget}get targetPath(){return this.value===null?(0, dt.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};pe.DivertTargetValue=ba;var xh=class n extends Vt{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, dt.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return he.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new n(this.variableName,this.contextIndex)}};pe.VariablePointerValue=xh;var _a=class n extends Vt{get isTruthy(){return this.value===null?(0, dt.throwNullException)("this.value"):this.value.Count>0}get valueType(){return he.List}Cast(e){if(this.value===null)return (0, dt.throwNullException)("Value.value");if(e==he.Int){let t=this.value.maxItem;return t.Key.isNull?new Rt(0):new Rt(t.Value)}else if(e==he.Float){let t=this.value.maxItem;return t.Key.isNull?new $t(0):new $t(t.Value)}else if(e==he.String){let t=this.value.maxItem;return t.Key.isNull?new Zt(""):new Zt(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new Gn.InkList:e instanceof Gn.InkList?this.value=new Gn.InkList(e):e instanceof Gn.InkListItem&&typeof t=="number"&&(this.value=new Gn.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let r=(0, Ri.asOrNull)(e,n),i=(0, Ri.asOrNull)(t,n);if(i&&i.value===null)return (0, dt.throwNullException)("newList.value");if(r&&r.value===null)return (0, dt.throwNullException)("oldList.value");r&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}};pe.ListValue=_a;var he;(function(n){n[n.Bool=-1]="Bool",n[n.Int=0]="Int",n[n.Float=1]="Float",n[n.List=2]="List",n[n.String=3]="String",n[n.DivertTarget=4]="DivertTarget",n[n.VariablePointer=5]="VariablePointer";})(he||(pe.ValueType=he={}));});var ky=S(Sa=>{Object.defineProperty(Sa,"__esModule",{value:true});Sa.SearchResult=void 0;var GA=ye(),Th=class n{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof GA.Container?this.obj:null}copy(){let e=new n;return e.obj=this.obj,e.approximate=this.approximate,e}};Sa.SearchResult=Th;});var ye=S(ji=>{Object.defineProperty(ji,"__esModule",{value:true});ji.Container=void 0;var JA=fe(),Vy=ke(),zA=Mn(),Fr=Ze(),HA=ky(),Ry=Ye(),$y=Ii(),UA=Tr(),gn=ne(),$i=class n extends Fr.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,r]of this.namedContent){let i=(0, gn.asOrThrows)(r,Fr.InkObject);e.set(t,i);}for(let t of this.content){let r=(0, gn.asINamedContentOrNull)(t);r!=null&&r.hasValidName&&e.delete(r.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[r]of t)this.namedContent.delete(r);if(e!=null)for(let[,r]of e){let i=(0, gn.asINamedContentOrNull)(r);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=n.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=n.CountFlags.Turns),this.countingAtStartOnly&&(e|=n.CountFlags.CountStartOnly),e==n.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&n.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&n.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&n.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof n;)t.content.length>0&&(e.push(new Ry.Path.Component(0)),t=t.content[0]);return new Ry.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let r of t)this.AddContent(r);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, gn.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){$y.Debug.AssertType(e,Fr.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, gn.asOrThrows)(e,Fr.InkObject);if(t.parent=this,e.name===null)return (0, Vy.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,r=-1){r==-1&&(r=e.length);let i=new HA.SearchResult;i.approximate=false;let a=this,s=this;for(let o=t;o<r;++o){let u=e.GetComponent(o);if(a==null){i.approximate=true;break}let l=a.ContentWithPathComponent(u);if(l==null){i.approximate=true;break}let c=(0, gn.asOrNull)(l,n);if(o<r-1&&c==null){i.approximate=true;break}s=l,a=c;}return i.obj=s,i}InsertContent(e,t){if(this.content.splice(t,0,e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}AddContentsOfContainer(e){this.content.push(...e.content);for(let t of e.content)t.parent=this,this.TryAddNamedContent(t);}ContentWithPathComponent(e){if(e.isIndex)return e.index>=0&&e.index<this.content.length?this.content[e.index]:null;if(e.isParent)return this.parent;{if(e.name===null)return (0, Vy.throwNullException)("component.name");let t=(0, UA.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, gn.asOrThrows)(t.result,Fr.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new zA.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],r=arguments[2];function i(){for(let o=0;o<4*t;++o)e.Append(" ");}i(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==r&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof n?o.BuildStringOfHierarchy(e,t,r):(i(),o instanceof JA.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
11
- `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof n)&&o==r&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, gn.asOrThrows)(o,Fr.InkObject))>=0||a.set(s,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,s]of a)$y.Debug.AssertType(s,n,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,r),e.AppendLine();}t--,i(),e.Append("]");}};ji.Container=$i;(function(n){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(n.CountFlags||(n.CountFlags={}));})($i||(ji.Container=$i={}));});var Ve=S(qi=>{Object.defineProperty(qi,"__esModule",{value:true});qi.ControlCommand=void 0;var KA=Ze(),Li=class n extends KA.InkObject{get commandType(){return this._commandType}constructor(e=n.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new n(this.commandType)}static EvalStart(){return new n(n.CommandType.EvalStart)}static EvalOutput(){return new n(n.CommandType.EvalOutput)}static EvalEnd(){return new n(n.CommandType.EvalEnd)}static Duplicate(){return new n(n.CommandType.Duplicate)}static PopEvaluatedValue(){return new n(n.CommandType.PopEvaluatedValue)}static PopFunction(){return new n(n.CommandType.PopFunction)}static PopTunnel(){return new n(n.CommandType.PopTunnel)}static BeginString(){return new n(n.CommandType.BeginString)}static EndString(){return new n(n.CommandType.EndString)}static NoOp(){return new n(n.CommandType.NoOp)}static ChoiceCount(){return new n(n.CommandType.ChoiceCount)}static Turns(){return new n(n.CommandType.Turns)}static TurnsSince(){return new n(n.CommandType.TurnsSince)}static ReadCount(){return new n(n.CommandType.ReadCount)}static Random(){return new n(n.CommandType.Random)}static SeedRandom(){return new n(n.CommandType.SeedRandom)}static VisitIndex(){return new n(n.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new n(n.CommandType.SequenceShuffleIndex)}static StartThread(){return new n(n.CommandType.StartThread)}static Done(){return new n(n.CommandType.Done)}static End(){return new n(n.CommandType.End)}static ListFromInt(){return new n(n.CommandType.ListFromInt)}static ListRange(){return new n(n.CommandType.ListRange)}static ListRandom(){return new n(n.CommandType.ListRandom)}static BeginTag(){return new n(n.CommandType.BeginTag)}static EndTag(){return new n(n.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};qi.ControlCommand=Li;(function(n){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(n.CommandType||(n.CommandType={}));})(Li||(qi.ControlCommand=Li={}));});var ft=S(Ea=>{Object.defineProperty(Ea,"__esModule",{value:true});Ea.Expression=void 0;var jy=ye(),Nh=Ve(),XA=de(),Fh=class extends XA.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new jy.Container;return e.AddContent(Nh.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(Nh.ControlCommand.EvalOutput()),e.AddContent(Nh.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new jy.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let r=t.Copy();r&&e.AddContent(r);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};Ea.Expression=Fh;});var Jn=S(wa=>{Object.defineProperty(wa,"__esModule",{value:true});wa.Void=void 0;var YA=Ze(),Ih=class extends YA.InkObject{toString(){return "Void"}};wa.Void=Ih;});var jt=S(Aa=>{Object.defineProperty(Aa,"__esModule",{value:true});Aa.NativeFunctionCall=void 0;var T=fe(),Bi=Vi(),ZA=Jn(),Da=et(),QA=Ze(),pt=ne(),tt=ke(),G=class n extends QA.InkObject{static CallWithName(e){return new n(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, tt.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(n._nativeFunctions===null?(0, tt.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=n._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof ZA.Void)throw new Bi.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');a instanceof T.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let r=this.CoerceValuesToSingleType(e),i=r[0].valueType;return i==T.ValueType.Int?this.CallType(r):i==T.ValueType.Float?this.CallType(r):i==T.ValueType.String?this.CallType(r):i==T.ValueType.DivertTarget?this.CallType(r):i==T.ValueType.List?this.CallType(r):null}CallType(e){let t=(0, pt.asOrThrows)(e[0],T.Value),r=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, tt.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(r);if(!s){let o=T.ValueType[r];throw new Bi.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let u=(0, pt.asOrThrows)(e[1],T.Value),l=s;if(i.value===null||u.value===null)return (0, tt.throwNullException)("NativeFunctionCall.Call BinaryOp values");let c=l(i.value,u.value);return T.Value.Create(c)}else {let o=s;if(i.value===null)return (0, tt.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=o(i.value);return this.name===n.Int?T.Value.Create(u,T.ValueType.Int):this.name===n.Float?T.Value.Create(u,T.ValueType.Float):T.Value.Create(u,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof T.ListValue&&e[1]instanceof T.IntValue)return this.CallListIncrementOperation(e);let t=(0, pt.asOrThrows)(e[0],T.Value),r=(0, pt.asOrThrows)(e[1],T.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=T.ValueType.List||r.valueType!=T.ValueType.List)){if(this._operationFuncs===null)return (0, tt.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(T.ValueType.Int);if(i===null)return (0, tt.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, pt.asBooleanOrThrows)(i(t.isTruthy?1:0,r.isTruthy?1:0));return new T.BoolValue(a)}if(t.valueType==T.ValueType.List&&r.valueType==T.ValueType.List)return this.CallType([t,r]);throw new Bi.StoryException("Can not call use "+this.name+" operation on "+T.ValueType[t.valueType]+" and "+T.ValueType[r.valueType])}CallListIncrementOperation(e){let t=(0, pt.asOrThrows)(e[0],T.ListValue),r=(0, pt.asOrThrows)(e[1],T.IntValue),i=new Da.InkList;if(t.value===null)return (0, tt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=Da.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, tt.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(T.ValueType.Int);if(r.value===null)return (0, tt.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(s,r.value),c=null;if(t.value.origins===null)return (0, tt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let h of t.value.origins)if(h.name==o.originName){c=h;break}if(c!=null){let h=c.TryGetItemWithValue(l,Da.InkListItem.Null);h.exists&&i.Add(h.result,l);}}return new T.ListValue(i)}CoerceValuesToSingleType(e){let t=T.ValueType.Int,r=null;for(let a of e){let s=(0, pt.asOrThrows)(a,T.Value);s.valueType>t&&(t=s.valueType),s.valueType==T.ValueType.List&&(r=(0, pt.asOrNull)(s,T.ListValue));}let i=[];if(T.ValueType[t]==T.ValueType[T.ValueType.List])for(let a of e){let s=(0, pt.asOrThrows)(a,T.Value);if(s.valueType==T.ValueType.List)i.push(s);else if(s.valueType==T.ValueType.Int){let o=parseInt(s.valueObject);if(r=(0, pt.asOrThrows)(r,T.ListValue),r.value===null)return (0, tt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=r.value.originOfMaxItem;if(u===null)return (0, tt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(o,Da.InkListItem.Null);if(l.exists){let c=new T.ListValue(l.result,o);i.push(c);}else throw new Bi.StoryException("Could not find List item with the value "+o+" in "+u.name)}else {let o=T.ValueType[s.valueType];throw new Bi.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, pt.asOrThrows)(a,T.Value).Cast(t);i.push(o);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)n.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];n.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=true,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(r,i)=>r+i),this.AddIntBinaryOp(this.Subtract,(r,i)=>r-i),this.AddIntBinaryOp(this.Multiply,(r,i)=>r*i),this.AddIntBinaryOp(this.Divide,(r,i)=>Math.floor(r/i)),this.AddIntBinaryOp(this.Mod,(r,i)=>r%i),this.AddIntUnaryOp(this.Negate,r=>-r),this.AddIntBinaryOp(this.Equal,(r,i)=>r==i),this.AddIntBinaryOp(this.Greater,(r,i)=>r>i),this.AddIntBinaryOp(this.Less,(r,i)=>r<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(r,i)=>r>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(r,i)=>r<=i),this.AddIntBinaryOp(this.NotEquals,(r,i)=>r!=i),this.AddIntUnaryOp(this.Not,r=>r==0),this.AddIntBinaryOp(this.And,(r,i)=>r!=0&&i!=0),this.AddIntBinaryOp(this.Or,(r,i)=>r!=0||i!=0),this.AddIntBinaryOp(this.Max,(r,i)=>Math.max(r,i)),this.AddIntBinaryOp(this.Min,(r,i)=>Math.min(r,i)),this.AddIntBinaryOp(this.Pow,(r,i)=>Math.pow(r,i)),this.AddIntUnaryOp(this.Floor,n.Identity),this.AddIntUnaryOp(this.Ceiling,n.Identity),this.AddIntUnaryOp(this.Int,n.Identity),this.AddIntUnaryOp(this.Float,r=>r),this.AddFloatBinaryOp(this.Add,(r,i)=>r+i),this.AddFloatBinaryOp(this.Subtract,(r,i)=>r-i),this.AddFloatBinaryOp(this.Multiply,(r,i)=>r*i),this.AddFloatBinaryOp(this.Divide,(r,i)=>r/i),this.AddFloatBinaryOp(this.Mod,(r,i)=>r%i),this.AddFloatUnaryOp(this.Negate,r=>-r),this.AddFloatBinaryOp(this.Equal,(r,i)=>r==i),this.AddFloatBinaryOp(this.Greater,(r,i)=>r>i),this.AddFloatBinaryOp(this.Less,(r,i)=>r<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(r,i)=>r>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(r,i)=>r<=i),this.AddFloatBinaryOp(this.NotEquals,(r,i)=>r!=i),this.AddFloatUnaryOp(this.Not,r=>r==0),this.AddFloatBinaryOp(this.And,(r,i)=>r!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(r,i)=>r!=0||i!=0),this.AddFloatBinaryOp(this.Max,(r,i)=>Math.max(r,i)),this.AddFloatBinaryOp(this.Min,(r,i)=>Math.min(r,i)),this.AddFloatBinaryOp(this.Pow,(r,i)=>Math.pow(r,i)),this.AddFloatUnaryOp(this.Floor,r=>Math.floor(r)),this.AddFloatUnaryOp(this.Ceiling,r=>Math.ceil(r)),this.AddFloatUnaryOp(this.Int,r=>Math.floor(r)),this.AddFloatUnaryOp(this.Float,n.Identity),this.AddStringBinaryOp(this.Add,(r,i)=>r+i),this.AddStringBinaryOp(this.Equal,(r,i)=>r===i),this.AddStringBinaryOp(this.NotEquals,(r,i)=>r!==i),this.AddStringBinaryOp(this.Has,(r,i)=>r.includes(i)),this.AddStringBinaryOp(this.Hasnt,(r,i)=>!r.includes(i)),this.AddListBinaryOp(this.Add,(r,i)=>r.Union(i)),this.AddListBinaryOp(this.Subtract,(r,i)=>r.Without(i)),this.AddListBinaryOp(this.Has,(r,i)=>r.Contains(i)),this.AddListBinaryOp(this.Hasnt,(r,i)=>!r.Contains(i)),this.AddListBinaryOp(this.Intersect,(r,i)=>r.Intersect(i)),this.AddListBinaryOp(this.Equal,(r,i)=>r.Equals(i)),this.AddListBinaryOp(this.Greater,(r,i)=>r.GreaterThan(i)),this.AddListBinaryOp(this.Less,(r,i)=>r.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(r,i)=>r.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(r,i)=>r.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(r,i)=>!r.Equals(i)),this.AddListBinaryOp(this.And,(r,i)=>r.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(r,i)=>r.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,r=>r.Count==0?1:0),this.AddListUnaryOp(this.Invert,r=>r.inverse),this.AddListUnaryOp(this.All,r=>r.all),this.AddListUnaryOp(this.ListMin,r=>r.MinAsList()),this.AddListUnaryOp(this.ListMax,r=>r.MaxAsList()),this.AddListUnaryOp(this.Count,r=>r.Count),this.AddListUnaryOp(this.ValueOfList,r=>r.maxItem.Value);let e=(r,i)=>r.Equals(i),t=(r,i)=>!r.Equals(i);this.AddOpToNativeFunc(this.Equal,2,T.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,T.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,r,i){if(this._nativeFunctions===null)return (0, tt.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new n(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(r,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};Aa.NativeFunctionCall=G;G.Add="+";G.Subtract="-";G.Divide="/";G.Multiply="*";G.Mod="%";G.Negate="_";G.Equal="==";G.Greater=">";G.Less="<";G.GreaterThanOrEquals=">=";G.LessThanOrEquals="<=";G.NotEquals="!=";G.Not="!";G.And="&&";G.Or="||";G.Min="MIN";G.Max="MAX";G.Pow="POW";G.Floor="FLOOR";G.Ceiling="CEILING";G.Int="INT";G.Float="FLOAT";G.Has="?";G.Hasnt="!?";G.Intersect="^";G.ListMin="LIST_MIN";G.ListMax="LIST_MAX";G.All="LIST_ALL";G.Count="LIST_COUNT";G.ValueOfList="LIST_VALUE";G.Invert="LIST_INVERT";G._nativeFunctions=null;});var Oa=S(Pa=>{Object.defineProperty(Pa,"__esModule",{value:true});Pa.NumberExpression=void 0;var eP=ft(),kh=fe(),tP=ne(),Vh=class n extends eP.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=r=>{this.isInt()?r.AddContent(new kh.IntValue(this.value)):this.isFloat()?r.AddContent(new kh.FloatValue(this.value)):this.isBool()&&r.AddContent(new kh.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, tP.asOrNull)(e,n);return t?t.subtype==this.subtype&&t.value==this.value:false}};Pa.NumberExpression=Vh;});var Rh=S(xa=>{Object.defineProperty(xa,"__esModule",{value:true});xa.UnaryExpression=void 0;var nP=ft(),rP=jt(),Ir=Oa(),iP=ne(),Wi=class extends nP.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=r=>{this.innerExpression.GenerateIntoContainer(r),r.AddContent(rP.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};xa.UnaryExpression=Wi;Wi.WithInner=(n,e)=>{let t=(0, iP.asOrNull)(n,Ir.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new Ir.NumberExpression(-t.value,"int");if(t.isFloat())return new Ir.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new Ir.NumberExpression(t.value==0,"bool");if(t.isFloat())return new Ir.NumberExpression(t.value==0,"bool");if(t.isBool())return new Ir.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new Wi(n,e)};});var jh=S(Ta=>{Object.defineProperty(Ta,"__esModule",{value:true});Ta.BinaryExpression=void 0;var sP=ft(),aP=jt(),oP=Rh(),uP=ne(),$h=class extends sP.Expression{constructor(e,t,r){super(),this.opName=r,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(aP.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=r;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, uP.asOrNull)(this.leftExpression,oP.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};Ta.BinaryExpression=$h;});var Gi=S(Na=>{Object.defineProperty(Na,"__esModule",{value:true});Na.CharacterSet=void 0;var Mi=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,r)=>{for(let i=t.charCodeAt(0);i<=r.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let r of t)this.Add(r);else for(let r of t.set)this.Add(r);return this},e&&this.AddCharacters(e);}};Na.CharacterSet=Mi;Mi.FromRange=(n,e)=>new Mi().AddRange(n,e);});var qy=S(Fa=>{Object.defineProperty(Fa,"__esModule",{value:true});Fa.CharacterRange=void 0;var Ly=Gi(),Ji=class{constructor(e,t,r=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Ly.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),a;i<=this.end.charCodeAt(0);i+=1)a=String.fromCharCode(i),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},r instanceof Ly.CharacterSet)this._excludes=r.set;else for(let i of r)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};Fa.CharacterRange=Ji;Ji.Define=(n,e,t=[])=>new Ji(n,e,t);});var ka=S(Ia=>{Object.defineProperty(Ia,"__esModule",{value:true});Ia.ChoicePoint=void 0;var lP=Ze(),cP=Ye(),Lh=ke(),qh=class extends lP.InkObject{constructor(e=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, Lh.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Lh.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new cP.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Lh.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};Ia.ChoicePoint=qh;});var zn=S(Va=>{Object.defineProperty(Va,"__esModule",{value:true});Va.PushPopType=void 0;var By;(function(n){n[n.Tunnel=0]="Tunnel",n[n.Function=1]="Function",n[n.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(By||(Va.PushPopType=By={}));});var zi=S(Ra=>{Object.defineProperty(Ra,"__esModule",{value:true});Ra.Pointer=void 0;var hP=Ye(),Bh=class n{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new hP.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new n(this.container,this.index)}static StartOf(e){return new n(e,0)}static get Null(){return new n(null,-1)}};Ra.Pointer=Bh;});var Lt=S(ja=>{Object.defineProperty(ja,"__esModule",{value:true});ja.Divert=void 0;var dP=Ye(),fP=zn(),pP=Mn(),mP=Ze(),Wh=zi(),Wy=ye(),$a=ke(),Mh=class n extends mP.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=Wh.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, $a.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, $a.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, $a.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof Wy.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Wh.Pointer.StartOf(e instanceof Wy.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new dP.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=Wh.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof e<"u"&&(this.pushesToStack=true,this.stackPushType=e);}Equals(e){let t=e;return t instanceof n&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, $a.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new pP.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==fP.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};ja.Divert=Mh;});var Qt=S(La=>{Object.defineProperty(La,"__esModule",{value:true});La.SymbolType=void 0;var My;(function(n){n[n.Knot=0]="Knot",n[n.List=1]="List",n[n.ListItem=2]="ListItem",n[n.Var=3]="Var",n[n.SubFlowAndWeave=4]="SubFlowAndWeave",n[n.Arg=5]="Arg",n[n.Temp=6]="Temp";})(My||(La.SymbolType=My={}));});var yn=S(qa=>{Object.defineProperty(qa,"__esModule",{value:true});qa.VariableAssignment=void 0;var gP=Ze(),Gh=class extends gP.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};qa.VariableAssignment=Gh;});var kr=S(Wa=>{Object.defineProperty(Wa,"__esModule",{value:true});Wa.Choice=void 0;var yP=ka(),Ba=ye(),vn=Ve(),Jh=Lt(),Gy=fe(),vP=de(),CP=Qt(),Jy=yn(),zh=class extends vP.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,r){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new Ba.Container,this._runtimeChoice=new yP.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(vn.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Gy.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Jy.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(vn.ControlCommand.BeginString()),this._divertToStartContentOuter=new Jh.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Jh.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Ba.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(vn.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(vn.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(vn.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(vn.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Ba.Container,this.startContent){this._returnToR2=new Gy.DivertTargetValue,this._innerContentContainer.AddContent(vn.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(vn.ControlCommand.EvalEnd());let i=new Jy.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Jh.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Ba.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=e,this.choiceOnlyContent=t,this.innerContent=r,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),r&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(e){var t;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,CP.SymbolType.SubFlowAndWeave);}};Wa.Choice=zh;});var zy=S(Ga=>{Object.defineProperty(Ga,"__esModule",{value:true});Ga.StringParserElement=void 0;var Ma=class n{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{n._uniqueIdCounter++,this.uniqueId=n._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};Ga.StringParserElement=Ma;Ma._uniqueIdCounter=1e3;});var Uy=S(Ja=>{Object.defineProperty(Ja,"__esModule",{value:true});Ja.StringParserState=void 0;var Hy=zy(),Hh=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let r=0;r<200;++r)this._stack[r]=new Hy.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],r=this._stack[this._numElements];return this._numElements++,r.CopyFrom(t),r.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],r=this._stack[this._numElements-1];t.SquashFrom(r),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new Hy.StringParserElement;this._numElements=1;}};Ja.StringParserState=Hh;});var Kh=S(Hn=>{Object.defineProperty(Hn,"__esModule",{value:true});Hn.StringParser=Hn.ParseSuccess=void 0;var Uh=Gi(),bP=Uy();Hn.ParseSuccess=Symbol("ParseSuccessStruct");var Hi=class n{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=r=>(this.state.Pop(r),null),this.CancelRule=r=>{this.state.Pop(r);},this.SucceedRule=(r,i=null)=>{let a=this.state.Peek(r),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,s,a),this.state.Squash();let o=i;return o===null&&(o=n.ParseSuccess),o},this.Expect=(r,i=null,a=null)=>{let s=this.ParseObject(r);if(s===null){i===null&&(i=r.name);let o,u=this.LineRemainder();u===null||u.length===0?o="end of line":o=`'${u}'`,this.Error(`Expected ${i} but saw ${o}`),a!==null&&(s=a());}return s},this.Error=(r,i=false)=>{this.ErrorOnLine(r,this.lineIndex+1,i);},this.ErrorWithParsedObject=(r,i,a=false)=>{this.ErrorOnLine(r,i.debugMetadata?i.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(r,i,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(r,this.index,i-1,a);else throw new Error(`${s} on line ${i}: ${r}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=r=>this.Error(r,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
8
+ deps: ${t}}`};var hE={keyword:"dependencies",type:"object",schemaType:"object",error:Vt.error,code(n){let[e,t]=dE(n);wg(n,e),Eg(n,t);}};function dE({schema:n}){let e={},t={};for(let r in n){if(r==="__proto__")continue;let i=Array.isArray(n[r])?e:t;i[r]=n[r];}return [e,t]}function wg(n,e=n.schema){let{gen:t,data:r,it:i}=n;if(Object.keys(e).length===0)return;let a=t.let("missing");for(let s in e){let o=e[s];if(o.length===0)continue;let u=(0, Ni.propertyInData)(t,r,s,i.opts.ownProperties);n.setParams({property:s,depsCount:o.length,deps:o.join(", ")}),i.allErrors?t.if(u,()=>{for(let l of o)(0, Ni.checkReportMissingProp)(n,l);}):(t.if((0, Ic._)`${u} && (${(0, Ni.checkMissingProp)(n,o,a)})`),(0, Ni.reportMissingProp)(n,a),t.else());}}Vt.validatePropertyDeps=wg;function Eg(n,e=n.schema){let{gen:t,data:r,keyword:i,it:a}=n,s=t.name("valid");for(let o in e)(0, cE.alwaysValidSchema)(a,e[o])||(t.if((0, Ni.propertyInData)(t,r,o,a.opts.ownProperties),()=>{let u=n.subschema({keyword:i,schemaProp:o},s);n.mergeValidEvaluated(u,s);},()=>t.var(s,true)),n.ok(s));}Vt.validateSchemaDeps=Eg;Vt.default=hE;});var Ag=_(kc=>{Object.defineProperty(kc,"__esModule",{value:true});var Dg=k(),pE=q(),fE={message:"property name must be valid",params:({params:n})=>(0, Dg._)`{propertyName: ${n.propertyName}}`},mE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fE,code(n){let{gen:e,schema:t,data:r,it:i}=n;if((0, pE.alwaysValidSchema)(i,t))return;let a=e.name("valid");e.forIn("key",r,s=>{n.setParams({propertyName:s}),n.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:true},a),e.if((0, Dg.not)(a),()=>{n.error(true),i.allErrors||e.break();});}),n.ok(a);}};kc.default=mE;});var Rc=_(Vc=>{Object.defineProperty(Vc,"__esModule",{value:true});var ta=ht(),Ot=k(),gE=ct(),na=q(),yE={message:"must NOT have additional properties",params:({params:n})=>(0, Ot._)`{additionalProperty: ${n.additionalProperty}}`},vE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:yE,code(n){let{gen:e,schema:t,parentSchema:r,data:i,errsCount:a,it:s}=n;if(!a)throw new Error("ajv implementation error");let{allErrors:o,opts:u}=s;if(s.props=true,u.removeAdditional!=="all"&&(0, na.alwaysValidSchema)(s,t))return;let l=(0, ta.allSchemaProperties)(r.properties),c=(0, ta.allSchemaProperties)(r.patternProperties);h(),n.ok((0, Ot._)`${a} === ${gE.default.errors}`);function h(){e.forIn("key",i,b=>{!l.length&&!c.length?g(b):e.if(p(b),()=>g(b));});}function p(b){let C;if(l.length>8){let v=(0, na.schemaRefOrVal)(s,r.properties,"properties");C=(0, ta.isOwnProperty)(e,v,b);}else l.length?C=(0, Ot.or)(...l.map(v=>(0, Ot._)`${b} === ${v}`)):C=Ot.nil;return c.length&&(C=(0, Ot.or)(C,...c.map(v=>(0, Ot._)`${(0, ta.usePattern)(n,v)}.test(${b})`))),(0, Ot.not)(C)}function f(b){e.code((0, Ot._)`delete ${i}[${b}]`);}function g(b){if(u.removeAdditional==="all"||u.removeAdditional&&t===false){f(b);return}if(t===false){n.setParams({additionalProperty:b}),n.error(),o||e.break();return}if(typeof t=="object"&&!(0, na.alwaysValidSchema)(s,t)){let C=e.name("valid");u.removeAdditional==="failing"?(m(b,C,false),e.if((0, Ot.not)(C),()=>{n.reset(),f(b);})):(m(b,C),o||e.if((0, Ot.not)(C),()=>e.break()));}}function m(b,C,v){let d={keyword:"additionalProperties",dataProp:b,dataPropType:na.Type.Str};v===false&&Object.assign(d,{compositeRule:true,createErrors:false,allErrors:false}),n.subschema(d,C);}}};Vc.default=vE;});var xg=_($c=>{Object.defineProperty($c,"__esModule",{value:true});var bE=fr(),Og=ht(),jc=q(),Pg=Rc(),CE={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:e,schema:t,parentSchema:r,data:i,it:a}=n;a.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Pg.default.code(new bE.KeywordCxt(a,Pg.default,"additionalProperties"));let s=(0, Og.allSchemaProperties)(t);for(let h of s)a.definedProperties.add(h);a.opts.unevaluated&&s.length&&a.props!==true&&(a.props=jc.mergeEvaluated.props(e,(0, jc.toHash)(s),a.props));let o=s.filter(h=>!(0, jc.alwaysValidSchema)(a,t[h]));if(o.length===0)return;let u=e.name("valid");for(let h of o)l(h)?c(h):(e.if((0, Og.propertyInData)(e,i,h,a.opts.ownProperties)),c(h),a.allErrors||e.else().var(u,true),e.endIf()),n.it.definedProperties.add(h),n.ok(u);function l(h){return a.opts.useDefaults&&!a.compositeRule&&t[h].default!==void 0}function c(h){n.subschema({keyword:"properties",schemaProp:h,dataProp:h},u);}}};$c.default=CE;});var Ig=_(Lc=>{Object.defineProperty(Lc,"__esModule",{value:true});var Tg=ht(),ra=k(),Ng=q(),Fg=q(),SE={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:e,schema:t,data:r,parentSchema:i,it:a}=n,{opts:s}=a,o=(0, Tg.allSchemaProperties)(t),u=o.filter(m=>(0, Ng.alwaysValidSchema)(a,t[m]));if(o.length===0||u.length===o.length&&(!a.opts.unevaluated||a.props===true))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,c=e.name("valid");a.props!==true&&!(a.props instanceof ra.Name)&&(a.props=(0, Fg.evaluatedPropsToName)(e,a.props));let{props:h}=a;p();function p(){for(let m of o)l&&f(m),a.allErrors?g(m):(e.var(c,true),g(m),e.if(c));}function f(m){for(let b in l)new RegExp(m).test(b)&&(0, Ng.checkStrictMode)(a,`property ${b} matches pattern ${m} (use allowMatchingProperties)`);}function g(m){e.forIn("key",r,b=>{e.if((0, ra._)`${(0, Tg.usePattern)(n,m)}.test(${b})`,()=>{let C=u.includes(m);C||n.subschema({keyword:"patternProperties",schemaProp:m,dataProp:b,dataPropType:Fg.Type.Str},c),a.opts.unevaluated&&h!==true?e.assign((0, ra._)`${h}[${b}]`,true):!C&&!a.allErrors&&e.if((0, ra.not)(c),()=>e.break());});});}}};Lc.default=SE;});var kg=_(qc=>{Object.defineProperty(qc,"__esModule",{value:true});var _E=q(),wE={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(n){let{gen:e,schema:t,it:r}=n;if((0, _E.alwaysValidSchema)(r,t)){n.fail();return}let i=e.name("valid");n.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},i),n.failResult(i,()=>n.reset(),()=>n.error());},error:{message:"must NOT be valid"}};qc.default=wE;});var Vg=_(Bc=>{Object.defineProperty(Bc,"__esModule",{value:true});var EE=ht(),DE={keyword:"anyOf",schemaType:"array",trackErrors:true,code:EE.validateUnion,error:{message:"must match a schema in anyOf"}};Bc.default=DE;});var Rg=_(Wc=>{Object.defineProperty(Wc,"__esModule",{value:true});var ia=k(),AE=q(),OE={message:"must match exactly one schema in oneOf",params:({params:n})=>(0, ia._)`{passingSchemas: ${n.passing}}`},PE={keyword:"oneOf",schemaType:"array",trackErrors:true,error:OE,code(n){let{gen:e,schema:t,parentSchema:r,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&r.discriminator)return;let a=t,s=e.let("valid",false),o=e.let("passing",null),u=e.name("_valid");n.setParams({passing:o}),e.block(l),n.result(s,()=>n.reset(),()=>n.error(true));function l(){a.forEach((c,h)=>{let p;(0, AE.alwaysValidSchema)(i,c)?e.var(u,true):p=n.subschema({keyword:"oneOf",schemaProp:h,compositeRule:true},u),h>0&&e.if((0, ia._)`${u} && ${s}`).assign(s,false).assign(o,(0, ia._)`[${o}, ${h}]`).else(),e.if(u,()=>{e.assign(s,true),e.assign(o,h),p&&n.mergeEvaluated(p,ia.Name);});});}}};Wc.default=PE;});var jg=_(Mc=>{Object.defineProperty(Mc,"__esModule",{value:true});var xE=q(),TE={keyword:"allOf",schemaType:"array",code(n){let{gen:e,schema:t,it:r}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((a,s)=>{if((0, xE.alwaysValidSchema)(r,a))return;let o=n.subschema({keyword:"allOf",schemaProp:s},i);n.ok(i),n.mergeEvaluated(o);});}};Mc.default=TE;});var qg=_(Gc=>{Object.defineProperty(Gc,"__esModule",{value:true});var sa=k(),Lg=q(),NE={message:({params:n})=>(0, sa.str)`must match "${n.ifClause}" schema`,params:({params:n})=>(0, sa._)`{failingKeyword: ${n.ifClause}}`},FE={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:NE,code(n){let{gen:e,parentSchema:t,it:r}=n;t.then===void 0&&t.else===void 0&&(0, Lg.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let i=$g(r,"then"),a=$g(r,"else");if(!i&&!a)return;let s=e.let("valid",true),o=e.name("_valid");if(u(),n.reset(),i&&a){let c=e.let("ifClause");n.setParams({ifClause:c}),e.if(o,l("then",c),l("else",c));}else i?e.if(o,l("then")):e.if((0, sa.not)(o),l("else"));n.pass(s,()=>n.error(true));function u(){let c=n.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},o);n.mergeEvaluated(c);}function l(c,h){return ()=>{let p=n.subschema({keyword:c},o);e.assign(s,o),n.mergeValidEvaluated(p,s),h?e.assign(h,(0, sa._)`${c}`):n.setParams({ifClause:c});}}}};function $g(n,e){let t=n.schema[e];return t!==void 0&&!(0, Lg.alwaysValidSchema)(n,t)}Gc.default=FE;});var Bg=_(Jc=>{Object.defineProperty(Jc,"__esModule",{value:true});var IE=q(),kE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:e,it:t}){e.if===void 0&&(0, IE.checkStrictMode)(t,`"${n}" without "if" is ignored`);}};Jc.default=kE;});var Hc=_(zc=>{Object.defineProperty(zc,"__esModule",{value:true});var VE=Pc(),RE=bg(),jE=xc(),$E=Sg(),LE=_g(),qE=ea(),BE=Ag(),WE=Rc(),ME=xg(),GE=Ig(),JE=kg(),zE=Vg(),HE=Rg(),UE=jg(),KE=qg(),XE=Bg();function YE(n=false){let e=[JE.default,zE.default,HE.default,UE.default,KE.default,XE.default,BE.default,WE.default,qE.default,ME.default,GE.default];return n?e.push(RE.default,$E.default):e.push(VE.default,jE.default),e.push(LE.default),e}zc.default=YE;});var Wg=_(Uc=>{Object.defineProperty(Uc,"__esModule",{value:true});var ye=k(),ZE={message:({schemaCode:n})=>(0, ye.str)`must match format "${n}"`,params:({schemaCode:n})=>(0, ye._)`{format: ${n}}`},QE={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:ZE,code(n,e){let{gen:t,data:r,$data:i,schema:a,schemaCode:s,it:o}=n,{opts:u,errSchemaPath:l,schemaEnv:c,self:h}=o;if(!u.validateFormats)return;i?p():f();function p(){let g=t.scopeValue("formats",{ref:h.formats,code:u.code.formats}),m=t.const("fDef",(0, ye._)`${g}[${s}]`),b=t.let("fType"),C=t.let("format");t.if((0, ye._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(b,(0, ye._)`${m}.type || "string"`).assign(C,(0, ye._)`${m}.validate`),()=>t.assign(b,(0, ye._)`"string"`).assign(C,m)),n.fail$data((0, ye.or)(v(),d()));function v(){return u.strictSchema===false?ye.nil:(0, ye._)`${s} && !${C}`}function d(){let S=c.$async?(0, ye._)`(${m}.async ? await ${C}(${r}) : ${C}(${r}))`:(0, ye._)`${C}(${r})`,y=(0, ye._)`(typeof ${C} == "function" ? ${S} : ${C}.test(${r}))`;return (0, ye._)`${C} && ${C} !== true && ${b} === ${e} && !${y}`}}function f(){let g=h.formats[a];if(!g){v();return}if(g===true)return;let[m,b,C]=d(g);m===e&&n.pass(S());function v(){if(u.strictSchema===false){h.logger.warn(y());return}throw new Error(y());function y(){return `unknown format "${a}" ignored in schema at path "${l}"`}}function d(y){let w=y instanceof RegExp?(0, ye.regexpCode)(y):u.code.formats?(0, ye._)`${u.code.formats}${(0, ye.getProperty)(a)}`:void 0,E=t.scopeValue("formats",{key:a,ref:y,code:w});return typeof y=="object"&&!(y instanceof RegExp)?[y.type||"string",y.validate,(0, ye._)`${E}.validate`]:["string",y,E]}function S(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!c.$async)throw new Error("async format in sync schema");return (0, ye._)`await ${C}(${r})`}return typeof b=="function"?(0, ye._)`${C}(${r})`:(0, ye._)`${C}.test(${r})`}}}};Uc.default=QE;});var Xc=_(Kc=>{Object.defineProperty(Kc,"__esModule",{value:true});var eD=Wg(),tD=[eD.default];Kc.default=tD;});var Yc=_(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.contentVocabulary=Cr.metadataVocabulary=void 0;Cr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Cr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];});var Gg=_(Zc=>{Object.defineProperty(Zc,"__esModule",{value:true});var nD=cc(),rD=Ac(),iD=Hc(),sD=Xc(),Mg=Yc(),aD=[nD.default,rD.default,(0, iD.default)(),sD.default,Mg.metadataVocabulary,Mg.contentVocabulary];Zc.default=aD;});var zg=_(aa=>{Object.defineProperty(aa,"__esModule",{value:true});aa.DiscrError=void 0;var Jg;(function(n){n.Tag="tag",n.Mapping="mapping";})(Jg||(aa.DiscrError=Jg={}));});var th=_(eh=>{Object.defineProperty(eh,"__esModule",{value:true});var Sr=k(),Qc=zg(),Hg=yi(),oD=mr(),uD=q(),lD={message:({params:{discrError:n,tagName:e}})=>n===Qc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:n,tag:e,tagName:t}})=>(0, Sr._)`{error: ${n}, tag: ${t}, tagValue: ${e}}`},cD={keyword:"discriminator",type:"object",schemaType:"object",error:lD,code(n){let{gen:e,data:t,schema:r,parentSchema:i,it:a}=n,{oneOf:s}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let o=r.propertyName;if(typeof o!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let u=e.let("valid",false),l=e.const("tag",(0, Sr._)`${t}${(0, Sr.getProperty)(o)}`);e.if((0, Sr._)`typeof ${l} == "string"`,()=>c(),()=>n.error(false,{discrError:Qc.DiscrError.Tag,tag:l,tagName:o})),n.ok(u);function c(){let f=p();e.if(false);for(let g in f)e.elseIf((0, Sr._)`${l} === ${g}`),e.assign(u,h(f[g]));e.else(),n.error(false,{discrError:Qc.DiscrError.Mapping,tag:l,tagName:o}),e.endIf();}function h(f){let g=e.name("valid"),m=n.subschema({keyword:"oneOf",schemaProp:f},g);return n.mergeEvaluated(m,Sr.Name),g}function p(){var f;let g={},m=C(i),b=true;for(let S=0;S<s.length;S++){let y=s[S];if(y?.$ref&&!(0, uD.schemaHasRulesButRef)(y,a.self.RULES)){let E=y.$ref;if(y=Hg.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,E),y instanceof Hg.SchemaEnv&&(y=y.schema),y===void 0)throw new oD.default(a.opts.uriResolver,a.baseId,E)}let w=(f=y?.properties)===null||f===void 0?void 0:f[o];if(typeof w!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);b=b&&(m||C(y)),v(w,S);}if(!b)throw new Error(`discriminator: "${o}" must be required`);return g;function C({required:S}){return Array.isArray(S)&&S.includes(o)}function v(S,y){if(S.const)d(S.const,y);else if(S.enum)for(let w of S.enum)d(w,y);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function d(S,y){if(typeof S!="string"||S in g)throw new Error(`discriminator: "${o}" values must be unique strings`);g[S]=y;}}}};eh.default=cD;});var Ug=_((ZI,hD)=>{hD.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true};});var Xg=_((ce,nh)=>{Object.defineProperty(ce,"__esModule",{value:true});ce.MissingRefError=ce.ValidationError=ce.CodeGen=ce.Name=ce.nil=ce.stringify=ce.str=ce._=ce.KeywordCxt=ce.Ajv=void 0;var dD=oc(),pD=Gg(),fD=th(),Kg=Ug(),mD=["/properties"],oa="http://json-schema.org/draft-07/schema",_r=class extends dD.default{_addVocabularies(){super._addVocabularies(),pD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(fD.default);}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Kg,mD):Kg;this.addMetaSchema(e,oa,false),this.refs["http://json-schema.org/schema"]=oa;}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(oa)?oa:void 0)}};ce.Ajv=_r;nh.exports=ce=_r;nh.exports.Ajv=_r;Object.defineProperty(ce,"__esModule",{value:true});ce.default=_r;var gD=fr();Object.defineProperty(ce,"KeywordCxt",{enumerable:true,get:function(){return gD.KeywordCxt}});var wr=k();Object.defineProperty(ce,"_",{enumerable:true,get:function(){return wr._}});Object.defineProperty(ce,"str",{enumerable:true,get:function(){return wr.str}});Object.defineProperty(ce,"stringify",{enumerable:true,get:function(){return wr.stringify}});Object.defineProperty(ce,"nil",{enumerable:true,get:function(){return wr.nil}});Object.defineProperty(ce,"Name",{enumerable:true,get:function(){return wr.Name}});Object.defineProperty(ce,"CodeGen",{enumerable:true,get:function(){return wr.CodeGen}});var yD=gi();Object.defineProperty(ce,"ValidationError",{enumerable:true,get:function(){return yD.default}});var vD=mr();Object.defineProperty(ce,"MissingRefError",{enumerable:true,get:function(){return vD.default}});});var ih=_(Fi=>{Object.defineProperty(Fi,"__esModule",{value:true});Fi.dynamicAnchor=void 0;var rh=k(),bD=ct(),Yg=yi(),CD=Us(),SD={keyword:"$dynamicAnchor",schemaType:"string",code:n=>Zg(n,n.schema)};function Zg(n,e){let{gen:t,it:r}=n;r.schemaEnv.root.dynamicAnchors[e]=true;let i=(0, rh._)`${bD.default.dynamicAnchors}${(0, rh.getProperty)(e)}`,a=r.errSchemaPath==="#"?r.validateName:_D(n);t.if((0, rh._)`!${i}`,()=>t.assign(i,a));}Fi.dynamicAnchor=Zg;function _D(n){let{schemaEnv:e,schema:t,self:r}=n.it,{root:i,baseId:a,localRefs:s,meta:o}=e.root,{schemaId:u}=r.opts,l=new Yg.SchemaEnv({schema:t,schemaId:u,root:i,baseId:a,localRefs:s,meta:o});return Yg.compileSchema.call(r,l),(0, CD.getValidate)(n,l)}Fi.default=SD;});var sh=_(Ii=>{Object.defineProperty(Ii,"__esModule",{value:true});Ii.dynamicRef=void 0;var Qg=k(),wD=ct(),ey=Us(),ED={keyword:"$dynamicRef",schemaType:"string",code:n=>ty(n,n.schema)};function ty(n,e){let{gen:t,keyword:r,it:i}=n;if(e[0]!=="#")throw new Error(`"${r}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)s();else {let u=t.let("valid",false);s(u),n.ok(u);}function s(u){if(i.schemaEnv.root.dynamicAnchors[a]){let l=t.let("_v",(0, Qg._)`${wD.default.dynamicAnchors}${(0, Qg.getProperty)(a)}`);t.if(l,o(l,u),o(i.validateName,u));}else o(i.validateName,u)();}function o(u,l){return l?()=>t.block(()=>{(0, ey.callRef)(n,u),t.let(l,true);}):()=>(0, ey.callRef)(n,u)}}Ii.dynamicRef=ty;Ii.default=ED;});var ny=_(ah=>{Object.defineProperty(ah,"__esModule",{value:true});var DD=ih(),AD=q(),OD={keyword:"$recursiveAnchor",schemaType:"boolean",code(n){n.schema?(0, DD.dynamicAnchor)(n,""):(0, AD.checkStrictMode)(n.it,"$recursiveAnchor: false is ignored");}};ah.default=OD;});var ry=_(oh=>{Object.defineProperty(oh,"__esModule",{value:true});var PD=sh(),xD={keyword:"$recursiveRef",schemaType:"string",code:n=>(0, PD.dynamicRef)(n,n.schema)};oh.default=xD;});var iy=_(uh=>{Object.defineProperty(uh,"__esModule",{value:true});var TD=ih(),ND=sh(),FD=ny(),ID=ry(),kD=[TD.default,ND.default,FD.default,ID.default];uh.default=kD;});var ay=_(lh=>{Object.defineProperty(lh,"__esModule",{value:true});var sy=ea(),VD={keyword:"dependentRequired",type:"object",schemaType:"object",error:sy.error,code:n=>(0, sy.validatePropertyDeps)(n)};lh.default=VD;});var oy=_(ch=>{Object.defineProperty(ch,"__esModule",{value:true});var RD=ea(),jD={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0, RD.validateSchemaDeps)(n)};ch.default=jD;});var uy=_(hh=>{Object.defineProperty(hh,"__esModule",{value:true});var $D=q(),LD={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:e,it:t}){e.contains===void 0&&(0, $D.checkStrictMode)(t,`"${n}" without "contains" is ignored`);}};hh.default=LD;});var ly=_(dh=>{Object.defineProperty(dh,"__esModule",{value:true});var qD=ay(),BD=oy(),WD=uy(),MD=[qD.default,BD.default,WD.default];dh.default=MD;});var hy=_(ph=>{Object.defineProperty(ph,"__esModule",{value:true});var gn=k(),cy=q(),GD=ct(),JD={message:"must NOT have unevaluated properties",params:({params:n})=>(0, gn._)`{unevaluatedProperty: ${n.unevaluatedProperty}}`},zD={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:true,error:JD,code(n){let{gen:e,schema:t,data:r,errsCount:i,it:a}=n;if(!i)throw new Error("ajv implementation error");let{allErrors:s,props:o}=a;o instanceof gn.Name?e.if((0, gn._)`${o} !== true`,()=>e.forIn("key",r,h=>e.if(l(o,h),()=>u(h)))):o!==true&&e.forIn("key",r,h=>o===void 0?u(h):e.if(c(o,h),()=>u(h))),a.props=true,n.ok((0, gn._)`${i} === ${GD.default.errors}`);function u(h){if(t===false){n.setParams({unevaluatedProperty:h}),n.error(),s||e.break();return}if(!(0, cy.alwaysValidSchema)(a,t)){let p=e.name("valid");n.subschema({keyword:"unevaluatedProperties",dataProp:h,dataPropType:cy.Type.Str},p),s||e.if((0, gn.not)(p),()=>e.break());}}function l(h,p){return (0, gn._)`!${h} || !${h}[${p}]`}function c(h,p){let f=[];for(let g in h)h[g]===true&&f.push((0, gn._)`${p} !== ${g}`);return (0, gn.and)(...f)}}};ph.default=zD;});var py=_(fh=>{Object.defineProperty(fh,"__esModule",{value:true});var Gn=k(),dy=q(),HD={message:({params:{len:n}})=>(0, Gn.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, Gn._)`{limit: ${n}}`},UD={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:HD,code(n){let{gen:e,schema:t,data:r,it:i}=n,a=i.items||0;if(a===true)return;let s=e.const("len",(0, Gn._)`${r}.length`);if(t===false)n.setParams({len:a}),n.fail((0, Gn._)`${s} > ${a}`);else if(typeof t=="object"&&!(0, dy.alwaysValidSchema)(i,t)){let u=e.var("valid",(0, Gn._)`${s} <= ${a}`);e.if((0, Gn.not)(u),()=>o(u,a)),n.ok(u);}i.items=true;function o(u,l){e.forRange("i",l,s,c=>{n.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:dy.Type.Num},u),i.allErrors||e.if((0, Gn.not)(u),()=>e.break());});}}};fh.default=UD;});var fy=_(mh=>{Object.defineProperty(mh,"__esModule",{value:true});var KD=hy(),XD=py(),YD=[KD.default,XD.default];mh.default=YD;});var gy=_(gh=>{Object.defineProperty(gh,"__esModule",{value:true});var ZD=cc(),QD=Ac(),eA=Hc(),tA=iy(),nA=ly(),rA=fy(),iA=Xc(),my=Yc(),sA=[tA.default,ZD.default,QD.default,(0, eA.default)(true),iA.default,my.metadataVocabulary,my.contentVocabulary,nA.default,rA.default];gh.default=sA;});var yy=_((dk,aA)=>{aA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:true,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:true,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:true},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:true}}};});var vy=_((pk,oA)=>{oA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":true},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}};});var by=_((fk,uA)=>{uA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}};});var Cy=_((mk,lA)=>{lA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}};});var Sy=_((gk,cA)=>{cA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}};});var _y=_((yk,hA)=>{hA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}};});var wy=_((vk,dA)=>{dA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:true,deprecated:{type:"boolean",default:false},readOnly:{type:"boolean",default:false},writeOnly:{type:"boolean",default:false},examples:{type:"array",items:true}}};});var Ey=_((bk,pA)=>{pA.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":true},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:true}]},const:true,enum:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}}};});var Dy=_(yh=>{Object.defineProperty(yh,"__esModule",{value:true});var fA=yy(),mA=vy(),gA=by(),yA=Cy(),vA=Sy(),bA=_y(),CA=wy(),SA=Ey(),_A=["/properties"];function wA(n){return [fA,mA,gA,yA,vA,e(this,bA),CA,e(this,SA)].forEach(t=>this.addMetaSchema(t,void 0,false)),this;function e(t,r){return n?t.$dataMetaSchema(r,_A):r}}yh.default=wA;});var Ay=_((he,bh)=>{Object.defineProperty(he,"__esModule",{value:true});he.MissingRefError=he.ValidationError=he.CodeGen=he.Name=he.nil=he.stringify=he.str=he._=he.KeywordCxt=he.Ajv2020=void 0;var EA=oc(),DA=gy(),AA=th(),OA=Dy(),vh="https://json-schema.org/draft/2020-12/schema",Er=class extends EA.default{constructor(e={}){super({...e,dynamicRef:true,next:true,unevaluated:true});}_addVocabularies(){super._addVocabularies(),DA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(AA.default);}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(OA.default.call(this,e),this.refs["http://json-schema.org/schema"]=vh);}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(vh)?vh:void 0)}};he.Ajv2020=Er;bh.exports=he=Er;bh.exports.Ajv2020=Er;Object.defineProperty(he,"__esModule",{value:true});he.default=Er;var PA=fr();Object.defineProperty(he,"KeywordCxt",{enumerable:true,get:function(){return PA.KeywordCxt}});var Dr=k();Object.defineProperty(he,"_",{enumerable:true,get:function(){return Dr._}});Object.defineProperty(he,"str",{enumerable:true,get:function(){return Dr.str}});Object.defineProperty(he,"stringify",{enumerable:true,get:function(){return Dr.stringify}});Object.defineProperty(he,"nil",{enumerable:true,get:function(){return Dr.nil}});Object.defineProperty(he,"Name",{enumerable:true,get:function(){return Dr.Name}});Object.defineProperty(he,"CodeGen",{enumerable:true,get:function(){return Dr.CodeGen}});var xA=gi();Object.defineProperty(he,"ValidationError",{enumerable:true,get:function(){return xA.default}});var TA=mr();Object.defineProperty(he,"MissingRefError",{enumerable:true,get:function(){return TA.default}});});var Sh=_(ua=>{Object.defineProperty(ua,"__esModule",{value:true});ua.CompilerOptions=void 0;var Ch=class{constructor(e=null,t=[],r=false,i=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=r,this.errorHandler=i,this.fileHandler=a;}};ua.CompilerOptions=Ch;});var Oy=_(la=>{Object.defineProperty(la,"__esModule",{value:true});la.DebugSourceRange=void 0;var _h=class{constructor(e,t,r){this.length=e,this.debugMetadata=t,this.text=r;}};la.DebugSourceRange=_h;});var Ar=_(ca=>{Object.defineProperty(ca,"__esModule",{value:true});ca.ErrorType=void 0;var Py;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(Py||(ca.ErrorType=Py={}));});var xy=_(ha=>{Object.defineProperty(ha,"__esModule",{value:true});ha.Argument=void 0;var wh=class{constructor(e=null,t=null,r=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=r;}get typeName(){return "Argument"}};ha.Argument=wh;});var re=_(Ee=>{Object.defineProperty(Ee,"__esModule",{value:true});Ee.filterUndef=Ee.isEquatable=Ee.nullIfUndefined=Ee.asINamedContentOrNull=Ee.asBooleanOrThrows=Ee.asNumberOrThrows=Ee.asOrThrows=Ee.asOrNull=void 0;function NA(n,e){return n instanceof e?Ty(n):null}Ee.asOrNull=NA;function FA(n,e){if(n instanceof e)return Ty(n);throw new Error(`${n} is not of type ${e}`)}Ee.asOrThrows=FA;function IA(n){if(typeof n=="number")return n;throw new Error(`${n} is not a number`)}Ee.asNumberOrThrows=IA;function kA(n){if(typeof n=="boolean")return n;throw new Error(`${n} is not a boolean`)}Ee.asBooleanOrThrows=kA;function VA(n){return n.hasValidName&&n.name?n:null}Ee.asINamedContentOrNull=VA;function RA(n){return typeof n>"u"?null:n}Ee.nullIfUndefined=RA;function jA(n){return typeof n=="object"&&typeof n.Equals=="function"}Ee.isEquatable=jA;function Ty(n,e){return n}function $A(n){return n!=null}Ee.filterUndef=$A;});var pe=_(da=>{Object.defineProperty(da,"__esModule",{value:true});da.ParsedObject=void 0;var Ny=re(),Eh=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let r of t)r.hasOwnProperty("parent")&&(r.parent=this),this.content.push(r);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let r=(0, Ny.asOrNull)(this,e);if(r!==null&&(t===null||t(r)===true))return r;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,r)=>{let i=Array.isArray(r)?r:[],a=(0, Ny.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&i.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,r=false){if(t===null&&(t=this),!(t._alreadyHadError&&!r||t._alreadyHadWarning&&r)){if(this.parent)this.parent.Error(e,t,r);else throw new Error(`No parent object to send error to: ${e}`);r?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};da.ParsedObject=Eh;});var fa=_(pa=>{Object.defineProperty(pa,"__esModule",{value:true});pa.AuthorWarning=void 0;var LA=pe(),Dh=class extends LA.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};pa.AuthorWarning=Dh;});var Qe=_(ki=>{Object.defineProperty(ki,"__esModule",{value:true});ki.Path=void 0;var Or=class n{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof n.Component&&arguments[1]instanceof n){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new n(e)}else return n.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new n;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new n,r=0;for(let i=0;i<e._components.length&&e._components[i].isParent;++i)r++;for(let i=0;i<this._components.length-r;++i)t._components.push(this._components[i]);for(let i=r;i<e._components.length;++i)t._components.push(e._components[i]);return t}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let t=this._componentsString.split(".");for(let r of t)/^(\-|\+)?([0-9]+|Infinity)$/.test(r)?this._components.push(new n.Component(parseInt(r))):this._components.push(new n.Component(r));}toString(){return this.componentsString}Equals(e){if(e==null||e._components.length!=this._components.length||e.isRelative!=this.isRelative)return false;for(let t=0,r=e._components.length;t<r;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new n;return t._components.push(...this._components),t._components.push(e),t}};ki.Path=Or;Or.parentId="^";(function(n){class e{constructor(r){this.index=-1,this.name=null,typeof r=="string"?this.name=r:this.index=r;}get isIndex(){return this.index>=0}get isParent(){return this.name==n.parentId}static ToParent(){return new e(n.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(r){return r!=null&&r.isIndex==this.isIndex?this.isIndex?this.index==r.index:this.name==r.name:false}}n.Component=e;})(Or||(ki.Path=Or={}));});var Vi=_(ma=>{Object.defineProperty(ma,"__esModule",{value:true});ma.Debug=void 0;var Fy;(function(n){function e(r,i,a){t(r instanceof i,a);}n.AssertType=e;function t(r,i){if(!r)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}n.Assert=t;})(Fy||(ma.Debug=Fy={}));});var Ve=_(Pr=>{Object.defineProperty(Pr,"__esModule",{value:true});Pr.throwNullException=Pr.NullException=void 0;var ga=class extends Error{};Pr.NullException=ga;function qA(n){throw new ga(`${n} is null or undefined`)}Pr.throwNullException=qA;});var et=_(va=>{Object.defineProperty(va,"__esModule",{value:true});va.InkObject=void 0;var xr=Qe(),Ri=ve(),Ah=Vi(),Tr=re(),ya=Ve(),Oh=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let r=t.ContentAtPath(e).obj;if(r){let i=r.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new xr.Path;else {let e=[],t=this,r=(0, Tr.asOrNull)(t.parent,Ri.Container);for(;r!==null;){let i=(0, Tr.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, ya.throwNullException)("namedChild.name");e.unshift(new xr.Path.Component(i.name));}else e.unshift(new xr.Path.Component(r.content.indexOf(t)));t=r,r=(0, Tr.asOrNull)(r.parent,Ri.Container);}this._path=new xr.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, ya.throwNullException)("path");if(e.isRelative){let t=(0, Tr.asOrNull)(this,Ri.Container);return t===null&&(Ah.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, Tr.asOrNull)(this.parent,Ri.Container),Ah.Debug.Assert(t!==null,"Expected parent to be a container"),Ah.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, ya.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, ya.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,r=Math.min(e.length,t.length),i=-1;for(let u=0;u<r;++u){let l=t.GetComponent(u),c=e.GetComponent(u);if(l.Equals(c))i=u;else break}if(i==-1)return e;let a=t.componentCount-1-i,s=[];for(let u=0;u<a;++u)s.push(xr.Path.Component.ToParent());for(let u=i+1;u<e.componentCount;++u)s.push(e.GetComponent(u));return new xr.Path(s,true)}CompactPathString(e){let t=null,r=null;return e.isRelative?(r=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(r=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),r.length<t.length?r:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, Tr.asOrNull)(e,Ri.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,r){e[t]&&(e[t]=null),e[t]=r,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};va.InkObject=Oh;});var Jn=_(ba=>{Object.defineProperty(ba,"__esModule",{value:true});ba.StringBuilder=void 0;var Ph=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=`
9
+ `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(r,i)=>typeof t[i]<"u"?t[i]:r);}toString(){return this.string}Clear(){this.string="";}};ba.StringBuilder=Ph;});var nt=_(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.InkList=Nr.InkListItem=void 0;var Rt=Ve(),BA=Jn(),tt=class n{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new n(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(e){if(e instanceof n){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new n(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!n.isLikeInkListItem(t))return n.Null;let r=t;return new n(r.originName,r.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};Nr.InkListItem=tt;var xh=class n extends Map{constructor(){if(super(arguments[0]instanceof n?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof n){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, Rt.throwNullException)("originStory.listDefinitions");let r=t.listDefinitions.TryListGetDefinition(e,null);if(r.exists){if(r.result===null)return (0, Rt.throwNullException)("def.result");this.origins=[r.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var r;if(e==null||e=="")return new n;let i=(r=t.listDefinitions)===null||r===void 0?void 0:r.FindSingleItemListWithName(e);if(i)return i.value===null?(0, Rt.throwNullException)("listValue.value"):new n(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof tt){let r=e;if(r.originName==null){this.AddItem(r.itemName);return}if(this.origins===null)return (0, Rt.throwNullException)("this.origins");for(let i of this.origins)if(i.name==r.originName){let a=i.TryGetValueForItem(r,0);if(a.exists){this.Add(r,a.result);return}else throw new Error("Could not add the item "+r+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let r=e,i=null;if(this.origins===null)return (0, Rt.throwNullException)("this.origins");for(let a of this.origins){if(r===null)return (0, Rt.throwNullException)("itemName");if(a.ContainsItemWithName(r)){if(i!=null)throw new Error("Could not add the item "+r+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+r+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=n.FromString(r,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new tt(i.name,r),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(tt.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let r=e.serialized();if(this.has(r))throw new Error(`The Map already contains an entry for ${e}`);this.set(r,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(r=>r.name==e?(t=r,false):true),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=tt.fromSerializedKey(e);if(t.originName===null)return (0, Rt.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:tt.Null,Value:0};for(let[t,r]of this){let i=tt.fromSerializedKey(t);(e.Key.isNull||r>e.Value)&&(e={Key:i,Value:r});}return e}get minItem(){let e={Key:tt.Null,Value:0};for(let[t,r]of this){let i=tt.fromSerializedKey(t);(e.Key.isNull||r<e.Value)&&(e={Key:i,Value:r});}return e}get inverse(){let e=new n;if(this.origins!=null)for(let t of this.origins)for(let[r,i]of t.items){let a=tt.fromSerializedKey(r);this.ContainsKey(a)||e.Add(a,i);}return e}get all(){let e=new n;if(this.origins!=null)for(let t of this.origins)for(let[r,i]of t.items){let a=tt.fromSerializedKey(r);e.set(a.serialized(),i);}return e}Union(e){let t=new n(this);for(let[r,i]of e)t.set(r,i);return t}Intersect(e){let t=new n;for(let[r,i]of this)e.has(r)&&t.set(r,i);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new n(this);for(let[r]of e)t.delete(r);return t}Contains(e){if(typeof e=="string")return this.ContainsItemNamed(e);let t=e;if(t.size==0||this.size==0)return false;for(let[r]of t)if(!this.has(r))return false;return true}GreaterThan(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>e.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<e.minItem.Value}LessThanOrEquals(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<=e.maxItem.Value&&this.minItem.Value<=e.minItem.Value}MaxAsList(){return this.Count>0?new n(this.maxItem):new n}MinAsList(){return this.Count>0?new n(this.minItem):new n}ListWithSubRange(e,t){if(this.Count==0)return new n;let r=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof n&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof n&&t.Count>0&&(a=t.maxItem.Value);let s=new n;s.SetInitialOriginNames(this.originNames);for(let o of r)o.Value>=i&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(e){if(!(e instanceof n)||e.Count!=this.Count)return false;for(let[t]of this)if(!e.has(t))return false;return true}get orderedItems(){let e=new Array;for(let[t,r]of this){let i=tt.fromSerializedKey(t);e.push({Key:i,Value:r});}return e.sort((t,r)=>t.Key.originName===null?(0, Rt.throwNullException)("x.Key.originName"):r.Key.originName===null?(0, Rt.throwNullException)("y.Key.originName"):t.Value==r.Value?t.Key.originName.localeCompare(r.Key.originName):t.Value<r.Value?-1:t.Value>r.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new BA.StringBuilder;for(let r=0;r<e.length;r++){r>0&&t.Append(", ");let i=e[r].Key;if(i.itemName===null)return (0, Rt.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};Nr.InkList=xh;});var ji=_(Ca=>{Object.defineProperty(Ca,"__esModule",{value:true});Ca.StoryException=void 0;var Th=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};Ca.StoryException=Th;});var Fr=_(yn=>{Object.defineProperty(yn,"__esModule",{value:true});yn.tryParseFloat=yn.tryParseInt=yn.tryGetValueFromMap=void 0;function WA(n,e,t){if(n===null)return {result:t,exists:false};let r=n.get(e);return typeof r>"u"?{result:t,exists:false}:{result:r,exists:true}}yn.tryGetValueFromMap=WA;function MA(n,e=0){let t=parseInt(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}yn.tryParseInt=MA;function GA(n,e=0){let t=parseFloat(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}yn.tryParseFloat=GA;});var fe=_(me=>{Object.defineProperty(me,"__esModule",{value:true});me.ValueType=me.ListValue=me.VariablePointerValue=me.DivertTargetValue=me.StringValue=me.FloatValue=me.IntValue=me.BoolValue=me.Value=me.AbstractValue=void 0;var Iy=et(),ky=Qe(),zn=nt(),JA=ji(),$i=re(),Vy=Fr(),ft=Ve(),Sa=class n extends Iy.InkObject{static Create(e,t){if(t){if(t===de.Int&&Number.isInteger(Number(e)))return new $t(Number(e));if(t===de.Float&&!isNaN(e))return new Lt(Number(e))}if(typeof e=="boolean")return new Ir(!!e);if(typeof e=="string")return new en(String(e));if(Number.isInteger(Number(e)))return new $t(Number(e));if(isNaN(e)){if(e instanceof ky.Path)return new _a((0, $i.asOrThrows)(e,ky.Path));if(e instanceof zn.InkList)return new wa((0, $i.asOrThrows)(e,zn.InkList))}else return new Lt(Number(e));return null}Copy(){return (0, $i.asOrThrows)(n.Create(this.valueObject),Iy.InkObject)}BadCastException(e){return new JA.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};me.AbstractValue=Sa;var jt=class extends Sa{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, ft.throwNullException)("Value.value"):this.value.toString()}};me.Value=jt;var Ir=class extends jt{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return de.Bool}Cast(e){if(this.value===null)return (0, ft.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==de.Int)return new $t(this.value?1:0);if(e==de.Float)return new Lt(this.value?1:0);if(e==de.String)return new en(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};me.BoolValue=Ir;var $t=class extends jt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return de.Int}Cast(e){if(this.value===null)return (0, ft.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==de.Bool)return new Ir(this.value!==0);if(e==de.Float)return new Lt(this.value);if(e==de.String)return new en(""+this.value);throw this.BadCastException(e)}};me.IntValue=$t;var Lt=class extends jt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return de.Float}Cast(e){if(this.value===null)return (0, ft.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==de.Bool)return new Ir(this.value!==0);if(e==de.Int)return new $t(this.value);if(e==de.String)return new en(""+this.value);throw this.BadCastException(e)}};me.FloatValue=Lt;var en=class extends jt{constructor(e){if(super(e||""),this._isNewline=this.value==`
10
+ `,this._isInlineWhitespace=true,this.value===null)return (0, ft.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return de.String}get isTruthy(){return this.value===null?(0, ft.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==de.Int){let t=(0, Vy.tryParseInt)(this.value);if(t.exists)return new $t(t.result);throw this.BadCastException(e)}if(e==de.Float){let t=(0, Vy.tryParseFloat)(this.value);if(t.exists)return new Lt(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};me.StringValue=en;var _a=class extends jt{constructor(e=null){super(e);}get valueType(){return de.DivertTarget}get targetPath(){return this.value===null?(0, ft.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};me.DivertTargetValue=_a;var Nh=class n extends jt{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, ft.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return de.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new n(this.variableName,this.contextIndex)}};me.VariablePointerValue=Nh;var wa=class n extends jt{get isTruthy(){return this.value===null?(0, ft.throwNullException)("this.value"):this.value.Count>0}get valueType(){return de.List}Cast(e){if(this.value===null)return (0, ft.throwNullException)("Value.value");if(e==de.Int){let t=this.value.maxItem;return t.Key.isNull?new $t(0):new $t(t.Value)}else if(e==de.Float){let t=this.value.maxItem;return t.Key.isNull?new Lt(0):new Lt(t.Value)}else if(e==de.String){let t=this.value.maxItem;return t.Key.isNull?new en(""):new en(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new zn.InkList:e instanceof zn.InkList?this.value=new zn.InkList(e):e instanceof zn.InkListItem&&typeof t=="number"&&(this.value=new zn.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let r=(0, $i.asOrNull)(e,n),i=(0, $i.asOrNull)(t,n);if(i&&i.value===null)return (0, ft.throwNullException)("newList.value");if(r&&r.value===null)return (0, ft.throwNullException)("oldList.value");r&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}};me.ListValue=wa;var de;(function(n){n[n.Bool=-1]="Bool",n[n.Int=0]="Int",n[n.Float=1]="Float",n[n.List=2]="List",n[n.String=3]="String",n[n.DivertTarget=4]="DivertTarget",n[n.VariablePointer=5]="VariablePointer";})(de||(me.ValueType=de={}));});var Ry=_(Ea=>{Object.defineProperty(Ea,"__esModule",{value:true});Ea.SearchResult=void 0;var zA=ve(),Fh=class n{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof zA.Container?this.obj:null}copy(){let e=new n;return e.obj=this.obj,e.approximate=this.approximate,e}};Ea.SearchResult=Fh;});var ve=_(qi=>{Object.defineProperty(qi,"__esModule",{value:true});qi.Container=void 0;var HA=fe(),jy=Ve(),UA=Jn(),kr=et(),KA=Ry(),$y=Qe(),Ly=Vi(),XA=Fr(),vn=re(),Li=class n extends kr.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,r]of this.namedContent){let i=(0, vn.asOrThrows)(r,kr.InkObject);e.set(t,i);}for(let t of this.content){let r=(0, vn.asINamedContentOrNull)(t);r!=null&&r.hasValidName&&e.delete(r.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[r]of t)this.namedContent.delete(r);if(e!=null)for(let[,r]of e){let i=(0, vn.asINamedContentOrNull)(r);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=n.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=n.CountFlags.Turns),this.countingAtStartOnly&&(e|=n.CountFlags.CountStartOnly),e==n.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&n.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&n.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&n.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof n;)t.content.length>0&&(e.push(new $y.Path.Component(0)),t=t.content[0]);return new $y.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let r of t)this.AddContent(r);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, vn.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Ly.Debug.AssertType(e,kr.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, vn.asOrThrows)(e,kr.InkObject);if(t.parent=this,e.name===null)return (0, jy.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,r=-1){r==-1&&(r=e.length);let i=new KA.SearchResult;i.approximate=false;let a=this,s=this;for(let o=t;o<r;++o){let u=e.GetComponent(o);if(a==null){i.approximate=true;break}let l=a.ContentWithPathComponent(u);if(l==null){i.approximate=true;break}let c=(0, vn.asOrNull)(l,n);if(o<r-1&&c==null){i.approximate=true;break}s=l,a=c;}return i.obj=s,i}InsertContent(e,t){if(this.content.splice(t,0,e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}AddContentsOfContainer(e){this.content.push(...e.content);for(let t of e.content)t.parent=this,this.TryAddNamedContent(t);}ContentWithPathComponent(e){if(e.isIndex)return e.index>=0&&e.index<this.content.length?this.content[e.index]:null;if(e.isParent)return this.parent;{if(e.name===null)return (0, jy.throwNullException)("component.name");let t=(0, XA.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, vn.asOrThrows)(t.result,kr.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new UA.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],r=arguments[2];function i(){for(let o=0;o<4*t;++o)e.Append(" ");}i(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==r&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof n?o.BuildStringOfHierarchy(e,t,r):(i(),o instanceof HA.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
11
+ `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof n)&&o==r&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, vn.asOrThrows)(o,kr.InkObject))>=0||a.set(s,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,s]of a)Ly.Debug.AssertType(s,n,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,r),e.AppendLine();}t--,i(),e.Append("]");}};qi.Container=Li;(function(n){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(n.CountFlags||(n.CountFlags={}));})(Li||(qi.Container=Li={}));});var Re=_(Wi=>{Object.defineProperty(Wi,"__esModule",{value:true});Wi.ControlCommand=void 0;var YA=et(),Bi=class n extends YA.InkObject{get commandType(){return this._commandType}constructor(e=n.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new n(this.commandType)}static EvalStart(){return new n(n.CommandType.EvalStart)}static EvalOutput(){return new n(n.CommandType.EvalOutput)}static EvalEnd(){return new n(n.CommandType.EvalEnd)}static Duplicate(){return new n(n.CommandType.Duplicate)}static PopEvaluatedValue(){return new n(n.CommandType.PopEvaluatedValue)}static PopFunction(){return new n(n.CommandType.PopFunction)}static PopTunnel(){return new n(n.CommandType.PopTunnel)}static BeginString(){return new n(n.CommandType.BeginString)}static EndString(){return new n(n.CommandType.EndString)}static NoOp(){return new n(n.CommandType.NoOp)}static ChoiceCount(){return new n(n.CommandType.ChoiceCount)}static Turns(){return new n(n.CommandType.Turns)}static TurnsSince(){return new n(n.CommandType.TurnsSince)}static ReadCount(){return new n(n.CommandType.ReadCount)}static Random(){return new n(n.CommandType.Random)}static SeedRandom(){return new n(n.CommandType.SeedRandom)}static VisitIndex(){return new n(n.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new n(n.CommandType.SequenceShuffleIndex)}static StartThread(){return new n(n.CommandType.StartThread)}static Done(){return new n(n.CommandType.Done)}static End(){return new n(n.CommandType.End)}static ListFromInt(){return new n(n.CommandType.ListFromInt)}static ListRange(){return new n(n.CommandType.ListRange)}static ListRandom(){return new n(n.CommandType.ListRandom)}static BeginTag(){return new n(n.CommandType.BeginTag)}static EndTag(){return new n(n.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};Wi.ControlCommand=Bi;(function(n){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(n.CommandType||(n.CommandType={}));})(Bi||(Wi.ControlCommand=Bi={}));});var mt=_(Da=>{Object.defineProperty(Da,"__esModule",{value:true});Da.Expression=void 0;var qy=ve(),Ih=Re(),ZA=pe(),kh=class extends ZA.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new qy.Container;return e.AddContent(Ih.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(Ih.ControlCommand.EvalOutput()),e.AddContent(Ih.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new qy.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let r=t.Copy();r&&e.AddContent(r);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};Da.Expression=kh;});var Hn=_(Aa=>{Object.defineProperty(Aa,"__esModule",{value:true});Aa.Void=void 0;var QA=et(),Vh=class extends QA.InkObject{toString(){return "Void"}};Aa.Void=Vh;});var qt=_(Pa=>{Object.defineProperty(Pa,"__esModule",{value:true});Pa.NativeFunctionCall=void 0;var T=fe(),Mi=ji(),eO=Hn(),Oa=nt(),tO=et(),gt=re(),rt=Ve(),J=class n extends tO.InkObject{static CallWithName(e){return new n(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, rt.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(n._nativeFunctions===null?(0, rt.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=n._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof eO.Void)throw new Mi.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');a instanceof T.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let r=this.CoerceValuesToSingleType(e),i=r[0].valueType;return i==T.ValueType.Int?this.CallType(r):i==T.ValueType.Float?this.CallType(r):i==T.ValueType.String?this.CallType(r):i==T.ValueType.DivertTarget?this.CallType(r):i==T.ValueType.List?this.CallType(r):null}CallType(e){let t=(0, gt.asOrThrows)(e[0],T.Value),r=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, rt.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(r);if(!s){let o=T.ValueType[r];throw new Mi.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let u=(0, gt.asOrThrows)(e[1],T.Value),l=s;if(i.value===null||u.value===null)return (0, rt.throwNullException)("NativeFunctionCall.Call BinaryOp values");let c=l(i.value,u.value);return T.Value.Create(c)}else {let o=s;if(i.value===null)return (0, rt.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=o(i.value);return this.name===n.Int?T.Value.Create(u,T.ValueType.Int):this.name===n.Float?T.Value.Create(u,T.ValueType.Float):T.Value.Create(u,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof T.ListValue&&e[1]instanceof T.IntValue)return this.CallListIncrementOperation(e);let t=(0, gt.asOrThrows)(e[0],T.Value),r=(0, gt.asOrThrows)(e[1],T.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=T.ValueType.List||r.valueType!=T.ValueType.List)){if(this._operationFuncs===null)return (0, rt.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(T.ValueType.Int);if(i===null)return (0, rt.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, gt.asBooleanOrThrows)(i(t.isTruthy?1:0,r.isTruthy?1:0));return new T.BoolValue(a)}if(t.valueType==T.ValueType.List&&r.valueType==T.ValueType.List)return this.CallType([t,r]);throw new Mi.StoryException("Can not call use "+this.name+" operation on "+T.ValueType[t.valueType]+" and "+T.ValueType[r.valueType])}CallListIncrementOperation(e){let t=(0, gt.asOrThrows)(e[0],T.ListValue),r=(0, gt.asOrThrows)(e[1],T.IntValue),i=new Oa.InkList;if(t.value===null)return (0, rt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=Oa.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, rt.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(T.ValueType.Int);if(r.value===null)return (0, rt.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(s,r.value),c=null;if(t.value.origins===null)return (0, rt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let h of t.value.origins)if(h.name==o.originName){c=h;break}if(c!=null){let h=c.TryGetItemWithValue(l,Oa.InkListItem.Null);h.exists&&i.Add(h.result,l);}}return new T.ListValue(i)}CoerceValuesToSingleType(e){let t=T.ValueType.Int,r=null;for(let a of e){let s=(0, gt.asOrThrows)(a,T.Value);s.valueType>t&&(t=s.valueType),s.valueType==T.ValueType.List&&(r=(0, gt.asOrNull)(s,T.ListValue));}let i=[];if(T.ValueType[t]==T.ValueType[T.ValueType.List])for(let a of e){let s=(0, gt.asOrThrows)(a,T.Value);if(s.valueType==T.ValueType.List)i.push(s);else if(s.valueType==T.ValueType.Int){let o=parseInt(s.valueObject);if(r=(0, gt.asOrThrows)(r,T.ListValue),r.value===null)return (0, rt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=r.value.originOfMaxItem;if(u===null)return (0, rt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(o,Oa.InkListItem.Null);if(l.exists){let c=new T.ListValue(l.result,o);i.push(c);}else throw new Mi.StoryException("Could not find List item with the value "+o+" in "+u.name)}else {let o=T.ValueType[s.valueType];throw new Mi.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, gt.asOrThrows)(a,T.Value).Cast(t);i.push(o);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)n.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];n.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=true,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(r,i)=>r+i),this.AddIntBinaryOp(this.Subtract,(r,i)=>r-i),this.AddIntBinaryOp(this.Multiply,(r,i)=>r*i),this.AddIntBinaryOp(this.Divide,(r,i)=>Math.floor(r/i)),this.AddIntBinaryOp(this.Mod,(r,i)=>r%i),this.AddIntUnaryOp(this.Negate,r=>-r),this.AddIntBinaryOp(this.Equal,(r,i)=>r==i),this.AddIntBinaryOp(this.Greater,(r,i)=>r>i),this.AddIntBinaryOp(this.Less,(r,i)=>r<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(r,i)=>r>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(r,i)=>r<=i),this.AddIntBinaryOp(this.NotEquals,(r,i)=>r!=i),this.AddIntUnaryOp(this.Not,r=>r==0),this.AddIntBinaryOp(this.And,(r,i)=>r!=0&&i!=0),this.AddIntBinaryOp(this.Or,(r,i)=>r!=0||i!=0),this.AddIntBinaryOp(this.Max,(r,i)=>Math.max(r,i)),this.AddIntBinaryOp(this.Min,(r,i)=>Math.min(r,i)),this.AddIntBinaryOp(this.Pow,(r,i)=>Math.pow(r,i)),this.AddIntUnaryOp(this.Floor,n.Identity),this.AddIntUnaryOp(this.Ceiling,n.Identity),this.AddIntUnaryOp(this.Int,n.Identity),this.AddIntUnaryOp(this.Float,r=>r),this.AddFloatBinaryOp(this.Add,(r,i)=>r+i),this.AddFloatBinaryOp(this.Subtract,(r,i)=>r-i),this.AddFloatBinaryOp(this.Multiply,(r,i)=>r*i),this.AddFloatBinaryOp(this.Divide,(r,i)=>r/i),this.AddFloatBinaryOp(this.Mod,(r,i)=>r%i),this.AddFloatUnaryOp(this.Negate,r=>-r),this.AddFloatBinaryOp(this.Equal,(r,i)=>r==i),this.AddFloatBinaryOp(this.Greater,(r,i)=>r>i),this.AddFloatBinaryOp(this.Less,(r,i)=>r<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(r,i)=>r>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(r,i)=>r<=i),this.AddFloatBinaryOp(this.NotEquals,(r,i)=>r!=i),this.AddFloatUnaryOp(this.Not,r=>r==0),this.AddFloatBinaryOp(this.And,(r,i)=>r!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(r,i)=>r!=0||i!=0),this.AddFloatBinaryOp(this.Max,(r,i)=>Math.max(r,i)),this.AddFloatBinaryOp(this.Min,(r,i)=>Math.min(r,i)),this.AddFloatBinaryOp(this.Pow,(r,i)=>Math.pow(r,i)),this.AddFloatUnaryOp(this.Floor,r=>Math.floor(r)),this.AddFloatUnaryOp(this.Ceiling,r=>Math.ceil(r)),this.AddFloatUnaryOp(this.Int,r=>Math.floor(r)),this.AddFloatUnaryOp(this.Float,n.Identity),this.AddStringBinaryOp(this.Add,(r,i)=>r+i),this.AddStringBinaryOp(this.Equal,(r,i)=>r===i),this.AddStringBinaryOp(this.NotEquals,(r,i)=>r!==i),this.AddStringBinaryOp(this.Has,(r,i)=>r.includes(i)),this.AddStringBinaryOp(this.Hasnt,(r,i)=>!r.includes(i)),this.AddListBinaryOp(this.Add,(r,i)=>r.Union(i)),this.AddListBinaryOp(this.Subtract,(r,i)=>r.Without(i)),this.AddListBinaryOp(this.Has,(r,i)=>r.Contains(i)),this.AddListBinaryOp(this.Hasnt,(r,i)=>!r.Contains(i)),this.AddListBinaryOp(this.Intersect,(r,i)=>r.Intersect(i)),this.AddListBinaryOp(this.Equal,(r,i)=>r.Equals(i)),this.AddListBinaryOp(this.Greater,(r,i)=>r.GreaterThan(i)),this.AddListBinaryOp(this.Less,(r,i)=>r.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(r,i)=>r.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(r,i)=>r.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(r,i)=>!r.Equals(i)),this.AddListBinaryOp(this.And,(r,i)=>r.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(r,i)=>r.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,r=>r.Count==0?1:0),this.AddListUnaryOp(this.Invert,r=>r.inverse),this.AddListUnaryOp(this.All,r=>r.all),this.AddListUnaryOp(this.ListMin,r=>r.MinAsList()),this.AddListUnaryOp(this.ListMax,r=>r.MaxAsList()),this.AddListUnaryOp(this.Count,r=>r.Count),this.AddListUnaryOp(this.ValueOfList,r=>r.maxItem.Value);let e=(r,i)=>r.Equals(i),t=(r,i)=>!r.Equals(i);this.AddOpToNativeFunc(this.Equal,2,T.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,T.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,r,i){if(this._nativeFunctions===null)return (0, rt.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new n(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(r,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,T.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,T.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};Pa.NativeFunctionCall=J;J.Add="+";J.Subtract="-";J.Divide="/";J.Multiply="*";J.Mod="%";J.Negate="_";J.Equal="==";J.Greater=">";J.Less="<";J.GreaterThanOrEquals=">=";J.LessThanOrEquals="<=";J.NotEquals="!=";J.Not="!";J.And="&&";J.Or="||";J.Min="MIN";J.Max="MAX";J.Pow="POW";J.Floor="FLOOR";J.Ceiling="CEILING";J.Int="INT";J.Float="FLOAT";J.Has="?";J.Hasnt="!?";J.Intersect="^";J.ListMin="LIST_MIN";J.ListMax="LIST_MAX";J.All="LIST_ALL";J.Count="LIST_COUNT";J.ValueOfList="LIST_VALUE";J.Invert="LIST_INVERT";J._nativeFunctions=null;});var Ta=_(xa=>{Object.defineProperty(xa,"__esModule",{value:true});xa.NumberExpression=void 0;var nO=mt(),Rh=fe(),rO=re(),jh=class n extends nO.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=r=>{this.isInt()?r.AddContent(new Rh.IntValue(this.value)):this.isFloat()?r.AddContent(new Rh.FloatValue(this.value)):this.isBool()&&r.AddContent(new Rh.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, rO.asOrNull)(e,n);return t?t.subtype==this.subtype&&t.value==this.value:false}};xa.NumberExpression=jh;});var $h=_(Na=>{Object.defineProperty(Na,"__esModule",{value:true});Na.UnaryExpression=void 0;var iO=mt(),sO=qt(),Vr=Ta(),aO=re(),Gi=class extends iO.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=r=>{this.innerExpression.GenerateIntoContainer(r),r.AddContent(sO.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};Na.UnaryExpression=Gi;Gi.WithInner=(n,e)=>{let t=(0, aO.asOrNull)(n,Vr.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new Vr.NumberExpression(-t.value,"int");if(t.isFloat())return new Vr.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new Vr.NumberExpression(t.value==0,"bool");if(t.isFloat())return new Vr.NumberExpression(t.value==0,"bool");if(t.isBool())return new Vr.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new Gi(n,e)};});var qh=_(Fa=>{Object.defineProperty(Fa,"__esModule",{value:true});Fa.BinaryExpression=void 0;var oO=mt(),uO=qt(),lO=$h(),cO=re(),Lh=class extends oO.Expression{constructor(e,t,r){super(),this.opName=r,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(uO.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=r;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, cO.asOrNull)(this.leftExpression,lO.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};Fa.BinaryExpression=Lh;});var zi=_(Ia=>{Object.defineProperty(Ia,"__esModule",{value:true});Ia.CharacterSet=void 0;var Ji=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,r)=>{for(let i=t.charCodeAt(0);i<=r.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let r of t)this.Add(r);else for(let r of t.set)this.Add(r);return this},e&&this.AddCharacters(e);}};Ia.CharacterSet=Ji;Ji.FromRange=(n,e)=>new Ji().AddRange(n,e);});var Wy=_(ka=>{Object.defineProperty(ka,"__esModule",{value:true});ka.CharacterRange=void 0;var By=zi(),Hi=class{constructor(e,t,r=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new By.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),a;i<=this.end.charCodeAt(0);i+=1)a=String.fromCharCode(i),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},r instanceof By.CharacterSet)this._excludes=r.set;else for(let i of r)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};ka.CharacterRange=Hi;Hi.Define=(n,e,t=[])=>new Hi(n,e,t);});var Ra=_(Va=>{Object.defineProperty(Va,"__esModule",{value:true});Va.ChoicePoint=void 0;var hO=et(),dO=Qe(),Bh=Ve(),Wh=class extends hO.InkObject{constructor(e=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, Bh.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Bh.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new dO.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Bh.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};Va.ChoicePoint=Wh;});var Un=_(ja=>{Object.defineProperty(ja,"__esModule",{value:true});ja.PushPopType=void 0;var My;(function(n){n[n.Tunnel=0]="Tunnel",n[n.Function=1]="Function",n[n.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(My||(ja.PushPopType=My={}));});var Ui=_($a=>{Object.defineProperty($a,"__esModule",{value:true});$a.Pointer=void 0;var pO=Qe(),Mh=class n{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new pO.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new n(this.container,this.index)}static StartOf(e){return new n(e,0)}static get Null(){return new n(null,-1)}};$a.Pointer=Mh;});var Bt=_(qa=>{Object.defineProperty(qa,"__esModule",{value:true});qa.Divert=void 0;var fO=Qe(),mO=Un(),gO=Jn(),yO=et(),Gh=Ui(),Gy=ve(),La=Ve(),Jh=class n extends yO.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=Gh.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, La.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, La.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, La.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof Gy.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Gh.Pointer.StartOf(e instanceof Gy.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new fO.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=Gh.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof e<"u"&&(this.pushesToStack=true,this.stackPushType=e);}Equals(e){let t=e;return t instanceof n&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, La.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new gO.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==mO.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};qa.Divert=Jh;});var tn=_(Ba=>{Object.defineProperty(Ba,"__esModule",{value:true});Ba.SymbolType=void 0;var Jy;(function(n){n[n.Knot=0]="Knot",n[n.List=1]="List",n[n.ListItem=2]="ListItem",n[n.Var=3]="Var",n[n.SubFlowAndWeave=4]="SubFlowAndWeave",n[n.Arg=5]="Arg",n[n.Temp=6]="Temp";})(Jy||(Ba.SymbolType=Jy={}));});var bn=_(Wa=>{Object.defineProperty(Wa,"__esModule",{value:true});Wa.VariableAssignment=void 0;var vO=et(),zh=class extends vO.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};Wa.VariableAssignment=zh;});var Rr=_(Ga=>{Object.defineProperty(Ga,"__esModule",{value:true});Ga.Choice=void 0;var bO=Ra(),Ma=ve(),Cn=Re(),Hh=Bt(),zy=fe(),CO=pe(),SO=tn(),Hy=bn(),Uh=class extends CO.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,r){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new Ma.Container,this._runtimeChoice=new bO.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Cn.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new zy.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Hy.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Cn.ControlCommand.BeginString()),this._divertToStartContentOuter=new Hh.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Hh.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Ma.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Cn.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Cn.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Cn.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Cn.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Ma.Container,this.startContent){this._returnToR2=new zy.DivertTargetValue,this._innerContentContainer.AddContent(Cn.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Cn.ControlCommand.EvalEnd());let i=new Hy.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Hh.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Ma.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=e,this.choiceOnlyContent=t,this.innerContent=r,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),r&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(e){var t;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,SO.SymbolType.SubFlowAndWeave);}};Ga.Choice=Uh;});var Uy=_(za=>{Object.defineProperty(za,"__esModule",{value:true});za.StringParserElement=void 0;var Ja=class n{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{n._uniqueIdCounter++,this.uniqueId=n._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};za.StringParserElement=Ja;Ja._uniqueIdCounter=1e3;});var Xy=_(Ha=>{Object.defineProperty(Ha,"__esModule",{value:true});Ha.StringParserState=void 0;var Ky=Uy(),Kh=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let r=0;r<200;++r)this._stack[r]=new Ky.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],r=this._stack[this._numElements];return this._numElements++,r.CopyFrom(t),r.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],r=this._stack[this._numElements-1];t.SquashFrom(r),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new Ky.StringParserElement;this._numElements=1;}};Ha.StringParserState=Kh;});var Yh=_(Kn=>{Object.defineProperty(Kn,"__esModule",{value:true});Kn.StringParser=Kn.ParseSuccess=void 0;var Xh=zi(),_O=Xy();Kn.ParseSuccess=Symbol("ParseSuccessStruct");var Ki=class n{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=r=>(this.state.Pop(r),null),this.CancelRule=r=>{this.state.Pop(r);},this.SucceedRule=(r,i=null)=>{let a=this.state.Peek(r),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,s,a),this.state.Squash();let o=i;return o===null&&(o=n.ParseSuccess),o},this.Expect=(r,i=null,a=null)=>{let s=this.ParseObject(r);if(s===null){i===null&&(i=r.name);let o,u=this.LineRemainder();u===null||u.length===0?o="end of line":o=`'${u}'`,this.Error(`Expected ${i} but saw ${o}`),a!==null&&(s=a());}return s},this.Error=(r,i=false)=>{this.ErrorOnLine(r,this.lineIndex+1,i);},this.ErrorWithParsedObject=(r,i,a=false)=>{this.ErrorOnLine(r,i.debugMetadata?i.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(r,i,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(r,this.index,i-1,a);else throw new Error(`${s} on line ${i}: ${r}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=r=>this.Error(r,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
12
12
  \r`)),this.SetFlag=(r,i)=>{i?this.state.customFlags|=r:this.state.customFlags&=~r;},this.GetFlag=r=>!!(this.state.customFlags&r),this.ParseObject=r=>{let i=this.BeginRule(),a=this.state.stackHeight,s=r();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return s===null?this.FailRule(i):(this.SucceedRule(i,s),s)},this.Parse=r=>{let i=this.BeginRule(),a=r();return a===null?(this.FailRule(i),null):(this.SucceedRule(i,a),a)},this.OneOf=r=>{for(let i of r){let a=this.ParseObject(i);if(a!==null)return a}return null},this.OneOrMore=r=>{let i=[],a=null;do a=this.ParseObject(r),a!==null&&i.push(a);while(a!==null);return i.length>0?i:null},this.Optional=r=>()=>{let i=this.ParseObject(r);return i===null?n.ParseSuccess:i},this.Exclude=r=>()=>this.ParseObject(r)&&n.ParseSuccess,this.OptionalExclude=r=>()=>(this.ParseObject(r),n.ParseSuccess),this.String=r=>()=>this.ParseString(r),this.TryAddResultToList=(r,i,a=true)=>{if(r!==n.ParseSuccess){if(a&&Array.isArray(r)){let s=r;if(s!==null){for(let o of s)i.push(o);return}}i.push(r);}},this.Interleave=(r,i,a=null,s=true)=>{let o=this.BeginRule(),u=[],l=this.ParseObject(r);if(l===null)return this.FailRule(o);this.TryAddResultToList(l,u,s);let c=null,h=null;do{if(a!==null&&this.Peek(a)!==null||(c=this.ParseObject(i),c===null))break;if(this.TryAddResultToList(c,u,s),h=null,c!==null){if(h=this.ParseObject(r),h===null)break;this.TryAddResultToList(h,u,s);}}while((c!==null||h!==null)&&!(c===n.ParseSuccess&&h==n.ParseSuccess)&&this.remainingLength>0);return u.length===0?this.FailRule(o):this.SucceedRule(o,u)},this.ParseString=r=>{if(r.length>this.remainingLength)return null;let i=this.BeginRule(),a=this.index,s=this.characterInLineIndex,o=this.lineIndex,u=true;for(let l=0;l<r.length;l+=1){let c=r[l];if(this._chars[a]!==c){u=false;break}c===`
13
13
  `&&(o++,s=-1),a++,s++;}return this.index=a,this.characterInLineIndex=s,this.lineIndex=o,u?this.SucceedRule(i,r):this.FailRule(i)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){let r=this._chars[this.index];return r===`
14
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,r}return "0"},this.ParseUntilCharactersFromString=(r,i=-1)=>this.ParseCharactersFromString(r,false,i),this.ParseUntilCharactersFromCharSet=(r,i=-1)=>this.ParseCharactersFromCharSet(r,false,i),this.ParseCharactersFromString=(r,i=-1,a=-1)=>{let s=new Uh.CharacterSet(r);return typeof i=="number"?this.ParseCharactersFromCharSet(s,true,i):this.ParseCharactersFromCharSet(s,i,a)},this.ParseCharactersFromCharSet=(r,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,u=this.characterInLineIndex,l=this.lineIndex,c=0;for(;o<this._chars.length&&r.set.has(this._chars[o])===i&&c<a;)this._chars[o]===`
14
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,r}return "0"},this.ParseUntilCharactersFromString=(r,i=-1)=>this.ParseCharactersFromString(r,false,i),this.ParseUntilCharactersFromCharSet=(r,i=-1)=>this.ParseCharactersFromCharSet(r,false,i),this.ParseCharactersFromString=(r,i=-1,a=-1)=>{let s=new Xh.CharacterSet(r);return typeof i=="number"?this.ParseCharactersFromCharSet(s,true,i):this.ParseCharactersFromCharSet(s,i,a)},this.ParseCharactersFromCharSet=(r,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,u=this.characterInLineIndex,l=this.lineIndex,c=0;for(;o<this._chars.length&&r.set.has(this._chars[o])===i&&c<a;)this._chars[o]===`
15
15
  `&&(l+=1,u=-1),o+=1,u+=1,c+=1;return this.index=o,this.characterInLineIndex=u,this.lineIndex=l,this.index>s?this._chars.slice(s,this.index).join(""):null},this.Peek=r=>{let i=this.BeginRule(),a=r();return this.CancelRule(i),a},this.ParseInt=()=>{let r=this.index,i=this.characterInLineIndex,a=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");let s=this.ParseCharactersFromCharSet(n.numbersCharacterSet);if(s===null)return this.index=r,this.characterInLineIndex=i,null;let o;return Number.isNaN(Number(s))?(this.Error("Failed to read integer value: "+s+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(o=Number(s),a?-o:o)},this.ParseFloat=()=>{let r=this.index,i=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let s=this.ParseCharactersFromCharSet(n.numbersCharacterSet);return +`${a}.${s}`}return this.index=r,this.characterInLineIndex=i,null},this.ParseNewline=()=>{let r=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
16
16
  `)===null?this.FailRule(r):this.SucceedRule(r,`
17
- `)};let t=this.PreProcessInputString(e);this.state=new bP.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,r=null){let i=this.BeginRule(),a=new Uh.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),r!==null&&(a.set=new Set([...a.set.values(),...r.set.values()]));let s="",o=null;do{let u=this.ParseUntilCharactersFromCharSet(a);if(u&&(s+=u),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let l=this.currentCharacter;if(t!==null&&t.set.has(l)){s+=l,l===`
18
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(i,String(s)):this.FailRule(i)}};Hn.StringParser=Hi;Hi.ParseSuccess=Hn.ParseSuccess;Hi.numbersCharacterSet=new Uh.CharacterSet("0123456789");});var Ky=S(za=>{Object.defineProperty(za,"__esModule",{value:true});za.CommentEliminator=void 0;var Xh=Gi(),_P=Kh(),Yh=class extends _P.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Xh.CharacterSet(`/\r
19
- `),this._commentBlockEndCharacter=new Xh.CharacterSet("*"),this._newlineCharacters=new Xh.CharacterSet(`
17
+ `)};let t=this.PreProcessInputString(e);this.state=new _O.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,r=null){let i=this.BeginRule(),a=new Xh.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),r!==null&&(a.set=new Set([...a.set.values(),...r.set.values()]));let s="",o=null;do{let u=this.ParseUntilCharactersFromCharSet(a);if(u&&(s+=u),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let l=this.currentCharacter;if(t!==null&&t.set.has(l)){s+=l,l===`
18
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(i,String(s)):this.FailRule(i)}};Kn.StringParser=Ki;Ki.ParseSuccess=Kn.ParseSuccess;Ki.numbersCharacterSet=new Xh.CharacterSet("0123456789");});var Yy=_(Ua=>{Object.defineProperty(Ua,"__esModule",{value:true});Ua.CommentEliminator=void 0;var Zh=zi(),wO=Yh(),Qh=class extends wO.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Zh.CharacterSet(`/\r
19
+ `),this._commentBlockEndCharacter=new Zh.CharacterSet("*"),this._newlineCharacters=new Zh.CharacterSet(`
20
20
  \r`),this.Process=()=>{let e=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return e!==null?e.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let e=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return e!==null?e.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>this.ParseString("//")===null?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(this.ParseString("/*")===null)return null;let e=this.lineIndex,t=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),t!=null?`
21
- `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};za.CommentEliminator=Yh;});var Ua=S(Ha=>{Object.defineProperty(Ha,"__esModule",{value:true});Ha.Conditional=void 0;var SP=ye(),Xy=Ve(),EP=de(),Zh=class extends EP.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let r=new SP.Container;this.initialCondition&&r.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let a=i.runtimeObject;r.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&r.AddContent(Xy.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Xy.ControlCommand.NoOp(),r.AddContent(this._reJoinTarget),r},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let r of this.branches){if(!r.returnDivert)throw new Error;r.returnDivert.targetPath=t;}super.ResolveReferences(e);}};Ha.Conditional=Zh;});var Cn=S(Ka=>{Object.defineProperty(Ka,"__esModule",{value:true});Ka.Text=void 0;var wP=de(),DP=fe(),Qh=class extends wP.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new DP.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Ka.Text=Qh;});var Ya=S(Xa=>{Object.defineProperty(Xa,"__esModule",{value:true});Xa.ConstantDeclaration=void 0;var AP=de(),PP=Qt(),ed=class extends AP.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,PP.SymbolType.Var);}};Xa.ConstantDeclaration=ed;});var Vr=S(Za=>{Object.defineProperty(Za,"__esModule",{value:true});Za.FlowLevel=void 0;var Yy;(function(n){n[n.Story=0]="Story",n[n.Knot=1]="Knot",n[n.Stitch=2]="Stitch",n[n.WeavePoint=3]="WeavePoint";})(Yy||(Za.FlowLevel=Yy={}));});var Ui=S(Qa=>{Object.defineProperty(Qa,"__esModule",{value:true});Qa.Gather=void 0;var OP=ye(),xP=de(),TP=Qt(),td=class extends xP.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let r=new OP.Container;if(r.name=this.name,this.story.countAllVisits&&(r.visitsShouldBeCounted=true),r.countingAtStartOnly=true,this.content)for(let i of this.content)r.AddContent(i.runtimeObject);return r},this.toString=()=>{var r,i;return `- ${!((r=this.identifier)===null||r===void 0)&&r.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,TP.SymbolType.SubFlowAndWeave);}};Qa.Gather=td;});var Un=S(to=>{Object.defineProperty(to,"__esModule",{value:true});to.Path=void 0;var eo=ne(),Zy=qt(),Rr=Vr(),NP=Kn(),nd=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Rr.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(eo.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Rr.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=r=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(r);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=r=>{let i=this.firstComponent,a=r;for(;a;){let s=a===r,o=this.GetChildFromContext(a,i,null,s);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=r=>{let i=r;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let s=this.components[a].name,o,u=(0, eo.asOrNull)(i,Zy.FlowBase);if(u!==null?o=u.flowLevel+1:o=Rr.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,s,o),i===null)break}return i},this.GetChildFromContext=(r,i,a,s=false)=>{let o=a===null,u=(0, eo.asOrNull)(r,NP.Weave);if(i&&u!==null&&(o||a===Rr.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, eo.asOrNull)(r,Zy.FlowBase);if(i&&l!==null){let c=s||l.flowLevel===Rr.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,a,c)}return null},Object.values(Rr.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};to.Path=nd;});var sd=S(no=>{Object.defineProperty(no,"__esModule",{value:true});no.ReturnType=void 0;var FP=de(),IP=ye(),rd=Ve(),kP=Jn(),id=class extends FP.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new IP.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(rd.ControlCommand.EvalStart()),t.AddContent(new kP.Void),t.AddContent(rd.ControlCommand.EvalEnd())),t.AddContent(rd.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};no.ReturnType=id;});var Ki=S(ro=>{Object.defineProperty(ro,"__esModule",{value:true});ro.ClosestFlowBase=void 0;function VP(n){let e=n.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}ro.ClosestFlowBase=VP;});var so=S(io=>{Object.defineProperty(io,"__esModule",{value:true});io.Identifier=void 0;var ad=class n{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new n("DONE")}};io.Identifier=ad;});var qt=S(ao=>{Object.defineProperty(ao,"__esModule",{value:true});ao.FlowBase=void 0;var RP=kr(),od=jr(),$P=$r(),Bt=Vr(),jP=Ui(),LP=de(),qP=Un(),BP=sd(),WP=ye(),MP=Lt(),GP=yn(),ud=Qt(),JP=Kn(),zP=Ki(),HP=so(),Qy=ne(),ld=class n extends LP.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,r=null,i=false,a=false){super(),this.isFunction=i,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(s,o)=>{var u,l;let c=[],h=[];this._subFlowsByName=new Map;for(let p of s){let g=(0, Qy.asOrNull)(p,n);g?(this._firstChildFlow===null&&(this._firstChildFlow=g),h.push(p),!((u=g.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=g.identifier)===null||l===void 0?void 0:l.name,g)):c.push(p);}o&&c.push(new jP.Gather(null,1),new od.Divert(new qP.Path(HP.Identifier.Done())));let f=[];return c.length>0&&(this._rootWeave=new JP.Weave(c,0),f.push(this._rootWeave)),h.length>0&&f.push(...h),f},this.ResolveVariableWithName=(s,o)=>{var u;let l={},c=o===null?this:(0, zP.ClosestFlowBase)(o);if(c){if(c.args!==null){for(let h of c.args)if(((u=h.identifier)===null||u===void 0?void 0:u.name)===s)return l.found=true,l.isArgument=true,l.ownerFlow=c,l}if(c!==this.story&&c.variableDeclarations.has(s))return l.found=true,l.ownerFlow=c,l.isTemporary=true,l}return this.story.variableDeclarations.has(s)?(l.found=true,l.ownerFlow=this.story,l.isGlobal=true,l):(l.found=false,l)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let u=this.variableDeclarations.get(o),l="";u.debugMetadata&&(l=` (${u.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${l}`,s,false);return}this.variableDeclarations.set(s.variableName,s);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,s]of this._subFlowsByName)s.hasOwnProperty("ResolveWeavePointNaming")&&s.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var s;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===Bt.FlowLevel.Knot||this.flowLevel===Bt.FlowLevel.Stitch)&&(o=this.Find(BP.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let u=new WP.Container;u.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(u.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(u);let l=0;for(;this.content!==null&&l<this.content.length;){let c=this.content[l];if(c instanceof n){let h=c,f=h.runtimeObject;l===0&&!h.hasParameters&&this.flowLevel===Bt.FlowLevel.Knot&&(this._startingSubFlowDivert=new MP.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let p=f,g=u.namedContent.get(p.name)||null;if(g){let m=`${this.GetType()} already contains flow named '${p.name}' (at ${g.debugMetadata})`;this.Error(m,h);}u.AddToNamedContentOnly(p);}else c&&u.AddContent(c.runtimeObject);l+=1;}return this.flowLevel!==Bt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),u},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let u=this.args.length-1;u>=0;--u){let l=((o=this.args[u].identifier)===null||o===void 0?void 0:o.name)||null,c=new GP.VariableAssignment(l,true);s.AddContent(c);}},this.ContentWithNameAtLevel=(s,o=null,u=false)=>{var l;if((o===this.flowLevel||o===null)&&s===((l=this.identifier)===null||l===void 0?void 0:l.name))return this;if(o===Bt.FlowLevel.WeavePoint||o===null){let h=null;if(this._rootWeave&&(h=this._rootWeave.WeavePointNamed(s),h))return h;if(o===Bt.FlowLevel.WeavePoint)return u?this.DeepSearchForAnyLevelContent(s):null}if(o!==null&&o<this.flowLevel)return null;let c=this._subFlowsByName.get(s)||null;return c&&(o===null||o===c.flowLevel)?c:u?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,Bt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,u]of this._subFlowsByName){let l=u.ContentWithNameAtLevel(s,null,true);if(l)return l}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==Bt.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[u,l]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${u}' within the function '${this.identifier}'`,l);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(od.Divert)();for(let u of s)!u.isFunctionCall&&!(u.parent instanceof $P.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let o=this._rootWeave.FindAll(RP.Choice)();for(let u of o)this.Error(`Functions may not contain choices, but saw '${u}'`,u);},this.WarningInTermination=s=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";s.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let u=(0, Qy.asOrNull)(s,od.Divert);u&&u.isTunnel&&(o+=` When final tunnel to '${u.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=r,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,r;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,ud.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((t=this.args[i].identifier)===null||t===void 0?void 0:t.name)==((r=this.args[a].identifier)===null||r===void 0?void 0:r.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==Bt.FlowLevel.Story){let i=this.flowLevel===Bt.FlowLevel.Knot?ud.SymbolType.Knot:ud.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};ao.FlowBase=ld;});var uo=S(oo=>{Object.defineProperty(oo,"__esModule",{value:true});oo.ContentList=void 0;var UP=ye(),KP=de(),XP=Cn(),YP=ne(),cd=class extends KP.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let r=this.content.length-1;r>=0;--r){let i=(0, YP.asOrNull)(this.content[r],XP.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(r,1);else break}},this.GenerateRuntimeObject=()=>{let r=new UP.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&r.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(r),r},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};oo.ContentList=cd;});var Lr=S(lo=>{Object.defineProperty(lo,"__esModule",{value:true});lo.VariableReference=void 0;var ZP=Ze(),QP=Ye(),hd=class extends ZP.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new QP.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};lo.VariableReference=hd;});var qr=S(co=>{Object.defineProperty(co,"__esModule",{value:true});co.VariableReference=void 0;var eO=uo(),tO=ft(),ev=qt(),nO=Un(),rO=Lr(),iO=Kn(),sO=so(),tv=ne(),dd=class extends tO.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(tv.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new sO.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=t=>{let r=this.story.constants.get(this.name);if(r){r.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new rO.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",a="";this.path.length===1?i=this.path[0]:(a=this.path[0],i=this.path[1]),this.story.ResolveListItem(a,i,this)&&(this.isListItemReference=true);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new nO.Path(this.pathIdentifiers),r=t.ResolveFromContext(this);if(r){if(!r.containerForCounting)throw new Error;if(r.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=r.runtimePath,this._runtimeVarRef.name=null;let i=(0, tv.asOrNull)(r,ev.FlowBase);i&&i.isFunction&&(this.parent instanceof iO.Weave||this.parent instanceof eO.ContentList||this.parent instanceof ev.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${t}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};co.VariableReference=dd;});var Xi=S(mo=>{Object.defineProperty(mo,"__esModule",{value:true});mo.FunctionCall=void 0;var Wt=Ve(),aO=jr(),oO=$r(),uO=ft(),lO=et(),cO=fe(),fo=jt(),nv=Oa(),hO=Un(),dO=fe(),fO=qr(),ho=ne(),po=class n extends uO.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(e,t){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=r=>{let i=this.story.ResolveList(this.name),a=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),r.AddContent(Wt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),r.AddContent(Wt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, ho.asOrNull)(this.args[0],oO.DivertTarget),o=(0, ho.asOrNull)(this.args[0],fO.VariableReference);if(this.args.length!==1||s===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}s?(this._divertTargetToCount=s,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(r)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(r)),this.isTurnsSince?r.AddContent(Wt.ControlCommand.TurnsSince()):r.AddContent(Wt.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let s=0;s<this.args.length;s+=1){let o=(0, ho.asOrNull)(this.args[s],nv.NumberExpression);if(o&&!o.isInt()){let u=s===0?"minimum":"maximum";this.Error(`RANDOM's ${u} parameter should be an integer`);}this.args[s].GenerateIntoContainer(r);}r.AddContent(Wt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, ho.asOrNull)(this.args[0],nv.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(r),r.AddContent(Wt.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let s=0;s<this.args.length;s+=1)this.args[s].GenerateIntoContainer(r);r.AddContent(Wt.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(r),r.AddContent(Wt.ControlCommand.ListRandom());else if(fo.NativeFunctionCall.CallExistsWithName(this.name)){let s=fo.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${n.name} should take ${s.numberOfParameters} parameter`;s.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(r);r.AddContent(fo.NativeFunctionCall.CallWithName(this.name));}else if(i!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)r.AddContent(new dO.StringValue(this.name)),this.args[0].GenerateIntoContainer(r),r.AddContent(Wt.ControlCommand.ListFromInt());else {let s=new lO.InkList;s.SetInitialOriginName(this.name),r.AddContent(new cO.ListValue(s));}else r.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&r.AddContent(Wt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let r=this.args.join(", ");return `${this.name}(${r})`},this._proxyDivert=new aO.Divert(new hO.Path(e),t),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,r=t.runtimeDivert.variableDivertName!=null;if(r){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let i=t.targetContent;if(i===null)r||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${n.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};mo.FunctionCall=po;po.IsBuiltIn=n=>fo.NativeFunctionCall.CallExistsWithName(n)?true:n==="CHOICE_COUNT"||n==="TURNS_SINCE"||n==="TURNS"||n==="RANDOM"||n==="SEED_RANDOM"||n==="LIST_VALUE"||n==="LIST_RANDOM"||n==="READ_COUNT";});var pd=S(go=>{Object.defineProperty(go,"__esModule",{value:true});go.MultipleConditionExpression=void 0;var pO=ft(),mO=jt(),fd=class extends pO.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let r=true;for(let i of this.subExpressions)i.GenerateIntoContainer(t),r||t.AddContent(mO.NativeFunctionCall.CallWithName("&&")),r=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};go.MultipleConditionExpression=fd;});var $r=S(yo=>{Object.defineProperty(yo,"__esModule",{value:true});yo.DivertTarget=void 0;var gO=jh(),yO=kr(),vO=Ua(),CO=vd(),bO=fe(),md=ft(),_O=qt(),rv=Xi(),SO=pd(),iv=qr(),gd=ne(),yd=class n extends md.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new bO.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let r=(0, gd.asOrNull)(t,n);if(!r||!this.divert.target||!r.divert.target)return false;let i=this.divert.target.dotSeparatedComponents,a=r.divert.target.dotSeparatedComponents;return i===a},this.divert=this.AddContent(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof md.Expression;){let i=false,a=false,s=t.parent;if(s instanceof gO.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof n||o.leftExpression instanceof iv.VariableReference)&&(o.rightExpression instanceof n||o.rightExpression instanceof iv.VariableReference)||(i=true),a=true;}else if(s instanceof rv.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof md.Expression||s instanceof SO.MultipleConditionExpression||s instanceof yO.Choice&&s.condition===t||s instanceof vO.Conditional||s instanceof CO.ConditionalSingleBranch)&&(i=true,a=true);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;t=s;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let r=this.divert.targetContent;if(r!==null){let i=r.containerForCounting;if(i!==null){let s=(0, gd.asOrNull)(this.parent,rv.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, gd.asOrNull)(r,_O.FlowBase);if(a!=null&&a.args!==null)for(let s of a.args)s.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${s.identifier}').`);}}};yo.DivertTarget=yd;});var jr=S(vo=>{Object.defineProperty(vo,"__esModule",{value:true});vo.Divert=void 0;var EO=ye(),Yi=Ve(),wO=Lt(),Cd=$r(),bd=qt(),DO=Xi(),AO=de(),sv=Un(),PO=Ye(),av=zn(),OO=fe(),ov=qr(),xO=Ki(),Zi=ne(),_d=class extends AO.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return Yi.ControlCommand.End();if(this.isDone)return Yi.ControlCommand.Done();this.runtimeDivert=new wO.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let r=this.args!==null&&this.args.length>0;if(r||this.isFunctionCall||this.isTunnel||this.isThread){let i=new EO.Container;if(r){this.isFunctionCall||i.AddContent(Yi.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let s=0;s<this.args.length;++s){let o=this.args[s],u=null;if(a&&s<a.length&&(u=a[s]),u&&u.isByReference){let l=(0, Zi.asOrNull)(o,ov.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${o}`);break}let c=new sv.Path(l.pathIdentifiers);if(c.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${c.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let f=new OO.VariablePointerValue(l.name);i.AddContent(f);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Yi.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Yi.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?av.PushPopType.Function:av.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let r=this.PathAsVariableName();if(r!==null){let i=(0, Zi.asOrNull)((0, xO.ClosestFlowBase)(this),bd.FlowBase);if(i){let a=i.ResolveVariableWithName(r,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var u;return ((u=o.identifier)===null||u===void 0?void 0:u.name)==r});s&&!s.isDivertTarget&&this.Error(`Since '${s.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${s.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=r;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let r=0;if(this.args!==null&&this.args.length>0&&(r=this.args.length),this.targetContent===null)return;let i=(0, Zi.asOrNull)(this.targetContent,bd.FlowBase);if(r===0&&(i===null||!i.hasParameters))return;if(i===null&&r>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&r>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof Cd.DivertTarget){r>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==r){let s;r===0?s="but there weren't any passed to it":r<a?s=`but only got ${r}`:s=`but got ${r}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=i.args[s],u=this.args[s];if(o.isDivertTarget){let l=(0, Zi.asOrNull)(u,ov.VariableReference);if(!(u instanceof Cd.DivertTarget)&&l===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${u}`,u);else if(l){let c=new sv.Path(l.pathIdentifiers);c.ResolveFromContext(l)&&this.Error(`Passing read count of '${c.dotSeparatedComponents}' instead of a divert target. You probably meant '${c}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=r=>{let i=this.target?this.target.firstComponent:null,a=r.externals.get(i);if(!a)throw new Error("external not found");let s=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==s&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${s} but got ${o}`);},this.toString=()=>{let r="";if(this.target!==null)r+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(r+=" ->"),this.isFunctionCall&&(r+=" ()"),r},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, Zi.asOrNull)(this.targetContent,bd.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof Cd.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let r=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=DO.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new PO.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!r&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,r=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,r):super.Error(`Divert ${e}`,t,r);}};vo.Divert=_d;});var uv=S(Co=>{Object.defineProperty(Co,"__esModule",{value:true});Co.GatherPointToResolve=void 0;var Sd=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};Co.GatherPointToResolve=Sd;});var lv=S(bo=>{Object.defineProperty(bo,"__esModule",{value:true});bo.SequenceDivertToResolve=void 0;var Ed=class{constructor(e,t){this.divert=e,this.targetContent=t;}};bo.SequenceDivertToResolve=Ed;});var wd=S(_o=>{Object.defineProperty(_o,"__esModule",{value:true});_o.SequenceType=void 0;var cv;(function(n){n[n.Stopping=1]="Stopping",n[n.Cycle=2]="Cycle",n[n.Shuffle=4]="Shuffle",n[n.Once=8]="Once";})(cv||(_o.SequenceType=cv={}));});var Pd=S(wo=>{Object.defineProperty(wo,"__esModule",{value:true});wo.Sequence=void 0;var hv=ye(),At=Ve(),Dd=Lt(),Qi=fe(),So=jt(),TO=de(),NO=lv(),Eo=wd(),FO=Kn(),Ad=class extends TO.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let r=new hv.Container;r.visitsShouldBeCounted=true,r.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],r.AddContent(At.ControlCommand.EvalStart()),r.AddContent(At.ControlCommand.VisitIndex());let i=(this.sequenceType&Eo.SequenceType.Once)>0,a=(this.sequenceType&Eo.SequenceType.Cycle)>0,s=(this.sequenceType&Eo.SequenceType.Stopping)>0,o=(this.sequenceType&Eo.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),s||i?(r.AddContent(new Qi.IntValue(u-1)),r.AddContent(So.NativeFunctionCall.CallWithName("MIN"))):a&&(r.AddContent(new Qi.IntValue(this.sequenceElements.length)),r.AddContent(So.NativeFunctionCall.CallWithName("%"))),o){let c=At.ControlCommand.NoOp();if(i||s){let f=s?this.sequenceElements.length-1:this.sequenceElements.length;r.AddContent(At.ControlCommand.Duplicate()),r.AddContent(new Qi.IntValue(f)),r.AddContent(So.NativeFunctionCall.CallWithName("=="));let p=new Dd.Divert;p.isConditional=true,r.AddContent(p),this.AddDivertToResolve(p,c);}let h=this.sequenceElements.length;s&&(h-=1),r.AddContent(new Qi.IntValue(h)),r.AddContent(At.ControlCommand.SequenceShuffleIndex()),(i||s)&&r.AddContent(c);}r.AddContent(At.ControlCommand.EvalEnd());let l=At.ControlCommand.NoOp();for(let c=0;c<u;c+=1){r.AddContent(At.ControlCommand.EvalStart()),r.AddContent(At.ControlCommand.Duplicate()),r.AddContent(new Qi.IntValue(c)),r.AddContent(So.NativeFunctionCall.CallWithName("==")),r.AddContent(At.ControlCommand.EvalEnd());let h=new Dd.Divert;h.isConditional=true,r.AddContent(h);let f;c<this.sequenceElements.length?f=this.sequenceElements[c].runtimeObject:f=new hv.Container,f.name=`s${c}`,f.InsertContent(At.ControlCommand.PopEvaluatedValue(),0);let p=new Dd.Divert;f.AddContent(p),r.AddToNamedContentOnly(f),this.AddDivertToResolve(h,f),this.AddDivertToResolve(p,l);}return r.AddContent(l),r},this.AddDivertToResolve=(r,i)=>{this._sequenceDivertsToResolve.push(new NO.SequenceDivertToResolve(r,i));},this.sequenceType=t,this.sequenceElements=[];for(let r of e){let i=r.content,a=null;i===null||i.length===0?a=r:a=new FO.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};wo.Sequence=Ad;});var xd=S(Do=>{Object.defineProperty(Do,"__esModule",{value:true});Do.TunnelOnwards=void 0;var IO=ye(),es=Ve(),kO=Lt(),VO=fe(),RO=de(),$O=Jn(),jO=ne(),LO=Lr(),Od=class extends RO.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new IO.Container;if(e.AddContent(es.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),r=t;if(r){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let u=0;u<r.content.length;u+=1){let l=r.content[u];l&&(s==-1&&l.commandType===es.ControlCommand.CommandType.EvalStart?s=u:l.commandType===es.ControlCommand.CommandType.EvalEnd&&(o=u));}for(let u=s+1;u<o;u+=1){let l=r.content[u];l.parent=null,e.AddContent(r.content[u]);}}}let i=(0, jO.asOrNull)(t,kO.Divert);if(i!=null&&i.hasVariableTarget){let a=new LO.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new VO.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new $O.Void);return e.AddContent(es.ControlCommand.EvalEnd()),e.AddContent(es.ControlCommand.PopTunnel()),e},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};Do.TunnelOnwards=Od;});var Fd=S(Ao=>{Object.defineProperty(Ao,"__esModule",{value:true});Ao.ListDefinition=void 0;var Td=et(),Nd=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let r=new Td.InkListItem(this.name,e);this._items.set(r.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?false:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[r,i]of this._itemNameToValues)if(i==e)return t=new Td.InkListItem(this.name,r),{result:t,exists:true};return t=Td.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let r=this._itemNameToValues.get(e.itemName);return r?{result:r,exists:true}:{result:0,exists:false}}};Ao.ListDefinition=Nd;});var Oo=S(Po=>{Object.defineProperty(Po,"__esModule",{value:true});Po.ListDefinition=void 0;var qO=et(),BO=et(),WO=Fd(),MO=fe(),GO=de(),JO=Qt(),Id=class extends GO.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let r of this.itemDefinitions)t.has(r.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${r.name}'`):t.set(r.name,r.seriesValue);return new WO.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=r=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(r)||null},this.GenerateRuntimeObject=()=>{var r,i;let a=new qO.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new BO.InkListItem(((r=this.identifier)===null||r===void 0?void 0:r.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new MO.ListValue(a)};let t=1;for(let r of this.itemDefinitions)r.explicitValue!==null&&(t=r.explicitValue),r.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,JO.SymbolType.List);}};Po.ListDefinition=Id;});var Vd=S(xo=>{Object.defineProperty(xo,"__esModule",{value:true});xo.VariableAssignment=void 0;var zO=ye(),HO=Ki(),UO=Oo(),KO=de(),dv=Qt(),XO=yn(),YO=qr(),ZO=ne(),kd=class extends KO.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:r,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, HO.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new zO.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new XO.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!r,i instanceof UO.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?dv.SymbolType.Var:dv.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, ZO.asOrNull)(this.expression,YO.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};xo.VariableAssignment=kd;});var Kn=S(Fo=>{Object.defineProperty(Fo,"__esModule",{value:true});Fo.Weave=void 0;var fv=da(),mt=kr(),To=Ua(),QO=Ya(),ex=ye(),No=jr(),tx=Lt(),nx=$r(),rx=qt(),Mt=Ui(),ix=uv(),sx=de(),Rd=Pd(),ax=Cn(),ox=xd(),ux=Vd(),gt=ne(),$d=class n extends sx.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let r=this.content.length-1;r>=0;--r){e=this.content[r];let i=(0, gt.asOrNull)(e,ax.Text);if(!(i&&i.text===`
22
- `)&&!this.IsGlobalDeclaration(e))break}let t=(0, gt.asOrNull)(e,n);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var r,i,a;let s=[...this.FindAll(Mt.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(mt.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let u=this.namedWeavePoints.get(((r=o.identifier)===null||r===void 0?void 0:r.name)||"");if(u){let l=u instanceof Mt.Gather?"gather":"choice",c=u;this.Error(`A ${l} with the same label name '${o.name}' already exists in this context on line ${c.debugMetadata?c.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((i=o.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let r=0;for(;r<this.content.length;){let i=this.content[r];if(i instanceof mt.Choice||i instanceof Mt.Gather){let s=i.indentationDepth-1;if(s>this.baseIndentIndex){let o=r;for(;r<this.content.length;){let h=(0, gt.asOrNull)(this.content[r],mt.Choice)||(0, gt.asOrNull)(this.content[r],Mt.Gather);if(h!==null&&h.indentationDepth-1<=this.baseIndentIndex)break;r+=1;}let u=r-o,l=this.content.slice(o,o+u);this.content.splice(o,u);let c=new n(l,s);this.InsertContent(o,c),r=o;}}r+=1;}},this.DetermineBaseIndentationFromContent=r=>{for(let i of r)if(i instanceof mt.Choice||i instanceof Mt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new ex.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let r of this.content)if(r instanceof mt.Choice||r instanceof Mt.Gather)this.AddRuntimeForWeavePoint(r);else if(r instanceof n){let i=r;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(r.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=r=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=r.runtimeContainer;if(r.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let s of this.looseEnds){let o=s;if(o instanceof Mt.Gather&&o.indentationDepth==r.indentationDepth)continue;let u=null;if(o instanceof No.Divert)u=o.runtimeObject;else {u=new tx.Divert;let l=o;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new ix.GatherPointToResolve(u,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=r=>{if(r instanceof Mt.Gather)this.AddRuntimeForGather(r);else if(r instanceof mt.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Mt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=r;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(r)&&(this.looseEnds.push(r),(0, gt.asOrNull)(r,mt.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=r;},this.AddRuntimeForNestedWeave=r=>{this.AddGeneralRuntimeContent(r.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=r=>{if(r!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(r);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(r);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let r=null,i=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, gt.asOrNull)(s,n);o&&(!a&&r===null&&(r=o),a&&i===null&&(i=o)),(s instanceof Rd.Sequence||s instanceof To.Conditional)&&(a=true);}if(!(r===null&&i===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],u=false;if(a){if(o instanceof mt.Choice&&r!==null)r.ReceiveLooseEnd(o),u=true;else if(!(o instanceof mt.Choice)){let l=r||i;l!==null&&(l.ReceiveLooseEnd(o),u=true);}}else r?.hasOwnProperty("ReceiveLooseEnd")&&r.ReceiveLooseEnd(o),u=true;u&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=r=>{this.looseEnds.push(r);},this.WeavePointNamed=r=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(r);return i||null},this.IsGlobalDeclaration=r=>{let i=(0, gt.asOrNull)(r,ux.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, gt.asOrNull)(r,QO.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=r=>{let i=[],a=r;if(a.content!==null)for(let u of a.content)this.IsGlobalDeclaration(u)||i.push(u);let s=(0, gt.asOrNull)(a.parent,n);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let u=o+1;u<s.content.length;u+=1){let l=s.content[u];if(!this.IsGlobalDeclaration(l)){if(l instanceof mt.Choice||l instanceof Mt.Gather||l instanceof n)break;i.push(l);}}return i},this.ValidateTermination=r=>{if(this.lastParsedSignificantObject instanceof fv.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let s=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(s,a,r);}else {for(let a of this.content)if(a instanceof mt.Choice||a instanceof No.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,r);}},this.BadNestedTerminationHandler=r=>{let i=null;for(let s=r.parent;s!==null;s=s.parent)if(s instanceof Rd.Sequence||s instanceof To.Conditional){i=(0, gt.asOrNull)(s,To.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(mt.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,r);},this.ValidateFlowOfObjectsTerminates=(r,i,a)=>{let s=false,o=i;for(let u of r){if(u.Find(No.Divert)(c=>!c.isThread&&!c.isTunnel&&!c.isFunctionCall&&!(c.parent instanceof nx.DivertTarget))!==null&&(s=true),u.Find(ox.TunnelOnwards)()!=null){s=true;break}o=u;}if(!s){if(o instanceof fv.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=r=>{if(r.content===null)return true;for(let i=r.content.length-1;i>=0;--i){let a=(0, gt.asOrNull)(r.content[i],No.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let r=[];for(let i of this.ancestry){let a=(0, gt.asOrNull)(i,rx.FlowBase);if(a)r.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let s of r){let o=s.ContentWithNameAtLevel(i);if(o&&o!==a){let u=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(u,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let r=this.parent;r!==null;r=r.parent)if(r instanceof Rd.Sequence||r instanceof To.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};Fo.Weave=$d;});var vd=S(ko=>{Object.defineProperty(ko,"__esModule",{value:true});ko.ConditionalSingleBranch=void 0;var pv=ye(),Io=Ve(),mv=Lt(),lx=de(),cx=jt(),hx=fe(),dx=Cn(),fx=Kn(),px=ne(),jd=class extends lx.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let a=(0, px.asOrNull)(i,dx.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new pv.Container,r=this.matchingEquality&&!this.isElse;if(r&&t.AddContent(Io.ControlCommand.Duplicate()),this._conditionalDivert=new mv.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(Io.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(cx.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(Io.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new hx.StringValue(`
23
- `),0),(r||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Io.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new mv.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new pv.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new fx.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};ko.ConditionalSingleBranch=jd;});var yv=S(Vo=>{Object.defineProperty(Vo,"__esModule",{value:true});Vo.CustomFlags=void 0;var gv;(function(n){n[n.ParsingString=1]="ParsingString",n[n.TagActive=2]="TagActive";})(gv||(Vo.CustomFlags=gv={}));});var vv=S(Ro=>{Object.defineProperty(Ro,"__esModule",{value:true});Ro.DebugMetadata=void 0;var Ld=class n{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new n;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumber<e.startLineNumber?(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>e.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<e.endLineNumber?(t.endLineNumber=e.endLineNumber,t.endCharacterNumber=e.endCharacterNumber):(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=Math.max(this.endCharacterNumber,e.endCharacterNumber)),t}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};Ro.DebugMetadata=Ld;});var Cv=S($o=>{Object.defineProperty($o,"__esModule",{value:true});$o.ExternalDeclaration=void 0;var mx=de(),qd=class extends mx.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};$o.ExternalDeclaration=qd;});var bv=S(jo=>{Object.defineProperty(jo,"__esModule",{value:true});jo.FlowDecl=void 0;var Bd=class{constructor(e,t,r){this.name=e,this.args=t,this.isFunction=r;}};jo.FlowDecl=Bd;});var Md=S(Lo=>{Object.defineProperty(Lo,"__esModule",{value:true});Lo.Wrap=void 0;var gx=de(),Wd=class extends gx.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};Lo.Wrap=Wd;});var _v=S(qo=>{Object.defineProperty(qo,"__esModule",{value:true});qo.Glue=void 0;var yx=Md(),Gd=class extends yx.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};qo.Glue=Gd;});var Wo=S(Bo=>{Object.defineProperty(Bo,"__esModule",{value:true});Bo.Glue=void 0;var vx=Ze(),Jd=class extends vx.InkObject{toString(){return "Glue"}};Bo.Glue=Jd;});var Ev=S(Mo=>{Object.defineProperty(Mo,"__esModule",{value:true});Mo.IncDecExpression=void 0;var Cx=uo(),Sv=ft(),bx=qt(),_x=jt(),Sx=fe(),Ex=yn(),wx=Lr(),Dx=Kn(),zd=class extends Sv.Expression{constructor(e,t,r){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new wx.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new Sx.IntValue(1)),i.AddContent(_x.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new Ex.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,a;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof Sv.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!r):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let r=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(r.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=r.isGlobal,!(this.parent instanceof Dx.Weave)&&!(this.parent instanceof bx.FlowBase)&&!(this.parent instanceof Cx.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Mo.IncDecExpression=zd;});var Ud=S(Go=>{Object.defineProperty(Go,"__esModule",{value:true});Go.IncludedFile=void 0;var Ax=de(),Hd=class extends Ax.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Go.IncludedFile=Hd;});var wv=S(Jo=>{Object.defineProperty(Jo,"__esModule",{value:true});Jo.InfixOperator=void 0;var Kd=class{constructor(e,t,r){this.type=e,this.precedence=t,this.requireWhitespace=r,this.toString=()=>this.type;}};Jo.InfixOperator=Kd;});var Yd=S(zo=>{Object.defineProperty(zo,"__esModule",{value:true});zo.Knot=void 0;var Px=qt(),Dv=Vr(),Xd=class extends Px.FlowBase{get flowLevel(){return Dv.FlowLevel.Knot}constructor(e,t,r,i){super(e,t,r,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let r in this.subFlowsByName){let i=t.ContentWithNameAtLevel(r,Dv.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(r),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(s,a);}}}};zo.Knot=Xd;});var Av=S(Ho=>{Object.defineProperty(Ho,"__esModule",{value:true});Ho.List=void 0;var Ox=ft(),xx=et(),Tx=et(),Nx=fe(),Zd=class extends Ox.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var r,i;let a=new xx.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((r=s?.name)===null||r===void 0?void 0:r.split("."))||[],u=null,l="";o.length>1?(u=o[0],l=o[1]):l=o[0];let c=this.story.ResolveListItem(u,l,this);if(c===null)u===null?this.Error(`Could not find list definition that contains item '${s}'`):this.Error(`Could not find list item ${s}`);else {if(c.parent==null){this.Error(`Could not find list definition for item ${s}`);return}u||(u=((i=c.parent.identifier)===null||i===void 0?void 0:i.name)||null);let h=new Tx.InkListItem(u,c.name||null);a.has(h.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(h,c.seriesValue);}}t.AddContent(new Nx.ListValue(a));};}get typeName(){return "List"}};Ho.List=Zd;});var ef=S(Uo=>{Object.defineProperty(Uo,"__esModule",{value:true});Uo.ListElementDefinition=void 0;var Fx=de(),Ix=Qt(),Qd=class extends Fx.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,r=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=r,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,Ix.SymbolType.ListItem);}};Uo.ListElementDefinition=Qd;});var tf=S(Ko=>{Object.defineProperty(Ko,"__esModule",{value:true});Ko.StatementLevel=void 0;var Pv;(function(n){n[n.InnerBlock=0]="InnerBlock",n[n.Stitch=1]="Stitch",n[n.Knot=2]="Knot",n[n.Top=3]="Top";})(Pv||(Ko.StatementLevel=Pv={}));});var rf=S(Xo=>{Object.defineProperty(Xo,"__esModule",{value:true});Xo.Stitch=void 0;var kx=qt(),Vx=Vr(),nf=class extends kx.FlowBase{get flowLevel(){return Vx.FlowLevel.Stitch}constructor(e,t,r,i){super(e,t,r,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};Xo.Stitch=nf;});var Zo=S(Yo=>{Object.defineProperty(Yo,"__esModule",{value:true});Yo.Tag=void 0;var Rx=Ze(),sf=class extends Rx.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Yo.Tag=sf;});var of=S(Qo=>{Object.defineProperty(Qo,"__esModule",{value:true});Qo.Choice=void 0;var $x=Ye(),jx=ke(),Lx=Ze(),af=class n extends Lx.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, jx.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new $x.Path(e);}Clone(){let e=new n;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};Qo.Choice=af;});var lf=S(eu=>{Object.defineProperty(eu,"__esModule",{value:true});eu.ListDefinitionsOrigin=void 0;var qx=et(),Bx=fe(),Wx=ke(),uf=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[r,i]of t.items){let a=qx.InkListItem.fromSerializedKey(r),s=new Bx.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,s),this._allUnambiguousListValueCache.set(a.fullName,s);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let r=this._lists.get(e);return r?{result:r,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, Wx.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};eu.ListDefinitionsOrigin=uf;});var Wr=S(iu=>{Object.defineProperty(iu,"__esModule",{value:true});iu.JsonSerialisation=void 0;var tu=ye(),nt=fe(),Ov=Wo(),K=Ve(),Br=zn(),xv=Lt(),Tv=ka(),cf=Lr(),Nv=yn(),hf=jt(),Fv=Jn(),Iv=Zo(),Mx=Ye(),kv=of(),Gx=Fd(),Jx=lf(),nu=et(),ve=ne(),Xn=ke(),ru=class n{static JArrayToRuntimeObjList(e,t=false){let r=e.length;t&&r--;let i=[];for(let a=0;a<r;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, Xn.throwNullException)("runtimeObj");i.push(o);}return i}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[r,i]of t)e.WritePropertyStart(r),this.WriteRuntimeObject(e,i),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let r of t)this.WriteRuntimeObject(e,r);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[r,i]of t)e.WriteIntProperty(r,i);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let r=(0, ve.asOrNull)(t,tu.Container);if(r){this.WriteRuntimeContainer(e,r);return}let i=(0, ve.asOrNull)(t,xv.Divert);if(i){let y="->";i.isExternal?y="x()":i.pushesToStack&&(i.stackPushType==Br.PushPopType.Function?y="f()":i.stackPushType==Br.PushPopType.Tunnel&&(y="->t->"));let E;i.hasVariableTarget?E=i.variableDivertName:E=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(y,E),i.hasVariableTarget&&e.WriteProperty("var",true),i.isConditional&&e.WriteProperty("c",true),i.externalArgs>0&&e.WriteIntProperty("exArgs",i.externalArgs),e.WriteObjectEnd();return}let a=(0, ve.asOrNull)(t,Tv.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, ve.asOrNull)(t,nt.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, ve.asOrNull)(t,nt.IntValue);if(o){e.WriteInt(o.value);return}let u=(0, ve.asOrNull)(t,nt.FloatValue);if(u){e.WriteFloat(u.value);return}let l=(0, ve.asOrNull)(t,nt.StringValue);if(l){l.isNewline?e.Write(`
24
- `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(l.value),e.WriteStringEnd());return}let c=(0, ve.asOrNull)(t,nt.ListValue);if(c){this.WriteInkList(e,c);return}let h=(0, ve.asOrNull)(t,nt.DivertTargetValue);if(h){if(e.WriteObjectStart(),h.value===null)return (0, Xn.throwNullException)("divTargetVal.value");e.WriteProperty("^->",h.value.componentsString),e.WriteObjectEnd();return}let f=(0, ve.asOrNull)(t,nt.VariablePointerValue);if(f){e.WriteObjectStart(),e.WriteProperty("^var",f.value),e.WriteIntProperty("ci",f.contextIndex),e.WriteObjectEnd();return}if((0, ve.asOrNull)(t,Ov.Glue)){e.Write("<>");return}let g=(0, ve.asOrNull)(t,K.ControlCommand);if(g){e.Write(n._controlCommandNames[g.commandType]);return}let m=(0, ve.asOrNull)(t,hf.NativeFunctionCall);if(m){let y=m.name;y=="^"&&(y="L^"),e.Write(y);return}let C=(0, ve.asOrNull)(t,cf.VariableReference);if(C){e.WriteObjectStart();let y=C.pathStringForCount;y!=null?e.WriteProperty("CNT?",y):e.WriteProperty("VAR?",C.name),e.WriteObjectEnd();return}let b=(0, ve.asOrNull)(t,Nv.VariableAssignment);if(b){e.WriteObjectStart();let y=b.isGlobal?"VAR=":"temp=";e.WriteProperty(y,b.variableName),b.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, ve.asOrNull)(t,Fv.Void)){e.Write("void");return}let d=(0, ve.asOrNull)(t,Iv.Tag);if(d){e.WriteObjectStart(),e.WriteProperty("#",d.text),e.WriteObjectEnd();return}let _=(0, ve.asOrNull)(t,kv.Choice);if(_){this.WriteChoice(e,_);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let r in e)if(e.hasOwnProperty(r)){let i=this.JTokenToRuntimeObject(e[r]);if(i===null)return (0, Xn.throwNullException)("inkObject");t.set(r,i);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let r in e)e.hasOwnProperty(r)&&t.set(r,parseInt(e[r]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return nt.Value.Create(e);if(typeof e=="string"){let t=e.toString(),r=/^([0-9]+.[0-9]+f)$/.exec(t);if(r)return new nt.FloatValue(parseFloat(r[0]));let i=t[0];if(i=="^")return new nt.StringValue(t.substring(1));if(i==`
25
- `&&t.length==1)return new nt.StringValue(`
26
- `);if(t=="<>")return new Ov.Glue;for(let a=0;a<n._controlCommandNames.length;++a){let s=n._controlCommandNames[a];if(t==s)return new K.ControlCommand(a)}if(t=="L^"&&(t="^"),hf.NativeFunctionCall.CallExistsWithName(t))return hf.NativeFunctionCall.CallWithName(t);if(t=="->->")return K.ControlCommand.PopTunnel();if(t=="~ret")return K.ControlCommand.PopFunction();if(t=="void")return new Fv.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,r;if(t["^->"])return r=t["^->"],new nt.DivertTargetValue(new Mx.Path(r.toString()));if(t["^var"]){r=t["^var"];let c=new nt.VariablePointerValue(r.toString());return "ci"in t&&(r=t.ci,c.contextIndex=parseInt(r)),c}let i=false,a=false,s=Br.PushPopType.Function,o=false;if((r=t["->"])?i=true:(r=t["f()"])?(i=true,a=true,s=Br.PushPopType.Function):(r=t["->t->"])?(i=true,a=true,s=Br.PushPopType.Tunnel):(r=t["x()"])&&(i=true,o=true,a=false,s=Br.PushPopType.Function),i){let c=new xv.Divert;c.pushesToStack=a,c.stackPushType=s,c.isExternal=o;let h=r.toString();return (r=t.var)?c.variableDivertName=h:c.targetPathString=h,c.isConditional=!!t.c,o&&(r=t.exArgs)&&(c.externalArgs=parseInt(r)),c}if(r=t["*"]){let c=new Tv.ChoicePoint;return c.pathStringOnChoice=r.toString(),(r=t.flg)&&(c.flags=parseInt(r)),c}if(r=t["VAR?"])return new cf.VariableReference(r.toString());if(r=t["CNT?"]){let c=new cf.VariableReference;return c.pathStringForCount=r.toString(),c}let u=false,l=false;if((r=t["VAR="])?(u=true,l=true):(r=t["temp="])&&(u=true,l=false),u){let c=r.toString(),h=!t.re,f=new Nv.VariableAssignment(c,h);return f.isGlobal=l,f}if(t["#"]!==void 0)return r=t["#"],new Iv.Tag(r.toString());if(r=t.list){let c=r,h=new nu.InkList;if(r=t.origins){let f=r;h.SetInitialOriginNames(f);}for(let f in c)if(c.hasOwnProperty(f)){let p=c[f],g=new nu.InkListItem(f),m=parseInt(p);h.Add(g,m);}return new nt.ListValue(h)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,r){return JSON.stringify(e,(i,a)=>t?.some(s=>s===i)?void 0:a,r)}static WriteRuntimeContainer(e,t,r=false){if(e.WriteArrayStart(),t===null)return (0, Xn.throwNullException)("container");for(let u of t.content)this.WriteRuntimeObject(e,u);let i=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!r,o=i!=null||a>0||s;if(o&&e.WriteObjectStart(),i!=null)for(let[u,l]of i){let c=u,h=(0, ve.asOrNull)(l,tu.Container);e.WritePropertyStart(c),this.WriteRuntimeContainer(e,h,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),s&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new tu.Container;t.content=this.JArrayToRuntimeObjList(e,true);let r=e[e.length-1];if(r!=null){let i=new Map;for(let a in r)if(a=="#f")t.countFlags=parseInt(r[a]);else if(a=="#n")t.name=r[a].toString();else {let s=this.JTokenToRuntimeObject(r[a]),o=(0, ve.asOrNull)(s,tu.Container);o&&(o.name=a),i.set(a,s);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new kv.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t.isInvisibleDefault=!!e.isInvisibleDefault,t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),e.WriteProperty("isInvisibleDefault",t.isInvisibleDefault),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let r of t.tags)e.Write(r);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let r=t.value;if(r===null)return (0, Xn.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of r){let s=nu.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, Xn.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(s.originName?s.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(s.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),r.Count==0&&r.originNames!=null&&r.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of r.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let r of e.lists){let i={};for(let[a,s]of r.items){let o=nu.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Xn.throwNullException)("item.itemName");i[o.itemName]=s;}t[r.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,r=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),s=t[i],o=new Map;for(let l in s)if(t.hasOwnProperty(i)){let c=s[l];o.set(l,parseInt(c));}let u=new Gx.ListDefinition(a,o);r.push(u);}return new Jx.ListDefinitionsOrigin(r)}};iu.JsonSerialisation=ru;ru._controlCommandNames=(()=>{let n=[];n[K.ControlCommand.CommandType.EvalStart]="ev",n[K.ControlCommand.CommandType.EvalOutput]="out",n[K.ControlCommand.CommandType.EvalEnd]="/ev",n[K.ControlCommand.CommandType.Duplicate]="du",n[K.ControlCommand.CommandType.PopEvaluatedValue]="pop",n[K.ControlCommand.CommandType.PopFunction]="~ret",n[K.ControlCommand.CommandType.PopTunnel]="->->",n[K.ControlCommand.CommandType.BeginString]="str",n[K.ControlCommand.CommandType.EndString]="/str",n[K.ControlCommand.CommandType.NoOp]="nop",n[K.ControlCommand.CommandType.ChoiceCount]="choiceCnt",n[K.ControlCommand.CommandType.Turns]="turn",n[K.ControlCommand.CommandType.TurnsSince]="turns",n[K.ControlCommand.CommandType.ReadCount]="readc",n[K.ControlCommand.CommandType.Random]="rnd",n[K.ControlCommand.CommandType.SeedRandom]="srnd",n[K.ControlCommand.CommandType.VisitIndex]="visit",n[K.ControlCommand.CommandType.SequenceShuffleIndex]="seq",n[K.ControlCommand.CommandType.StartThread]="thread",n[K.ControlCommand.CommandType.Done]="done",n[K.ControlCommand.CommandType.End]="end",n[K.ControlCommand.CommandType.ListFromInt]="listInt",n[K.ControlCommand.CommandType.ListRange]="range",n[K.ControlCommand.CommandType.ListRandom]="lrnd",n[K.ControlCommand.CommandType.BeginTag]="#",n[K.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<K.ControlCommand.CommandType.TOTAL_VALUES;++e)if(n[e]==null)throw new Error("Control command not accounted for in serialisation");return n})();});var pf=S(rs=>{Object.defineProperty(rs,"__esModule",{value:true});rs.CallStack=void 0;var df=zn(),Vv=Ye(),zx=is(),Rv=Wr(),Hx=fe(),Ux=Mn(),ts=zi(),Kx=Ii(),$v=Tr(),ff=ke(),ns=class n{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){Kx.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=ts.Pointer.Null,arguments[0]instanceof zx.Story){let e=arguments[0];this._startOfRoot=ts.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new n.Thread),this._threads[0].callstack.push(new n.Element(df.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let r=e.threads;for(let i of r){let a=i,s=new n.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=ts.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let r of this._threads)r.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==df.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,r=0){let i=new n.Element(e,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=t,i.functionStartInOutputStream=r,this.callStack.push(i);}CanPop(e=null){return this.canPop?e==null?true:this.currentElement.type==e:false}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let r=this.callStack[t-1],i=(0, $v.tryGetValueFromMap)(r.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,r,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!r&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, $v.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&Hx.ListValue.RetainListOriginsForAssignment(s.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(r=>{if(r.threadIndex==e)return r});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new Ux.StringBuilder;for(let t=0;t<this._threads.length;t++){let r=this._threads[t],i=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
27
- `,t+1,this._threads.length,i?"(current) ":"");for(let a=0;a<r.callstack.length;a++){r.callstack[a].type==df.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=r.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, ff.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};rs.CallStack=ns;(function(n){class e{constructor(i,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}n.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=ts.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let s=i.callstack;for(let u of s){let l=u,c=parseInt(l.type),h=ts.Pointer.Null,f,p=l.cPath;if(typeof p<"u"){f=p.toString();let b=a.ContentAtPath(new Vv.Path(f));if(h.container=b.container,h.index=parseInt(l.idx),b.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+f+". Has the story changed since this save data was created?");b.approximate&&(h.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"', so it was approximated to '"+h.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let g=!!l.exp,m=new e(c,h,g),C=l.temp;typeof C<"u"?m.temporaryVariables=Rv.JsonSerialisation.JObjectToDictionaryRuntimeObjs(C):m.temporaryVariables.clear(),this.callstack.push(m);}let o=i.previousContentObject;if(typeof o<"u"){let u=new Vv.Path(o.toString());this.previousPointer=a.PointerAtPath(u);}}}Copy(){let i=new t;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, ff.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",a.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",a.currentPointer.index);}i.WriteProperty("exp",a.inExpressionEvaluation),i.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),Rv.JsonSerialisation.WriteDictionaryRuntimeObjs(i,a.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, ff.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}n.Thread=t;})(ns||(rs.CallStack=ns={}));});var Lv=S(au=>{Object.defineProperty(au,"__esModule",{value:true});au.VariablesState=void 0;var xe=fe(),Xx=Vi(),jv=Wr(),Re=ne(),ss=Tr(),bn=ke();function Yx(){return class{}}var su=class n extends Yx(){variableChangedEvent(e,t){for(let r of this.variableChangedEventCallbacks)r(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let r=this._globalVariables.get(t);this.variableChangedEvent(t,r);}if(this.patch!=null)for(let t of this.patch.changedVariables){let r=this.patch.TryGetGlobal(t,null);r.exists&&e.set(t,r);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,r]of e)this.variableChangedEvent(t,r);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let r=null;return this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists)?r.result.valueObject:(r=this._globalVariables.get(e),typeof r>"u"&&(r=this._defaultGlobalVariables.get(e)),typeof r<"u"?r.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new Xx.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let r=xe.Value.Create(t);if(r==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,r);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,s){return a in i?i[a]=s:i.$(a,s),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,a){return {enumerable:!0,configurable:!0,value:i.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, bn.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,r]of this._defaultGlobalVariables){let i=e[t];if(typeof i<"u"){let a=jv.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, bn.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,r);}}WriteJson(e){e.WriteObjectStart();for(let[t,r]of this._globalVariables){let i=t,a=r;if(n.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let s=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(i),jv.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, bn.throwNullException)("obj1");if(t===null)return (0, bn.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let r=(0, Re.asOrNull)(e,xe.BoolValue);if(r!==null)return r.value===(0, Re.asOrThrows)(t,xe.BoolValue).value;let i=(0, Re.asOrNull)(e,xe.IntValue);if(i!==null)return i.value===(0, Re.asOrThrows)(t,xe.IntValue).value;let a=(0, Re.asOrNull)(e,xe.FloatValue);if(a!==null)return a.value===(0, Re.asOrThrows)(t,xe.FloatValue).value;let s=(0, Re.asOrNull)(e,xe.Value),o=(0, Re.asOrNull)(t,xe.Value);if(s!==null&&o!==null)return (0, Re.isEquatable)(s.valueObject)&&(0, Re.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let r=this.GetRawVariableWithName(e,t),i=(0, Re.asOrNull)(r,xe.VariablePointerValue);return i!==null&&(r=this.ValueAtVariablePointer(i)),r}TryGetDefaultVariableValue(e){let t=(0, ss.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let r=null;if(t==0||t==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(e,null),i.exists)||(i=(0, ss.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, ss.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, bn.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return r=this._callStack.GetTemporaryVariableWithName(e,t),r}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let r=e.variableName;if(r===null)return (0, bn.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(r),e.isNewDeclaration){let s=(0, Re.asOrNull)(t,xe.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, Re.asOrNull)(this.GetRawVariableWithName(r,i),xe.VariablePointerValue),s!=null&&(r=s.variableName,i=s.contextIndex,a=i==0);while(s!=null)}a?this.SetGlobal(r,t):this._callStack.SetTemporaryVariable(r,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let r=(0, Re.asOrThrows)(e,xe.ListValue),i=(0, Re.asOrThrows)(t,xe.ListValue);r.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}SetGlobal(e,t){let r=null;if(this.patch===null&&(r=(0, ss.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists||(r=(0, ss.tryGetValueFromMap)(this._globalVariables,e,null))),xe.ListValue.RetainListOriginsForAssignment(r.result,t),e===null)return (0, bn.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&r!==null&&t!==r.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, bn.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let r=this.GetRawVariableWithName(e.variableName,t),i=(0, Re.asOrNull)(r,xe.VariablePointerValue);return i??new xe.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};au.VariablesState=su;su.dontSaveDefaultValues=true;});var gf=S(ou=>{Object.defineProperty(ou,"__esModule",{value:true});ou.PRNG=void 0;var mf=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};ou.PRNG=mf;});var qv=S(uu=>{Object.defineProperty(uu,"__esModule",{value:true});uu.StatePatch=void 0;var yf=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:true}:{result:t,exists:false}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:true}:{result:t,exists:false}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:true}:{result:t,exists:false}}};uu.StatePatch=yf;});var vf=S(os=>{Object.defineProperty(os,"__esModule",{value:true});os.SimpleJson=void 0;var as=class n{static TextToDictionary(e){return new n.Reader(e).ToDictionary()}static TextToArray(e){return new n.Reader(e).ToArray()}};os.SimpleJson=as;(function(n){class e{constructor(i){if(JSON.parse("0",(s,o,u)=>u!=null)){let s=(o,u,l)=>Number.isInteger(u)&&l.source.endsWith(".0")?l.source+"f":u;this._rootObject=JSON.parse(i,s);}else {let s=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}n.Reader=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===n.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===n.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===n.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===n.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property)),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===n.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==n.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===n.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===n.Writer.State.None||this.state===n.Writer.State.Property||this.state===n.Writer.State.Array):this.Assert(this.state===n.Writer.State.Property||this.state===n.Writer.State.Array),this.state===n.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===n.Writer.State.Array||this.state===n.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:n.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===n.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===n.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}n.Writer=t,(function(r){(function(s){s[s.None=0]="None",s[s.Object=1]="Object",s[s.Array=2]="Array",s[s.Property=3]="Property",s[s.PropertyName=4]="PropertyName",s[s.String=5]="String";})(r.State||(r.State={}));class a{constructor(o){this.type=n.Writer.State.None,this.childCount=0,this.type=o;}}r.StateElement=a;})(t=n.Writer||(n.Writer={}));})(as||(os.SimpleJson=as={}));});var Wv=S(cu=>{Object.defineProperty(cu,"__esModule",{value:true});cu.Flow=void 0;var Bv=pf(),lu=Wr(),Zx=ke(),Cf=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new Bv.CallStack(t),arguments[2]){let r=arguments[2];this.callStack.SetJsonToken(r.callstack,t),this.outputStream=lu.JsonSerialisation.JArrayToRuntimeObjList(r.outputStream),this.currentChoices=lu.JsonSerialisation.JArrayToRuntimeObjList(r.currentChoices);let i=r.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",r=>this.callStack.WriteJson(r)),e.WriteProperty("outputStream",r=>lu.JsonSerialisation.WriteListRuntimeObjs(r,this.outputStream));let t=false;for(let r of this.currentChoices){if(r.threadAtGeneration===null)return (0, Zx.throwNullException)("c.threadAtGeneration");r.originalThreadIndex=r.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(r.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(r.originalThreadIndex),r.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",r=>{r.WriteArrayStart();for(let i of this.currentChoices)lu.JsonSerialisation.WriteChoice(r,i);r.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let r of this.currentChoices){let i=this.callStack.ThreadWithIndex(r.originalThreadIndex);if(i!==null)r.threadAtGeneration=i.Copy();else {let a=e[`${r.originalThreadIndex}`];r.threadAtGeneration=new Bv.CallStack.Thread(a,t);}}}};cu.Flow=Cf;});var Jv=S(du=>{Object.defineProperty(du,"__esModule",{value:true});du.StoryState=void 0;var Qx=pf(),eT=Lv(),we=fe(),_n=zn(),tT=Zo(),bf=Wo(),Mv=Ye(),We=Ve(),_f=Mn(),Sn=Wr(),nT=gf(),rT=Jn(),Mr=zi(),us=Tr(),_e=ne(),iT=Ii(),yt=ke(),sT=is(),aT=qv(),Gv=vf(),hu=Wv(),oT=et(),Sf=class n{ToJson(e=false){let t=new Gv.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=Gv.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let r=this.story.ContentAtPath(new Mv.Path(e)).container;if(r===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(r,0),t.exists)return t.result}return t=(0, us.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, yt.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(e,0);if(i.exists)return i.result}let t=e.path.toString(),r=(0, us.tryGetValueFromMap)(this._visitCounts,t,null);return r.exists?r.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let i=this.VisitCountForContainer(e);i++,this._patch.SetVisitCount(e,i);return}let t=e.path.toString(),r=(0, us.tryGetValueFromMap)(this._visitCounts,t,null);r.exists?this._visitCounts.set(t,r.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(e,0);if(i.exists)return this.currentTurnIndex-i.result}let t=e.path.toString(),r=(0, us.tryGetValueFromMap)(this._turnIndices,t,0);return r.exists?this.currentTurnIndex-r.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, yt.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, yt.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new _f.StringBuilder,t=false;for(let r of this.outputStream){let i=(0, _e.asOrNull)(r,we.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, _e.asOrNull)(r,We.ControlCommand);a!==null&&(a.commandType==We.ControlCommand.CommandType.BeginTag?t=true:a.commandType==We.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new _f.StringBuilder,r=-1,i=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&r==-1&&(r=a),o||(s!=`
21
+ `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};Ua.CommentEliminator=Qh;});var Xa=_(Ka=>{Object.defineProperty(Ka,"__esModule",{value:true});Ka.Conditional=void 0;var EO=ve(),Zy=Re(),DO=pe(),ed=class extends DO.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let r=new EO.Container;this.initialCondition&&r.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let a=i.runtimeObject;r.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&r.AddContent(Zy.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Zy.ControlCommand.NoOp(),r.AddContent(this._reJoinTarget),r},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let r of this.branches){if(!r.returnDivert)throw new Error;r.returnDivert.targetPath=t;}super.ResolveReferences(e);}};Ka.Conditional=ed;});var Sn=_(Ya=>{Object.defineProperty(Ya,"__esModule",{value:true});Ya.Text=void 0;var AO=pe(),OO=fe(),td=class extends AO.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new OO.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Ya.Text=td;});var Qa=_(Za=>{Object.defineProperty(Za,"__esModule",{value:true});Za.ConstantDeclaration=void 0;var PO=pe(),xO=tn(),nd=class extends PO.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,xO.SymbolType.Var);}};Za.ConstantDeclaration=nd;});var jr=_(eo=>{Object.defineProperty(eo,"__esModule",{value:true});eo.FlowLevel=void 0;var Qy;(function(n){n[n.Story=0]="Story",n[n.Knot=1]="Knot",n[n.Stitch=2]="Stitch",n[n.WeavePoint=3]="WeavePoint";})(Qy||(eo.FlowLevel=Qy={}));});var Xi=_(to=>{Object.defineProperty(to,"__esModule",{value:true});to.Gather=void 0;var TO=ve(),NO=pe(),FO=tn(),rd=class extends NO.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let r=new TO.Container;if(r.name=this.name,this.story.countAllVisits&&(r.visitsShouldBeCounted=true),r.countingAtStartOnly=true,this.content)for(let i of this.content)r.AddContent(i.runtimeObject);return r},this.toString=()=>{var r,i;return `- ${!((r=this.identifier)===null||r===void 0)&&r.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,FO.SymbolType.SubFlowAndWeave);}};to.Gather=rd;});var Xn=_(ro=>{Object.defineProperty(ro,"__esModule",{value:true});ro.Path=void 0;var no=re(),ev=Wt(),$r=jr(),IO=Yn(),id=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?$r.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(no.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===$r.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=r=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(r);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=r=>{let i=this.firstComponent,a=r;for(;a;){let s=a===r,o=this.GetChildFromContext(a,i,null,s);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=r=>{let i=r;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let s=this.components[a].name,o,u=(0, no.asOrNull)(i,ev.FlowBase);if(u!==null?o=u.flowLevel+1:o=$r.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,s,o),i===null)break}return i},this.GetChildFromContext=(r,i,a,s=false)=>{let o=a===null,u=(0, no.asOrNull)(r,IO.Weave);if(i&&u!==null&&(o||a===$r.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, no.asOrNull)(r,ev.FlowBase);if(i&&l!==null){let c=s||l.flowLevel===$r.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,a,c)}return null},Object.values($r.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};ro.Path=id;});var od=_(io=>{Object.defineProperty(io,"__esModule",{value:true});io.ReturnType=void 0;var kO=pe(),VO=ve(),sd=Re(),RO=Hn(),ad=class extends kO.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new VO.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(sd.ControlCommand.EvalStart()),t.AddContent(new RO.Void),t.AddContent(sd.ControlCommand.EvalEnd())),t.AddContent(sd.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};io.ReturnType=ad;});var Yi=_(so=>{Object.defineProperty(so,"__esModule",{value:true});so.ClosestFlowBase=void 0;function jO(n){let e=n.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}so.ClosestFlowBase=jO;});var oo=_(ao=>{Object.defineProperty(ao,"__esModule",{value:true});ao.Identifier=void 0;var ud=class n{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new n("DONE")}};ao.Identifier=ud;});var Wt=_(uo=>{Object.defineProperty(uo,"__esModule",{value:true});uo.FlowBase=void 0;var $O=Rr(),ld=qr(),LO=Lr(),Mt=jr(),qO=Xi(),BO=pe(),WO=Xn(),MO=od(),GO=ve(),JO=Bt(),zO=bn(),cd=tn(),HO=Yn(),UO=Yi(),KO=oo(),tv=re(),hd=class n extends BO.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,r=null,i=false,a=false){super(),this.isFunction=i,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(s,o)=>{var u,l;let c=[],h=[];this._subFlowsByName=new Map;for(let f of s){let g=(0, tv.asOrNull)(f,n);g?(this._firstChildFlow===null&&(this._firstChildFlow=g),h.push(f),!((u=g.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=g.identifier)===null||l===void 0?void 0:l.name,g)):c.push(f);}o&&c.push(new qO.Gather(null,1),new ld.Divert(new WO.Path(KO.Identifier.Done())));let p=[];return c.length>0&&(this._rootWeave=new HO.Weave(c,0),p.push(this._rootWeave)),h.length>0&&p.push(...h),p},this.ResolveVariableWithName=(s,o)=>{var u;let l={},c=o===null?this:(0, UO.ClosestFlowBase)(o);if(c){if(c.args!==null){for(let h of c.args)if(((u=h.identifier)===null||u===void 0?void 0:u.name)===s)return l.found=true,l.isArgument=true,l.ownerFlow=c,l}if(c!==this.story&&c.variableDeclarations.has(s))return l.found=true,l.ownerFlow=c,l.isTemporary=true,l}return this.story.variableDeclarations.has(s)?(l.found=true,l.ownerFlow=this.story,l.isGlobal=true,l):(l.found=false,l)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let u=this.variableDeclarations.get(o),l="";u.debugMetadata&&(l=` (${u.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${l}`,s,false);return}this.variableDeclarations.set(s.variableName,s);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,s]of this._subFlowsByName)s.hasOwnProperty("ResolveWeavePointNaming")&&s.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var s;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===Mt.FlowLevel.Knot||this.flowLevel===Mt.FlowLevel.Stitch)&&(o=this.Find(MO.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let u=new GO.Container;u.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(u.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(u);let l=0;for(;this.content!==null&&l<this.content.length;){let c=this.content[l];if(c instanceof n){let h=c,p=h.runtimeObject;l===0&&!h.hasParameters&&this.flowLevel===Mt.FlowLevel.Knot&&(this._startingSubFlowDivert=new JO.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=p);let f=p,g=u.namedContent.get(f.name)||null;if(g){let m=`${this.GetType()} already contains flow named '${f.name}' (at ${g.debugMetadata})`;this.Error(m,h);}u.AddToNamedContentOnly(f);}else c&&u.AddContent(c.runtimeObject);l+=1;}return this.flowLevel!==Mt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),u},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let u=this.args.length-1;u>=0;--u){let l=((o=this.args[u].identifier)===null||o===void 0?void 0:o.name)||null,c=new zO.VariableAssignment(l,true);s.AddContent(c);}},this.ContentWithNameAtLevel=(s,o=null,u=false)=>{var l;if((o===this.flowLevel||o===null)&&s===((l=this.identifier)===null||l===void 0?void 0:l.name))return this;if(o===Mt.FlowLevel.WeavePoint||o===null){let h=null;if(this._rootWeave&&(h=this._rootWeave.WeavePointNamed(s),h))return h;if(o===Mt.FlowLevel.WeavePoint)return u?this.DeepSearchForAnyLevelContent(s):null}if(o!==null&&o<this.flowLevel)return null;let c=this._subFlowsByName.get(s)||null;return c&&(o===null||o===c.flowLevel)?c:u?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,Mt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,u]of this._subFlowsByName){let l=u.ContentWithNameAtLevel(s,null,true);if(l)return l}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==Mt.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[u,l]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${u}' within the function '${this.identifier}'`,l);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(ld.Divert)();for(let u of s)!u.isFunctionCall&&!(u.parent instanceof LO.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let o=this._rootWeave.FindAll($O.Choice)();for(let u of o)this.Error(`Functions may not contain choices, but saw '${u}'`,u);},this.WarningInTermination=s=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";s.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let u=(0, tv.asOrNull)(s,ld.Divert);u&&u.isTunnel&&(o+=` When final tunnel to '${u.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=r,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,r;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,cd.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((t=this.args[i].identifier)===null||t===void 0?void 0:t.name)==((r=this.args[a].identifier)===null||r===void 0?void 0:r.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==Mt.FlowLevel.Story){let i=this.flowLevel===Mt.FlowLevel.Knot?cd.SymbolType.Knot:cd.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};uo.FlowBase=hd;});var co=_(lo=>{Object.defineProperty(lo,"__esModule",{value:true});lo.ContentList=void 0;var XO=ve(),YO=pe(),ZO=Sn(),QO=re(),dd=class extends YO.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let r=this.content.length-1;r>=0;--r){let i=(0, QO.asOrNull)(this.content[r],ZO.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(r,1);else break}},this.GenerateRuntimeObject=()=>{let r=new XO.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&r.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(r),r},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};lo.ContentList=dd;});var Br=_(ho=>{Object.defineProperty(ho,"__esModule",{value:true});ho.VariableReference=void 0;var eP=et(),tP=Qe(),pd=class extends eP.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new tP.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};ho.VariableReference=pd;});var Wr=_(po=>{Object.defineProperty(po,"__esModule",{value:true});po.VariableReference=void 0;var nP=co(),rP=mt(),nv=Wt(),iP=Xn(),sP=Br(),aP=Yn(),oP=oo(),rv=re(),fd=class extends rP.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(rv.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new oP.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=t=>{let r=this.story.constants.get(this.name);if(r){r.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new sP.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",a="";this.path.length===1?i=this.path[0]:(a=this.path[0],i=this.path[1]),this.story.ResolveListItem(a,i,this)&&(this.isListItemReference=true);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new iP.Path(this.pathIdentifiers),r=t.ResolveFromContext(this);if(r){if(!r.containerForCounting)throw new Error;if(r.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=r.runtimePath,this._runtimeVarRef.name=null;let i=(0, rv.asOrNull)(r,nv.FlowBase);i&&i.isFunction&&(this.parent instanceof aP.Weave||this.parent instanceof nP.ContentList||this.parent instanceof nv.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${t}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};po.VariableReference=fd;});var Zi=_(yo=>{Object.defineProperty(yo,"__esModule",{value:true});yo.FunctionCall=void 0;var Gt=Re(),uP=qr(),lP=Lr(),cP=mt(),hP=nt(),dP=fe(),mo=qt(),iv=Ta(),pP=Xn(),fP=fe(),mP=Wr(),fo=re(),go=class n extends cP.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(e,t){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=r=>{let i=this.story.ResolveList(this.name),a=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),r.AddContent(Gt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),r.AddContent(Gt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, fo.asOrNull)(this.args[0],lP.DivertTarget),o=(0, fo.asOrNull)(this.args[0],mP.VariableReference);if(this.args.length!==1||s===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}s?(this._divertTargetToCount=s,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(r)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(r)),this.isTurnsSince?r.AddContent(Gt.ControlCommand.TurnsSince()):r.AddContent(Gt.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let s=0;s<this.args.length;s+=1){let o=(0, fo.asOrNull)(this.args[s],iv.NumberExpression);if(o&&!o.isInt()){let u=s===0?"minimum":"maximum";this.Error(`RANDOM's ${u} parameter should be an integer`);}this.args[s].GenerateIntoContainer(r);}r.AddContent(Gt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, fo.asOrNull)(this.args[0],iv.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(r),r.AddContent(Gt.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let s=0;s<this.args.length;s+=1)this.args[s].GenerateIntoContainer(r);r.AddContent(Gt.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(r),r.AddContent(Gt.ControlCommand.ListRandom());else if(mo.NativeFunctionCall.CallExistsWithName(this.name)){let s=mo.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${n.name} should take ${s.numberOfParameters} parameter`;s.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(r);r.AddContent(mo.NativeFunctionCall.CallWithName(this.name));}else if(i!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)r.AddContent(new fP.StringValue(this.name)),this.args[0].GenerateIntoContainer(r),r.AddContent(Gt.ControlCommand.ListFromInt());else {let s=new hP.InkList;s.SetInitialOriginName(this.name),r.AddContent(new dP.ListValue(s));}else r.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&r.AddContent(Gt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let r=this.args.join(", ");return `${this.name}(${r})`},this._proxyDivert=new uP.Divert(new pP.Path(e),t),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,r=t.runtimeDivert.variableDivertName!=null;if(r){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let i=t.targetContent;if(i===null)r||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${n.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};yo.FunctionCall=go;go.IsBuiltIn=n=>mo.NativeFunctionCall.CallExistsWithName(n)?true:n==="CHOICE_COUNT"||n==="TURNS_SINCE"||n==="TURNS"||n==="RANDOM"||n==="SEED_RANDOM"||n==="LIST_VALUE"||n==="LIST_RANDOM"||n==="READ_COUNT";});var gd=_(vo=>{Object.defineProperty(vo,"__esModule",{value:true});vo.MultipleConditionExpression=void 0;var gP=mt(),yP=qt(),md=class extends gP.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let r=true;for(let i of this.subExpressions)i.GenerateIntoContainer(t),r||t.AddContent(yP.NativeFunctionCall.CallWithName("&&")),r=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};vo.MultipleConditionExpression=md;});var Lr=_(bo=>{Object.defineProperty(bo,"__esModule",{value:true});bo.DivertTarget=void 0;var vP=qh(),bP=Rr(),CP=Xa(),SP=Cd(),_P=fe(),yd=mt(),wP=Wt(),sv=Zi(),EP=gd(),av=Wr(),vd=re(),bd=class n extends yd.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new _P.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let r=(0, vd.asOrNull)(t,n);if(!r||!this.divert.target||!r.divert.target)return false;let i=this.divert.target.dotSeparatedComponents,a=r.divert.target.dotSeparatedComponents;return i===a},this.divert=this.AddContent(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof yd.Expression;){let i=false,a=false,s=t.parent;if(s instanceof vP.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof n||o.leftExpression instanceof av.VariableReference)&&(o.rightExpression instanceof n||o.rightExpression instanceof av.VariableReference)||(i=true),a=true;}else if(s instanceof sv.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof yd.Expression||s instanceof EP.MultipleConditionExpression||s instanceof bP.Choice&&s.condition===t||s instanceof CP.Conditional||s instanceof SP.ConditionalSingleBranch)&&(i=true,a=true);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;t=s;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let r=this.divert.targetContent;if(r!==null){let i=r.containerForCounting;if(i!==null){let s=(0, vd.asOrNull)(this.parent,sv.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, vd.asOrNull)(r,wP.FlowBase);if(a!=null&&a.args!==null)for(let s of a.args)s.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${s.identifier}').`);}}};bo.DivertTarget=bd;});var qr=_(Co=>{Object.defineProperty(Co,"__esModule",{value:true});Co.Divert=void 0;var DP=ve(),Qi=Re(),AP=Bt(),Sd=Lr(),_d=Wt(),OP=Zi(),PP=pe(),ov=Xn(),xP=Qe(),uv=Un(),TP=fe(),lv=Wr(),NP=Yi(),es=re(),wd=class extends PP.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return Qi.ControlCommand.End();if(this.isDone)return Qi.ControlCommand.Done();this.runtimeDivert=new AP.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let r=this.args!==null&&this.args.length>0;if(r||this.isFunctionCall||this.isTunnel||this.isThread){let i=new DP.Container;if(r){this.isFunctionCall||i.AddContent(Qi.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let s=0;s<this.args.length;++s){let o=this.args[s],u=null;if(a&&s<a.length&&(u=a[s]),u&&u.isByReference){let l=(0, es.asOrNull)(o,lv.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${o}`);break}let c=new ov.Path(l.pathIdentifiers);if(c.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${c.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let p=new TP.VariablePointerValue(l.name);i.AddContent(p);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Qi.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Qi.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?uv.PushPopType.Function:uv.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let r=this.PathAsVariableName();if(r!==null){let i=(0, es.asOrNull)((0, NP.ClosestFlowBase)(this),_d.FlowBase);if(i){let a=i.ResolveVariableWithName(r,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var u;return ((u=o.identifier)===null||u===void 0?void 0:u.name)==r});s&&!s.isDivertTarget&&this.Error(`Since '${s.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${s.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=r;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let r=0;if(this.args!==null&&this.args.length>0&&(r=this.args.length),this.targetContent===null)return;let i=(0, es.asOrNull)(this.targetContent,_d.FlowBase);if(r===0&&(i===null||!i.hasParameters))return;if(i===null&&r>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&r>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof Sd.DivertTarget){r>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==r){let s;r===0?s="but there weren't any passed to it":r<a?s=`but only got ${r}`:s=`but got ${r}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=i.args[s],u=this.args[s];if(o.isDivertTarget){let l=(0, es.asOrNull)(u,lv.VariableReference);if(!(u instanceof Sd.DivertTarget)&&l===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${u}`,u);else if(l){let c=new ov.Path(l.pathIdentifiers);c.ResolveFromContext(l)&&this.Error(`Passing read count of '${c.dotSeparatedComponents}' instead of a divert target. You probably meant '${c}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=r=>{let i=this.target?this.target.firstComponent:null,a=r.externals.get(i);if(!a)throw new Error("external not found");let s=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==s&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${s} but got ${o}`);},this.toString=()=>{let r="";if(this.target!==null)r+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(r+=" ->"),this.isFunctionCall&&(r+=" ()"),r},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, es.asOrNull)(this.targetContent,_d.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof Sd.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let r=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=OP.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new xP.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!r&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,r=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,r):super.Error(`Divert ${e}`,t,r);}};Co.Divert=wd;});var cv=_(So=>{Object.defineProperty(So,"__esModule",{value:true});So.GatherPointToResolve=void 0;var Ed=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};So.GatherPointToResolve=Ed;});var hv=_(_o=>{Object.defineProperty(_o,"__esModule",{value:true});_o.SequenceDivertToResolve=void 0;var Dd=class{constructor(e,t){this.divert=e,this.targetContent=t;}};_o.SequenceDivertToResolve=Dd;});var Ad=_(wo=>{Object.defineProperty(wo,"__esModule",{value:true});wo.SequenceType=void 0;var dv;(function(n){n[n.Stopping=1]="Stopping",n[n.Cycle=2]="Cycle",n[n.Shuffle=4]="Shuffle",n[n.Once=8]="Once";})(dv||(wo.SequenceType=dv={}));});var xd=_(Ao=>{Object.defineProperty(Ao,"__esModule",{value:true});Ao.Sequence=void 0;var pv=ve(),Pt=Re(),Od=Bt(),ts=fe(),Eo=qt(),FP=pe(),IP=hv(),Do=Ad(),kP=Yn(),Pd=class extends FP.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let r=new pv.Container;r.visitsShouldBeCounted=true,r.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],r.AddContent(Pt.ControlCommand.EvalStart()),r.AddContent(Pt.ControlCommand.VisitIndex());let i=(this.sequenceType&Do.SequenceType.Once)>0,a=(this.sequenceType&Do.SequenceType.Cycle)>0,s=(this.sequenceType&Do.SequenceType.Stopping)>0,o=(this.sequenceType&Do.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),s||i?(r.AddContent(new ts.IntValue(u-1)),r.AddContent(Eo.NativeFunctionCall.CallWithName("MIN"))):a&&(r.AddContent(new ts.IntValue(this.sequenceElements.length)),r.AddContent(Eo.NativeFunctionCall.CallWithName("%"))),o){let c=Pt.ControlCommand.NoOp();if(i||s){let p=s?this.sequenceElements.length-1:this.sequenceElements.length;r.AddContent(Pt.ControlCommand.Duplicate()),r.AddContent(new ts.IntValue(p)),r.AddContent(Eo.NativeFunctionCall.CallWithName("=="));let f=new Od.Divert;f.isConditional=true,r.AddContent(f),this.AddDivertToResolve(f,c);}let h=this.sequenceElements.length;s&&(h-=1),r.AddContent(new ts.IntValue(h)),r.AddContent(Pt.ControlCommand.SequenceShuffleIndex()),(i||s)&&r.AddContent(c);}r.AddContent(Pt.ControlCommand.EvalEnd());let l=Pt.ControlCommand.NoOp();for(let c=0;c<u;c+=1){r.AddContent(Pt.ControlCommand.EvalStart()),r.AddContent(Pt.ControlCommand.Duplicate()),r.AddContent(new ts.IntValue(c)),r.AddContent(Eo.NativeFunctionCall.CallWithName("==")),r.AddContent(Pt.ControlCommand.EvalEnd());let h=new Od.Divert;h.isConditional=true,r.AddContent(h);let p;c<this.sequenceElements.length?p=this.sequenceElements[c].runtimeObject:p=new pv.Container,p.name=`s${c}`,p.InsertContent(Pt.ControlCommand.PopEvaluatedValue(),0);let f=new Od.Divert;p.AddContent(f),r.AddToNamedContentOnly(p),this.AddDivertToResolve(h,p),this.AddDivertToResolve(f,l);}return r.AddContent(l),r},this.AddDivertToResolve=(r,i)=>{this._sequenceDivertsToResolve.push(new IP.SequenceDivertToResolve(r,i));},this.sequenceType=t,this.sequenceElements=[];for(let r of e){let i=r.content,a=null;i===null||i.length===0?a=r:a=new kP.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};Ao.Sequence=Pd;});var Nd=_(Oo=>{Object.defineProperty(Oo,"__esModule",{value:true});Oo.TunnelOnwards=void 0;var VP=ve(),ns=Re(),RP=Bt(),jP=fe(),$P=pe(),LP=Hn(),qP=re(),BP=Br(),Td=class extends $P.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new VP.Container;if(e.AddContent(ns.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),r=t;if(r){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let u=0;u<r.content.length;u+=1){let l=r.content[u];l&&(s==-1&&l.commandType===ns.ControlCommand.CommandType.EvalStart?s=u:l.commandType===ns.ControlCommand.CommandType.EvalEnd&&(o=u));}for(let u=s+1;u<o;u+=1){let l=r.content[u];l.parent=null,e.AddContent(r.content[u]);}}}let i=(0, qP.asOrNull)(t,RP.Divert);if(i!=null&&i.hasVariableTarget){let a=new BP.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new jP.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new LP.Void);return e.AddContent(ns.ControlCommand.EvalEnd()),e.AddContent(ns.ControlCommand.PopTunnel()),e},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};Oo.TunnelOnwards=Td;});var kd=_(Po=>{Object.defineProperty(Po,"__esModule",{value:true});Po.ListDefinition=void 0;var Fd=nt(),Id=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let r=new Fd.InkListItem(this.name,e);this._items.set(r.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?false:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[r,i]of this._itemNameToValues)if(i==e)return t=new Fd.InkListItem(this.name,r),{result:t,exists:true};return t=Fd.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let r=this._itemNameToValues.get(e.itemName);return r?{result:r,exists:true}:{result:0,exists:false}}};Po.ListDefinition=Id;});var To=_(xo=>{Object.defineProperty(xo,"__esModule",{value:true});xo.ListDefinition=void 0;var WP=nt(),MP=nt(),GP=kd(),JP=fe(),zP=pe(),HP=tn(),Vd=class extends zP.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let r of this.itemDefinitions)t.has(r.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${r.name}'`):t.set(r.name,r.seriesValue);return new GP.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=r=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(r)||null},this.GenerateRuntimeObject=()=>{var r,i;let a=new WP.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new MP.InkListItem(((r=this.identifier)===null||r===void 0?void 0:r.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new JP.ListValue(a)};let t=1;for(let r of this.itemDefinitions)r.explicitValue!==null&&(t=r.explicitValue),r.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,HP.SymbolType.List);}};xo.ListDefinition=Vd;});var jd=_(No=>{Object.defineProperty(No,"__esModule",{value:true});No.VariableAssignment=void 0;var UP=ve(),KP=Yi(),XP=To(),YP=pe(),fv=tn(),ZP=bn(),QP=Wr(),ex=re(),Rd=class extends YP.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:r,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, KP.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new UP.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new ZP.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!r,i instanceof XP.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?fv.SymbolType.Var:fv.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, ex.asOrNull)(this.expression,QP.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};No.VariableAssignment=Rd;});var Yn=_(ko=>{Object.defineProperty(ko,"__esModule",{value:true});ko.Weave=void 0;var mv=fa(),yt=Rr(),Fo=Xa(),tx=Qa(),nx=ve(),Io=qr(),rx=Bt(),ix=Lr(),sx=Wt(),Jt=Xi(),ax=cv(),ox=pe(),$d=xd(),ux=Sn(),lx=Nd(),cx=jd(),vt=re(),Ld=class n extends ox.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let r=this.content.length-1;r>=0;--r){e=this.content[r];let i=(0, vt.asOrNull)(e,ux.Text);if(!(i&&i.text===`
22
+ `)&&!this.IsGlobalDeclaration(e))break}let t=(0, vt.asOrNull)(e,n);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var r,i,a;let s=[...this.FindAll(Jt.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(yt.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let u=this.namedWeavePoints.get(((r=o.identifier)===null||r===void 0?void 0:r.name)||"");if(u){let l=u instanceof Jt.Gather?"gather":"choice",c=u;this.Error(`A ${l} with the same label name '${o.name}' already exists in this context on line ${c.debugMetadata?c.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((i=o.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let r=0;for(;r<this.content.length;){let i=this.content[r];if(i instanceof yt.Choice||i instanceof Jt.Gather){let s=i.indentationDepth-1;if(s>this.baseIndentIndex){let o=r;for(;r<this.content.length;){let h=(0, vt.asOrNull)(this.content[r],yt.Choice)||(0, vt.asOrNull)(this.content[r],Jt.Gather);if(h!==null&&h.indentationDepth-1<=this.baseIndentIndex)break;r+=1;}let u=r-o,l=this.content.slice(o,o+u);this.content.splice(o,u);let c=new n(l,s);this.InsertContent(o,c),r=o;}}r+=1;}},this.DetermineBaseIndentationFromContent=r=>{for(let i of r)if(i instanceof yt.Choice||i instanceof Jt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new nx.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let r of this.content)if(r instanceof yt.Choice||r instanceof Jt.Gather)this.AddRuntimeForWeavePoint(r);else if(r instanceof n){let i=r;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(r.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=r=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=r.runtimeContainer;if(r.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let s of this.looseEnds){let o=s;if(o instanceof Jt.Gather&&o.indentationDepth==r.indentationDepth)continue;let u=null;if(o instanceof Io.Divert)u=o.runtimeObject;else {u=new rx.Divert;let l=o;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new ax.GatherPointToResolve(u,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=r=>{if(r instanceof Jt.Gather)this.AddRuntimeForGather(r);else if(r instanceof yt.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Jt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=r;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(r)&&(this.looseEnds.push(r),(0, vt.asOrNull)(r,yt.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=r;},this.AddRuntimeForNestedWeave=r=>{this.AddGeneralRuntimeContent(r.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=r=>{if(r!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(r);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(r);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let r=null,i=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, vt.asOrNull)(s,n);o&&(!a&&r===null&&(r=o),a&&i===null&&(i=o)),(s instanceof $d.Sequence||s instanceof Fo.Conditional)&&(a=true);}if(!(r===null&&i===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],u=false;if(a){if(o instanceof yt.Choice&&r!==null)r.ReceiveLooseEnd(o),u=true;else if(!(o instanceof yt.Choice)){let l=r||i;l!==null&&(l.ReceiveLooseEnd(o),u=true);}}else r?.hasOwnProperty("ReceiveLooseEnd")&&r.ReceiveLooseEnd(o),u=true;u&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=r=>{this.looseEnds.push(r);},this.WeavePointNamed=r=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(r);return i||null},this.IsGlobalDeclaration=r=>{let i=(0, vt.asOrNull)(r,cx.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, vt.asOrNull)(r,tx.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=r=>{let i=[],a=r;if(a.content!==null)for(let u of a.content)this.IsGlobalDeclaration(u)||i.push(u);let s=(0, vt.asOrNull)(a.parent,n);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let u=o+1;u<s.content.length;u+=1){let l=s.content[u];if(!this.IsGlobalDeclaration(l)){if(l instanceof yt.Choice||l instanceof Jt.Gather||l instanceof n)break;i.push(l);}}return i},this.ValidateTermination=r=>{if(this.lastParsedSignificantObject instanceof mv.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let s=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(s,a,r);}else {for(let a of this.content)if(a instanceof yt.Choice||a instanceof Io.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,r);}},this.BadNestedTerminationHandler=r=>{let i=null;for(let s=r.parent;s!==null;s=s.parent)if(s instanceof $d.Sequence||s instanceof Fo.Conditional){i=(0, vt.asOrNull)(s,Fo.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(yt.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,r);},this.ValidateFlowOfObjectsTerminates=(r,i,a)=>{let s=false,o=i;for(let u of r){if(u.Find(Io.Divert)(c=>!c.isThread&&!c.isTunnel&&!c.isFunctionCall&&!(c.parent instanceof ix.DivertTarget))!==null&&(s=true),u.Find(lx.TunnelOnwards)()!=null){s=true;break}o=u;}if(!s){if(o instanceof mv.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=r=>{if(r.content===null)return true;for(let i=r.content.length-1;i>=0;--i){let a=(0, vt.asOrNull)(r.content[i],Io.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let r=[];for(let i of this.ancestry){let a=(0, vt.asOrNull)(i,sx.FlowBase);if(a)r.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let s of r){let o=s.ContentWithNameAtLevel(i);if(o&&o!==a){let u=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(u,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let r=this.parent;r!==null;r=r.parent)if(r instanceof $d.Sequence||r instanceof Fo.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};ko.Weave=Ld;});var Cd=_(Ro=>{Object.defineProperty(Ro,"__esModule",{value:true});Ro.ConditionalSingleBranch=void 0;var gv=ve(),Vo=Re(),yv=Bt(),hx=pe(),dx=qt(),px=fe(),fx=Sn(),mx=Yn(),gx=re(),qd=class extends hx.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let a=(0, gx.asOrNull)(i,fx.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new gv.Container,r=this.matchingEquality&&!this.isElse;if(r&&t.AddContent(Vo.ControlCommand.Duplicate()),this._conditionalDivert=new yv.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(Vo.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(dx.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(Vo.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new px.StringValue(`
23
+ `),0),(r||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Vo.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new yv.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new gv.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new mx.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};Ro.ConditionalSingleBranch=qd;});var bv=_(jo=>{Object.defineProperty(jo,"__esModule",{value:true});jo.CustomFlags=void 0;var vv;(function(n){n[n.ParsingString=1]="ParsingString",n[n.TagActive=2]="TagActive";})(vv||(jo.CustomFlags=vv={}));});var Cv=_($o=>{Object.defineProperty($o,"__esModule",{value:true});$o.DebugMetadata=void 0;var Bd=class n{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new n;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumber<e.startLineNumber?(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>e.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<e.endLineNumber?(t.endLineNumber=e.endLineNumber,t.endCharacterNumber=e.endCharacterNumber):(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=Math.max(this.endCharacterNumber,e.endCharacterNumber)),t}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};$o.DebugMetadata=Bd;});var Sv=_(Lo=>{Object.defineProperty(Lo,"__esModule",{value:true});Lo.ExternalDeclaration=void 0;var yx=pe(),Wd=class extends yx.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};Lo.ExternalDeclaration=Wd;});var _v=_(qo=>{Object.defineProperty(qo,"__esModule",{value:true});qo.FlowDecl=void 0;var Md=class{constructor(e,t,r){this.name=e,this.args=t,this.isFunction=r;}};qo.FlowDecl=Md;});var Jd=_(Bo=>{Object.defineProperty(Bo,"__esModule",{value:true});Bo.Wrap=void 0;var vx=pe(),Gd=class extends vx.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};Bo.Wrap=Gd;});var wv=_(Wo=>{Object.defineProperty(Wo,"__esModule",{value:true});Wo.Glue=void 0;var bx=Jd(),zd=class extends bx.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};Wo.Glue=zd;});var Go=_(Mo=>{Object.defineProperty(Mo,"__esModule",{value:true});Mo.Glue=void 0;var Cx=et(),Hd=class extends Cx.InkObject{toString(){return "Glue"}};Mo.Glue=Hd;});var Dv=_(Jo=>{Object.defineProperty(Jo,"__esModule",{value:true});Jo.IncDecExpression=void 0;var Sx=co(),Ev=mt(),_x=Wt(),wx=qt(),Ex=fe(),Dx=bn(),Ax=Br(),Ox=Yn(),Ud=class extends Ev.Expression{constructor(e,t,r){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new Ax.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new Ex.IntValue(1)),i.AddContent(wx.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new Dx.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,a;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof Ev.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!r):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let r=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(r.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=r.isGlobal,!(this.parent instanceof Ox.Weave)&&!(this.parent instanceof _x.FlowBase)&&!(this.parent instanceof Sx.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Jo.IncDecExpression=Ud;});var Xd=_(zo=>{Object.defineProperty(zo,"__esModule",{value:true});zo.IncludedFile=void 0;var Px=pe(),Kd=class extends Px.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};zo.IncludedFile=Kd;});var Av=_(Ho=>{Object.defineProperty(Ho,"__esModule",{value:true});Ho.InfixOperator=void 0;var Yd=class{constructor(e,t,r){this.type=e,this.precedence=t,this.requireWhitespace=r,this.toString=()=>this.type;}};Ho.InfixOperator=Yd;});var Qd=_(Uo=>{Object.defineProperty(Uo,"__esModule",{value:true});Uo.Knot=void 0;var xx=Wt(),Ov=jr(),Zd=class extends xx.FlowBase{get flowLevel(){return Ov.FlowLevel.Knot}constructor(e,t,r,i){super(e,t,r,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let r in this.subFlowsByName){let i=t.ContentWithNameAtLevel(r,Ov.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(r),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(s,a);}}}};Uo.Knot=Zd;});var Pv=_(Ko=>{Object.defineProperty(Ko,"__esModule",{value:true});Ko.List=void 0;var Tx=mt(),Nx=nt(),Fx=nt(),Ix=fe(),ep=class extends Tx.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var r,i;let a=new Nx.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((r=s?.name)===null||r===void 0?void 0:r.split("."))||[],u=null,l="";o.length>1?(u=o[0],l=o[1]):l=o[0];let c=this.story.ResolveListItem(u,l,this);if(c===null)u===null?this.Error(`Could not find list definition that contains item '${s}'`):this.Error(`Could not find list item ${s}`);else {if(c.parent==null){this.Error(`Could not find list definition for item ${s}`);return}u||(u=((i=c.parent.identifier)===null||i===void 0?void 0:i.name)||null);let h=new Fx.InkListItem(u,c.name||null);a.has(h.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(h,c.seriesValue);}}t.AddContent(new Ix.ListValue(a));};}get typeName(){return "List"}};Ko.List=ep;});var np=_(Xo=>{Object.defineProperty(Xo,"__esModule",{value:true});Xo.ListElementDefinition=void 0;var kx=pe(),Vx=tn(),tp=class extends kx.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,r=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=r,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,Vx.SymbolType.ListItem);}};Xo.ListElementDefinition=tp;});var rp=_(Yo=>{Object.defineProperty(Yo,"__esModule",{value:true});Yo.StatementLevel=void 0;var xv;(function(n){n[n.InnerBlock=0]="InnerBlock",n[n.Stitch=1]="Stitch",n[n.Knot=2]="Knot",n[n.Top=3]="Top";})(xv||(Yo.StatementLevel=xv={}));});var sp=_(Zo=>{Object.defineProperty(Zo,"__esModule",{value:true});Zo.Stitch=void 0;var Rx=Wt(),jx=jr(),ip=class extends Rx.FlowBase{get flowLevel(){return jx.FlowLevel.Stitch}constructor(e,t,r,i){super(e,t,r,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};Zo.Stitch=ip;});var eu=_(Qo=>{Object.defineProperty(Qo,"__esModule",{value:true});Qo.Tag=void 0;var $x=et(),ap=class extends $x.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Qo.Tag=ap;});var up=_(tu=>{Object.defineProperty(tu,"__esModule",{value:true});tu.Choice=void 0;var Lx=Qe(),qx=Ve(),Bx=et(),op=class n extends Bx.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, qx.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new Lx.Path(e);}Clone(){let e=new n;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};tu.Choice=op;});var cp=_(nu=>{Object.defineProperty(nu,"__esModule",{value:true});nu.ListDefinitionsOrigin=void 0;var Wx=nt(),Mx=fe(),Gx=Ve(),lp=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[r,i]of t.items){let a=Wx.InkListItem.fromSerializedKey(r),s=new Mx.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,s),this._allUnambiguousListValueCache.set(a.fullName,s);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let r=this._lists.get(e);return r?{result:r,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, Gx.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};nu.ListDefinitionsOrigin=lp;});var Gr=_(au=>{Object.defineProperty(au,"__esModule",{value:true});au.JsonSerialisation=void 0;var ru=ve(),it=fe(),Tv=Go(),X=Re(),Mr=Un(),Nv=Bt(),Fv=Ra(),hp=Br(),Iv=bn(),dp=qt(),kv=Hn(),Vv=eu(),Jx=Qe(),Rv=up(),zx=kd(),Hx=cp(),iu=nt(),be=re(),Zn=Ve(),su=class n{static JArrayToRuntimeObjList(e,t=false){let r=e.length;t&&r--;let i=[];for(let a=0;a<r;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, Zn.throwNullException)("runtimeObj");i.push(o);}return i}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[r,i]of t)e.WritePropertyStart(r),this.WriteRuntimeObject(e,i),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let r of t)this.WriteRuntimeObject(e,r);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[r,i]of t)e.WriteIntProperty(r,i);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let r=(0, be.asOrNull)(t,ru.Container);if(r){this.WriteRuntimeContainer(e,r);return}let i=(0, be.asOrNull)(t,Nv.Divert);if(i){let y="->";i.isExternal?y="x()":i.pushesToStack&&(i.stackPushType==Mr.PushPopType.Function?y="f()":i.stackPushType==Mr.PushPopType.Tunnel&&(y="->t->"));let w;i.hasVariableTarget?w=i.variableDivertName:w=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(y,w),i.hasVariableTarget&&e.WriteProperty("var",true),i.isConditional&&e.WriteProperty("c",true),i.externalArgs>0&&e.WriteIntProperty("exArgs",i.externalArgs),e.WriteObjectEnd();return}let a=(0, be.asOrNull)(t,Fv.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, be.asOrNull)(t,it.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, be.asOrNull)(t,it.IntValue);if(o){e.WriteInt(o.value);return}let u=(0, be.asOrNull)(t,it.FloatValue);if(u){e.WriteFloat(u.value);return}let l=(0, be.asOrNull)(t,it.StringValue);if(l){l.isNewline?e.Write(`
24
+ `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(l.value),e.WriteStringEnd());return}let c=(0, be.asOrNull)(t,it.ListValue);if(c){this.WriteInkList(e,c);return}let h=(0, be.asOrNull)(t,it.DivertTargetValue);if(h){if(e.WriteObjectStart(),h.value===null)return (0, Zn.throwNullException)("divTargetVal.value");e.WriteProperty("^->",h.value.componentsString),e.WriteObjectEnd();return}let p=(0, be.asOrNull)(t,it.VariablePointerValue);if(p){e.WriteObjectStart(),e.WriteProperty("^var",p.value),e.WriteIntProperty("ci",p.contextIndex),e.WriteObjectEnd();return}if((0, be.asOrNull)(t,Tv.Glue)){e.Write("<>");return}let g=(0, be.asOrNull)(t,X.ControlCommand);if(g){e.Write(n._controlCommandNames[g.commandType]);return}let m=(0, be.asOrNull)(t,dp.NativeFunctionCall);if(m){let y=m.name;y=="^"&&(y="L^"),e.Write(y);return}let b=(0, be.asOrNull)(t,hp.VariableReference);if(b){e.WriteObjectStart();let y=b.pathStringForCount;y!=null?e.WriteProperty("CNT?",y):e.WriteProperty("VAR?",b.name),e.WriteObjectEnd();return}let C=(0, be.asOrNull)(t,Iv.VariableAssignment);if(C){e.WriteObjectStart();let y=C.isGlobal?"VAR=":"temp=";e.WriteProperty(y,C.variableName),C.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, be.asOrNull)(t,kv.Void)){e.Write("void");return}let d=(0, be.asOrNull)(t,Vv.Tag);if(d){e.WriteObjectStart(),e.WriteProperty("#",d.text),e.WriteObjectEnd();return}let S=(0, be.asOrNull)(t,Rv.Choice);if(S){this.WriteChoice(e,S);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let r in e)if(e.hasOwnProperty(r)){let i=this.JTokenToRuntimeObject(e[r]);if(i===null)return (0, Zn.throwNullException)("inkObject");t.set(r,i);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let r in e)e.hasOwnProperty(r)&&t.set(r,parseInt(e[r]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return it.Value.Create(e);if(typeof e=="string"){let t=e.toString(),r=/^([0-9]+.[0-9]+f)$/.exec(t);if(r)return new it.FloatValue(parseFloat(r[0]));let i=t[0];if(i=="^")return new it.StringValue(t.substring(1));if(i==`
25
+ `&&t.length==1)return new it.StringValue(`
26
+ `);if(t=="<>")return new Tv.Glue;for(let a=0;a<n._controlCommandNames.length;++a){let s=n._controlCommandNames[a];if(t==s)return new X.ControlCommand(a)}if(t=="L^"&&(t="^"),dp.NativeFunctionCall.CallExistsWithName(t))return dp.NativeFunctionCall.CallWithName(t);if(t=="->->")return X.ControlCommand.PopTunnel();if(t=="~ret")return X.ControlCommand.PopFunction();if(t=="void")return new kv.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,r;if(t["^->"])return r=t["^->"],new it.DivertTargetValue(new Jx.Path(r.toString()));if(t["^var"]){r=t["^var"];let c=new it.VariablePointerValue(r.toString());return "ci"in t&&(r=t.ci,c.contextIndex=parseInt(r)),c}let i=false,a=false,s=Mr.PushPopType.Function,o=false;if((r=t["->"])?i=true:(r=t["f()"])?(i=true,a=true,s=Mr.PushPopType.Function):(r=t["->t->"])?(i=true,a=true,s=Mr.PushPopType.Tunnel):(r=t["x()"])&&(i=true,o=true,a=false,s=Mr.PushPopType.Function),i){let c=new Nv.Divert;c.pushesToStack=a,c.stackPushType=s,c.isExternal=o;let h=r.toString();return (r=t.var)?c.variableDivertName=h:c.targetPathString=h,c.isConditional=!!t.c,o&&(r=t.exArgs)&&(c.externalArgs=parseInt(r)),c}if(r=t["*"]){let c=new Fv.ChoicePoint;return c.pathStringOnChoice=r.toString(),(r=t.flg)&&(c.flags=parseInt(r)),c}if(r=t["VAR?"])return new hp.VariableReference(r.toString());if(r=t["CNT?"]){let c=new hp.VariableReference;return c.pathStringForCount=r.toString(),c}let u=false,l=false;if((r=t["VAR="])?(u=true,l=true):(r=t["temp="])&&(u=true,l=false),u){let c=r.toString(),h=!t.re,p=new Iv.VariableAssignment(c,h);return p.isGlobal=l,p}if(t["#"]!==void 0)return r=t["#"],new Vv.Tag(r.toString());if(r=t.list){let c=r,h=new iu.InkList;if(r=t.origins){let p=r;h.SetInitialOriginNames(p);}for(let p in c)if(c.hasOwnProperty(p)){let f=c[p],g=new iu.InkListItem(p),m=parseInt(f);h.Add(g,m);}return new it.ListValue(h)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,r){return JSON.stringify(e,(i,a)=>t?.some(s=>s===i)?void 0:a,r)}static WriteRuntimeContainer(e,t,r=false){if(e.WriteArrayStart(),t===null)return (0, Zn.throwNullException)("container");for(let u of t.content)this.WriteRuntimeObject(e,u);let i=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!r,o=i!=null||a>0||s;if(o&&e.WriteObjectStart(),i!=null)for(let[u,l]of i){let c=u,h=(0, be.asOrNull)(l,ru.Container);e.WritePropertyStart(c),this.WriteRuntimeContainer(e,h,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),s&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new ru.Container;t.content=this.JArrayToRuntimeObjList(e,true);let r=e[e.length-1];if(r!=null){let i=new Map;for(let a in r)if(a=="#f")t.countFlags=parseInt(r[a]);else if(a=="#n")t.name=r[a].toString();else {let s=this.JTokenToRuntimeObject(r[a]),o=(0, be.asOrNull)(s,ru.Container);o&&(o.name=a),i.set(a,s);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new Rv.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t.isInvisibleDefault=!!e.isInvisibleDefault,t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),e.WriteProperty("isInvisibleDefault",t.isInvisibleDefault),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let r of t.tags)e.Write(r);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let r=t.value;if(r===null)return (0, Zn.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of r){let s=iu.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, Zn.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(s.originName?s.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(s.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),r.Count==0&&r.originNames!=null&&r.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of r.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let r of e.lists){let i={};for(let[a,s]of r.items){let o=iu.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Zn.throwNullException)("item.itemName");i[o.itemName]=s;}t[r.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,r=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),s=t[i],o=new Map;for(let l in s)if(t.hasOwnProperty(i)){let c=s[l];o.set(l,parseInt(c));}let u=new zx.ListDefinition(a,o);r.push(u);}return new Hx.ListDefinitionsOrigin(r)}};au.JsonSerialisation=su;su._controlCommandNames=(()=>{let n=[];n[X.ControlCommand.CommandType.EvalStart]="ev",n[X.ControlCommand.CommandType.EvalOutput]="out",n[X.ControlCommand.CommandType.EvalEnd]="/ev",n[X.ControlCommand.CommandType.Duplicate]="du",n[X.ControlCommand.CommandType.PopEvaluatedValue]="pop",n[X.ControlCommand.CommandType.PopFunction]="~ret",n[X.ControlCommand.CommandType.PopTunnel]="->->",n[X.ControlCommand.CommandType.BeginString]="str",n[X.ControlCommand.CommandType.EndString]="/str",n[X.ControlCommand.CommandType.NoOp]="nop",n[X.ControlCommand.CommandType.ChoiceCount]="choiceCnt",n[X.ControlCommand.CommandType.Turns]="turn",n[X.ControlCommand.CommandType.TurnsSince]="turns",n[X.ControlCommand.CommandType.ReadCount]="readc",n[X.ControlCommand.CommandType.Random]="rnd",n[X.ControlCommand.CommandType.SeedRandom]="srnd",n[X.ControlCommand.CommandType.VisitIndex]="visit",n[X.ControlCommand.CommandType.SequenceShuffleIndex]="seq",n[X.ControlCommand.CommandType.StartThread]="thread",n[X.ControlCommand.CommandType.Done]="done",n[X.ControlCommand.CommandType.End]="end",n[X.ControlCommand.CommandType.ListFromInt]="listInt",n[X.ControlCommand.CommandType.ListRange]="range",n[X.ControlCommand.CommandType.ListRandom]="lrnd",n[X.ControlCommand.CommandType.BeginTag]="#",n[X.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<X.ControlCommand.CommandType.TOTAL_VALUES;++e)if(n[e]==null)throw new Error("Control command not accounted for in serialisation");return n})();});var mp=_(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.CallStack=void 0;var pp=Un(),jv=Qe(),Ux=as(),$v=Gr(),Kx=fe(),Xx=Jn(),rs=Ui(),Yx=Vi(),Lv=Fr(),fp=Ve(),is=class n{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){Yx.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=rs.Pointer.Null,arguments[0]instanceof Ux.Story){let e=arguments[0];this._startOfRoot=rs.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new n.Thread),this._threads[0].callstack.push(new n.Element(pp.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let r=e.threads;for(let i of r){let a=i,s=new n.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=rs.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let r of this._threads)r.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==pp.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,r=0){let i=new n.Element(e,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=t,i.functionStartInOutputStream=r,this.callStack.push(i);}CanPop(e=null){return this.canPop?e==null?true:this.currentElement.type==e:false}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let r=this.callStack[t-1],i=(0, Lv.tryGetValueFromMap)(r.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,r,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!r&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, Lv.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&Kx.ListValue.RetainListOriginsForAssignment(s.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(r=>{if(r.threadIndex==e)return r});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new Xx.StringBuilder;for(let t=0;t<this._threads.length;t++){let r=this._threads[t],i=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
27
+ `,t+1,this._threads.length,i?"(current) ":"");for(let a=0;a<r.callstack.length;a++){r.callstack[a].type==pp.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=r.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, fp.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};ss.CallStack=is;(function(n){class e{constructor(i,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}n.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=rs.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let s=i.callstack;for(let u of s){let l=u,c=parseInt(l.type),h=rs.Pointer.Null,p,f=l.cPath;if(typeof f<"u"){p=f.toString();let C=a.ContentAtPath(new jv.Path(p));if(h.container=C.container,h.index=parseInt(l.idx),C.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+p+". Has the story changed since this save data was created?");C.approximate&&(h.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+p+"', so it was approximated to '"+h.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+p+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let g=!!l.exp,m=new e(c,h,g),b=l.temp;typeof b<"u"?m.temporaryVariables=$v.JsonSerialisation.JObjectToDictionaryRuntimeObjs(b):m.temporaryVariables.clear(),this.callstack.push(m);}let o=i.previousContentObject;if(typeof o<"u"){let u=new jv.Path(o.toString());this.previousPointer=a.PointerAtPath(u);}}}Copy(){let i=new t;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, fp.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",a.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",a.currentPointer.index);}i.WriteProperty("exp",a.inExpressionEvaluation),i.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),$v.JsonSerialisation.WriteDictionaryRuntimeObjs(i,a.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, fp.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}n.Thread=t;})(is||(ss.CallStack=is={}));});var Bv=_(uu=>{Object.defineProperty(uu,"__esModule",{value:true});uu.VariablesState=void 0;var Te=fe(),Zx=ji(),qv=Gr(),je=re(),os=Fr(),_n=Ve();function Qx(){return class{}}var ou=class n extends Qx(){variableChangedEvent(e,t){for(let r of this.variableChangedEventCallbacks)r(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let r=this._globalVariables.get(t);this.variableChangedEvent(t,r);}if(this.patch!=null)for(let t of this.patch.changedVariables){let r=this.patch.TryGetGlobal(t,null);r.exists&&e.set(t,r);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,r]of e)this.variableChangedEvent(t,r);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let r=null;return this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists)?r.result.valueObject:(r=this._globalVariables.get(e),typeof r>"u"&&(r=this._defaultGlobalVariables.get(e)),typeof r<"u"?r.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new Zx.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let r=Te.Value.Create(t);if(r==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,r);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,s){return a in i?i[a]=s:i.$(a,s),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,a){return {enumerable:!0,configurable:!0,value:i.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, _n.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,r]of this._defaultGlobalVariables){let i=e[t];if(typeof i<"u"){let a=qv.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, _n.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,r);}}WriteJson(e){e.WriteObjectStart();for(let[t,r]of this._globalVariables){let i=t,a=r;if(n.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let s=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(i),qv.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, _n.throwNullException)("obj1");if(t===null)return (0, _n.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let r=(0, je.asOrNull)(e,Te.BoolValue);if(r!==null)return r.value===(0, je.asOrThrows)(t,Te.BoolValue).value;let i=(0, je.asOrNull)(e,Te.IntValue);if(i!==null)return i.value===(0, je.asOrThrows)(t,Te.IntValue).value;let a=(0, je.asOrNull)(e,Te.FloatValue);if(a!==null)return a.value===(0, je.asOrThrows)(t,Te.FloatValue).value;let s=(0, je.asOrNull)(e,Te.Value),o=(0, je.asOrNull)(t,Te.Value);if(s!==null&&o!==null)return (0, je.isEquatable)(s.valueObject)&&(0, je.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let r=this.GetRawVariableWithName(e,t),i=(0, je.asOrNull)(r,Te.VariablePointerValue);return i!==null&&(r=this.ValueAtVariablePointer(i)),r}TryGetDefaultVariableValue(e){let t=(0, os.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let r=null;if(t==0||t==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(e,null),i.exists)||(i=(0, os.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, os.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, _n.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return r=this._callStack.GetTemporaryVariableWithName(e,t),r}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let r=e.variableName;if(r===null)return (0, _n.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(r),e.isNewDeclaration){let s=(0, je.asOrNull)(t,Te.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, je.asOrNull)(this.GetRawVariableWithName(r,i),Te.VariablePointerValue),s!=null&&(r=s.variableName,i=s.contextIndex,a=i==0);while(s!=null)}a?this.SetGlobal(r,t):this._callStack.SetTemporaryVariable(r,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let r=(0, je.asOrThrows)(e,Te.ListValue),i=(0, je.asOrThrows)(t,Te.ListValue);r.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}SetGlobal(e,t){let r=null;if(this.patch===null&&(r=(0, os.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists||(r=(0, os.tryGetValueFromMap)(this._globalVariables,e,null))),Te.ListValue.RetainListOriginsForAssignment(r.result,t),e===null)return (0, _n.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&r!==null&&t!==r.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, _n.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let r=this.GetRawVariableWithName(e.variableName,t),i=(0, je.asOrNull)(r,Te.VariablePointerValue);return i??new Te.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};uu.VariablesState=ou;ou.dontSaveDefaultValues=true;});var yp=_(lu=>{Object.defineProperty(lu,"__esModule",{value:true});lu.PRNG=void 0;var gp=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};lu.PRNG=gp;});var Wv=_(cu=>{Object.defineProperty(cu,"__esModule",{value:true});cu.StatePatch=void 0;var vp=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:true}:{result:t,exists:false}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:true}:{result:t,exists:false}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:true}:{result:t,exists:false}}};cu.StatePatch=vp;});var bp=_(ls=>{Object.defineProperty(ls,"__esModule",{value:true});ls.SimpleJson=void 0;var us=class n{static TextToDictionary(e){return new n.Reader(e).ToDictionary()}static TextToArray(e){return new n.Reader(e).ToArray()}};ls.SimpleJson=us;(function(n){class e{constructor(i){if(JSON.parse("0",(s,o,u)=>u!=null)){let s=(o,u,l)=>Number.isInteger(u)&&l.source.endsWith(".0")?l.source+"f":u;this._rootObject=JSON.parse(i,s);}else {let s=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}n.Reader=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===n.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===n.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===n.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===n.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property)),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===n.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==n.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===n.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===n.Writer.State.None||this.state===n.Writer.State.Property||this.state===n.Writer.State.Array):this.Assert(this.state===n.Writer.State.Property||this.state===n.Writer.State.Array),this.state===n.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===n.Writer.State.Array||this.state===n.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:n.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===n.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===n.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}n.Writer=t,(function(r){(function(s){s[s.None=0]="None",s[s.Object=1]="Object",s[s.Array=2]="Array",s[s.Property=3]="Property",s[s.PropertyName=4]="PropertyName",s[s.String=5]="String";})(r.State||(r.State={}));class a{constructor(o){this.type=n.Writer.State.None,this.childCount=0,this.type=o;}}r.StateElement=a;})(t=n.Writer||(n.Writer={}));})(us||(ls.SimpleJson=us={}));});var Gv=_(du=>{Object.defineProperty(du,"__esModule",{value:true});du.Flow=void 0;var Mv=mp(),hu=Gr(),eT=Ve(),Cp=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new Mv.CallStack(t),arguments[2]){let r=arguments[2];this.callStack.SetJsonToken(r.callstack,t),this.outputStream=hu.JsonSerialisation.JArrayToRuntimeObjList(r.outputStream),this.currentChoices=hu.JsonSerialisation.JArrayToRuntimeObjList(r.currentChoices);let i=r.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",r=>this.callStack.WriteJson(r)),e.WriteProperty("outputStream",r=>hu.JsonSerialisation.WriteListRuntimeObjs(r,this.outputStream));let t=false;for(let r of this.currentChoices){if(r.threadAtGeneration===null)return (0, eT.throwNullException)("c.threadAtGeneration");r.originalThreadIndex=r.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(r.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(r.originalThreadIndex),r.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",r=>{r.WriteArrayStart();for(let i of this.currentChoices)hu.JsonSerialisation.WriteChoice(r,i);r.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let r of this.currentChoices){let i=this.callStack.ThreadWithIndex(r.originalThreadIndex);if(i!==null)r.threadAtGeneration=i.Copy();else {let a=e[`${r.originalThreadIndex}`];r.threadAtGeneration=new Mv.CallStack.Thread(a,t);}}}};du.Flow=Cp;});var Hv=_(fu=>{Object.defineProperty(fu,"__esModule",{value:true});fu.StoryState=void 0;var tT=mp(),nT=Bv(),De=fe(),wn=Un(),rT=eu(),Sp=Go(),Jv=Qe(),Ge=Re(),_p=Jn(),En=Gr(),iT=yp(),sT=Hn(),Jr=Ui(),cs=Fr(),_e=re(),aT=Vi(),bt=Ve(),oT=as(),uT=Wv(),zv=bp(),pu=Gv(),lT=nt(),wp=class n{ToJson(e=false){let t=new zv.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=zv.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let r=this.story.ContentAtPath(new Jv.Path(e)).container;if(r===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(r,0),t.exists)return t.result}return t=(0, cs.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, bt.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(e,0);if(i.exists)return i.result}let t=e.path.toString(),r=(0, cs.tryGetValueFromMap)(this._visitCounts,t,null);return r.exists?r.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let i=this.VisitCountForContainer(e);i++,this._patch.SetVisitCount(e,i);return}let t=e.path.toString(),r=(0, cs.tryGetValueFromMap)(this._visitCounts,t,null);r.exists?this._visitCounts.set(t,r.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(e,0);if(i.exists)return this.currentTurnIndex-i.result}let t=e.path.toString(),r=(0, cs.tryGetValueFromMap)(this._turnIndices,t,0);return r.exists?this.currentTurnIndex-r.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, bt.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, bt.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new _p.StringBuilder,t=false;for(let r of this.outputStream){let i=(0, _e.asOrNull)(r,De.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, _e.asOrNull)(r,Ge.ControlCommand);a!==null&&(a.commandType==Ge.ControlCommand.CommandType.BeginTag?t=true:a.commandType==Ge.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new _p.StringBuilder,r=-1,i=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&r==-1&&(r=a),o||(s!=`
28
28
  `&&r>0&&r!=i&&t.Append(" "),r=-1),s==`
29
- `&&(i=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new _f.StringBuilder;for(let r of this.outputStream){let i=(0, _e.asOrNull)(r,We.ControlCommand);if(i!=null){if(i.commandType==We.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(i.commandType==We.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=false;}}else if(e){let a=(0, _e.asOrNull)(r,we.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, _e.asOrNull)(r,tT.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let r=this.CleanOutputWhitespace(t.toString());this._currentTags.push(r),t.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=Mr.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=e,this._currentFlow=new hu.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new eT.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new nT.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Mr.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,r=(0, us.tryGetValueFromMap)(this._namedFlows,e,null);r.exists?t=r.result:(t=new hu.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=true),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, yt.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new n(this.story);if(t._patch=new aT.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new Qx.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let r of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(r.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[r,i]of this._namedFlows)t._namedFlows.set(r,i),t._aliveFlowNamesDirty=true;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,true);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,false);this._patch=null;}}ApplyCountChanges(e,t,r){(r?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,r]of this._namedFlows)e.WriteProperty(t,i=>r.WriteJson(i));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>Sn.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, yt.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Sn.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Sn.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",sT.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,r=t.inkSaveVersion;if(r==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(r)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+r+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let i=t.flows;if(i!=null){let s=i;Object.keys(s).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(s);for(let[u,l]of o){let c=u,h=l,f=new hu.Flow(c,this.story,h);if(Object.keys(s).length===1)this._currentFlow=new hu.Flow(c,this.story,h);else {if(this._namedFlows===null)return (0, yt.throwNullException)("this._namedFlows");this._namedFlows.set(c,f);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let u=t.currentFlowName;this._currentFlow=this._namedFlows.get(u);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=Sn.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Sn.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let s=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Sn.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new Mv.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=Sn.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Sn.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, _e.asOrNull)(e,we.StringValue);if(t!==null){let r=this.TrySplittingHeadTailWhitespace(t);if(r!==null){for(let i of r)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, yt.throwNullException)("single.value");let r=-1,i=-1;for(let c=0;c<t.length;c++){let h=t[c];if(h==`
29
+ `&&(i=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new _p.StringBuilder;for(let r of this.outputStream){let i=(0, _e.asOrNull)(r,Ge.ControlCommand);if(i!=null){if(i.commandType==Ge.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(i.commandType==Ge.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=false;}}else if(e){let a=(0, _e.asOrNull)(r,De.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, _e.asOrNull)(r,rT.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let r=this.CleanOutputWhitespace(t.toString());this._currentTags.push(r),t.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=Jr.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=e,this._currentFlow=new pu.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new nT.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new iT.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Jr.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,r=(0, cs.tryGetValueFromMap)(this._namedFlows,e,null);r.exists?t=r.result:(t=new pu.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=true),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, bt.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new n(this.story);if(t._patch=new uT.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new tT.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let r of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(r.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[r,i]of this._namedFlows)t._namedFlows.set(r,i),t._aliveFlowNamesDirty=true;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,true);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,false);this._patch=null;}}ApplyCountChanges(e,t,r){(r?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,r]of this._namedFlows)e.WriteProperty(t,i=>r.WriteJson(i));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>En.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, bt.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>En.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>En.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",oT.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,r=t.inkSaveVersion;if(r==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(r)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+r+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let i=t.flows;if(i!=null){let s=i;Object.keys(s).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(s);for(let[u,l]of o){let c=u,h=l,p=new pu.Flow(c,this.story,h);if(Object.keys(s).length===1)this._currentFlow=new pu.Flow(c,this.story,h);else {if(this._namedFlows===null)return (0, bt.throwNullException)("this._namedFlows");this._namedFlows.set(c,p);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let u=t.currentFlowName;this._currentFlow=this._namedFlows.get(u);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=En.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=En.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let s=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=En.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new Jv.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=En.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=En.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, _e.asOrNull)(e,De.StringValue);if(t!==null){let r=this.TrySplittingHeadTailWhitespace(t);if(r!==null){for(let i of r)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, bt.throwNullException)("single.value");let r=-1,i=-1;for(let c=0;c<t.length;c++){let h=t[c];if(h==`
30
30
  `)r==-1&&(r=c),i=c;else {if(h==" "||h==" ")continue;break}}let a=-1,s=-1;for(let c=t.length-1;c>=0;c--){let h=t[c];if(h==`
31
- `)a==-1&&(a=c),s=c;else {if(h==" "||h==" ")continue;break}}if(r==-1&&a==-1)return null;let o=[],u=0,l=t.length;if(r!=-1){if(r>0){let c=new we.StringValue(t.substring(0,r));o.push(c);}o.push(new we.StringValue(`
32
- `)),u=i+1;}if(a!=-1&&(l=s),l>u){let c=t.substring(u,l);o.push(new we.StringValue(c));}if(a!=-1&&s>i&&(o.push(new we.StringValue(`
33
- `)),a<t.length-1)){let c=t.length-a-1,h=new we.StringValue(t.substring(a+1,a+1+c));o.push(h);}return o}PushToOutputStreamIndividual(e){let t=(0, _e.asOrNull)(e,bf.Glue),r=(0, _e.asOrNull)(e,we.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(r){let a=-1,s=this.callStack.currentElement;s.type==_n.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let l=this.outputStream.length-1;l>=0;l--){let c=this.outputStream[l],h=c instanceof We.ControlCommand?c:null;if((c instanceof bf.Glue?c:null)!=null){o=l;break}else if(h!=null&&h.commandType==We.ControlCommand.CommandType.BeginString){l>=a&&(a=-1);break}}let u=-1;if(o!=-1&&a!=-1?u=Math.min(a,o):o!=-1?u=o:u=a,u!=-1){if(r.isNewline)i=false;else if(r.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let l=this.callStack.elements;for(let c=l.length-1;c>=0;c--){let h=l[c];if(h.type==_n.PushPopType.Function)h.functionStartInOutputStream=-1;else break}}}else r.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, yt.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let r=this.outputStream[t],i=(0, _e.asOrNull)(r,We.ControlCommand),a=(0, _e.asOrNull)(r,we.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, _e.asOrNull)(this.outputStream[t],we.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 bf.Glue)this.outputStream.splice(e,1);else if(t instanceof We.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof We.ControlCommand);e--){let r=this.outputStream[e];if(r instanceof we.StringValue){if(r.isNewline)return true;if(r.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof we.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, _e.asOrNull)(this.outputStream[e],We.ControlCommand);if(t instanceof We.ControlCommand&&t.commandType==We.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, _e.asOrNull)(e,we.ListValue);if(t){let r=t.value;if(r===null)return (0, yt.throwNullException)("rawList");if(r.originNames!=null){r.origins||(r.origins=[]),r.origins.length=0;for(let i of r.originNames){if(this.story.listDefinitions===null)return (0, yt.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, yt.throwNullException)("StoryState def.result");r.origins.indexOf(a.result)<0&&r.origins.push(a.result);}}}if(e===null)return (0, yt.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, _e.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, _e.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Mr.Pointer.Null,this.previousPointer=Mr.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){iT.Debug.Assert(this.callStack.currentElement.type==_n.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let r=this.outputStream[t],i=(0, _e.asOrNull)(r,we.StringValue),a=(0, _e.asOrNull)(r,We.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==_n.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let r=this.story.PointerAtPath(e);!r.isNull&&r.index==-1&&(r.index=0),this.currentPointer=r,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(_n.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Mr.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 oT.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, _e.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(we.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==_n.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Mr.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=_n.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 r=this.PopEvaluationStack();t===null&&(t=r);}if(this.PopCallStack(_n.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof rT.Void)return null;let r=(0, _e.asOrThrows)(t,we.Value);return r.valueType==we.ValueType.DivertTarget?"-> "+r.valueObject.toString():r.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;}};du.StoryState=Sf;});var zv=S(fu=>{Object.defineProperty(fu,"__esModule",{value:true});fu.Stopwatch=void 0;var Ef=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;}};fu.Stopwatch=Ef;});var Uv=S(pu=>{Object.defineProperty(pu,"__esModule",{value:true});pu.ErrorType=void 0;var Hv;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(Hv||(pu.ErrorType=Hv={}));});var is=S(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.Story=Qn.InkList=void 0;var $e=ye(),wf=Ze(),Df=Wr(),uT=Jv(),j=Ve(),vt=zn(),lT=ka(),cT=of(),Kv=Lt(),N=fe(),Af=Ye(),ls=Jn(),mu=Zo(),hT=yn(),dT=Lr(),fT=jt(),Yn=Vi(),Pf=gf(),Zn=Mn(),pT=lf(),mT=zv(),En=zi(),cs=et(),B=ne(),ee=ke(),Xv=vf(),Yv=Uv(),gT=et();Object.defineProperty(Qn,"InkList",{enumerable:true,get:function(){return gT.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var Gr=class n extends wf.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, ee.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,r=null;if(arguments[0]instanceof $e.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let i=arguments[0];r=Xv.SimpleJson.TextToDictionary(i);}else r=arguments[0];if(t!=null&&(this._listDefinitions=new pT.ListDefinitionsOrigin(t)),this._externals=new Map,r!==null){let i=r,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let s=parseInt(a);if(s>n.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(s<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");s!=n.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${n.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=i.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let u;(u=i.listDefs)&&(this._listDefinitions=Df.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, B.asOrThrows)(Df.JsonSerialisation.JTokenToRuntimeObject(o),$e.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new Xv.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",n.inkVersionCurrent),e.WriteProperty("root",r=>Df.JsonSerialisation.WriteRuntimeContainer(r,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let r of this._listDefinitions.lists){e.WritePropertyStart(r.name),e.WriteObjectStart();for(let[i,a]of r.items){let s=cs.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(s.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new uT.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, ee.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, ee.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new Af.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 r=new mT.Stopwatch;r.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof Yn.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(i||this._asyncContinueActive&&r.ElapsedMilliseconds>e)break}while(this.canContinue);r.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(vt.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(vt.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(a=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let s of this.state.currentErrors)this.onError(s,Yv.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,Yv.ErrorType.Warning);this.ResetErrors();}else {let s=new Zn.StringBuilder;throw s.Append("Ink had "),this.state.hasError&&(s.Append(`${this.state.currentErrors.length}`),s.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&s.Append(" and ")),this.state.hasWarning&&(s.Append(`${this.state.currentWarnings.length}`),s.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&s.Append(" and ")),s.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),s.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new Yn.StoryException(s.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, ee.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, ee.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==n.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==n.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,r,i){if(e===null)return (0, ee.throwNullException)("prevText");if(t===null)return (0, ee.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
34
- `;if(r==i&&e.length==t.length&&a)return n.OutputStateChange.NoChange;if(!a)return n.OutputStateChange.NewlineRemoved;if(i>r)return n.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return n.OutputStateChange.ExtendedBeyondNewline}return n.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new Zn.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 $e.Container?t:null}PointerAtPath(e){if(e.length==0)return En.Pointer.Null;let t=new En.Pointer,r=e.length,i=null;return e.lastComponent===null?(0, ee.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(r=e.length-1,i=this.mainContentContainer.ContentAtPath(e,void 0,r),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&&r>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, ee.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 r=(0, B.asOrNull)(t.Resolve(),$e.Container);for(;r&&(this.VisitContainer(r,true),r.content.length!=0);)t=En.Pointer.StartOf(r),r=(0, B.asOrNull)(t.Resolve(),$e.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=t.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, B.asOrNull)(i,lT.ChoicePoint);if(s){let u=this.ProcessChoice(s);u&&this.state.generatedChoices.push(u),i=null,e=false;}if(i instanceof $e.Container&&(e=false),e){let u=(0, B.asOrNull)(i,N.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new N.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, B.asOrNull)(i,j.ControlCommand);o&&o.commandType==j.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let s=e.Resolve(),o=(0, B.asOrNull)(s,$e.Container)||(0, B.asOrNull)(e.container,$e.Container);for(;o;)this._prevContainers.push(o),o=(0, B.asOrNull)(o.parent,$e.Container);}let r=t.Resolve();if(r==null)return;let i=(0, B.asOrNull)(r.parent,$e.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let s=i.content.length>0&&r==i.content[0]&&a;s||(a=false),this.VisitContainer(i,s),r=i,i=(0, B.asOrNull)(i.parent,$e.Container);}}PopChoiceStringAndTags(e){let t=(0, B.asOrThrows)(this.state.PopEvaluationStack(),N.StringValue);for(;this.state.evaluationStack.length>0&&(0, B.asOrNull)(this.state.PeekEvaluationStack(),mu.Tag)!=null;){let r=(0, B.asOrNull)(this.state.PopEvaluationStack(),mu.Tag);r&&e.push(r.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let r="",i="",a=[];if(e.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(r=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new cT.Choice;return s.targetPath=e.pathOnChoice,s.sourcePath=e.path.toString(),s.isInvisibleDefault=e.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(r+i).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof N.Value){let r=e;if(r instanceof N.DivertTargetValue){let i=r;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 r.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof Kv.Divert){let t=e;if(t.isConditional){let r=this.state.PopEvaluationStack();if(!this.IsTruthy(r))return true}if(t.hasVariableTarget){let r=t.variableDivertName,i=this.state.variablesState.GetVariableWithName(r);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+r+")");else if(!(i instanceof N.DivertTargetValue)){let s=(0, B.asOrNull)(i,N.IntValue),o="Tried to divert to a target from a variable, but the variable ("+r+") didn't contain a divert target, it ";s instanceof N.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, B.asOrThrows)(i,N.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),true;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),true}else if(e instanceof j.ControlCommand){let t=e;switch(t.commandType){case j.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case j.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case j.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let y=this.state.PopEvaluationStack();if(!(y instanceof ls.Void)){let E=new N.StringValue(y.toString());this.state.PushToOutputStream(E);}}break;case j.ControlCommand.CommandType.NoOp:break;case j.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case j.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case j.ControlCommand.CommandType.PopFunction:case j.ControlCommand.CommandType.PopTunnel:let r=t.commandType==j.ControlCommand.CommandType.PopFunction?vt.PushPopType.Function:vt.PushPopType.Tunnel,i=null;if(r==vt.PushPopType.Tunnel){let y=this.state.PopEvaluationStack();i=(0, B.asOrNull)(y,N.DivertTargetValue),i===null&&this.Assert(y instanceof ls.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=r||!this.state.callStack.canPop){let y=new Map;y.set(vt.PushPopType.Function,"function return statement (~ return)"),y.set(vt.PushPopType.Tunnel,"tunnel onwards statement (->->)");let E=y.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(E="end of flow (-> END or choice)");let w="Found "+y.get(r)+", when expected "+E;this.Error(w);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case j.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 j.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case j.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let y=[],E=0;for(let x=this.state.outputStream.length-1;x>=0;--x){let H=this.state.outputStream[x];E++;let be=(0, B.asOrNull)(H,j.ControlCommand);if(be!=null){if(be.commandType==j.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}H instanceof N.StringValue&&y.push(H);}this.state.PopFromOutputStream(E);let w=new Zn.StringBuilder;for(let x of y.reverse())w.Append(x.toString());let P=new mu.Tag(this.state.CleanOutputWhitespace(w.toString()));this.state.PushEvaluationStack(P);}else this.state.PushToOutputStream(t);break}case j.ControlCommand.CommandType.EndString:{let y=[],E=[],w=0;for(let x=this.state.outputStream.length-1;x>=0;--x){let H=this.state.outputStream[x];w++;let be=(0, B.asOrNull)(H,j.ControlCommand);if(be&&be.commandType==j.ControlCommand.CommandType.BeginString)break;H instanceof mu.Tag&&E.push(H),H instanceof N.StringValue&&y.push(H);}this.state.PopFromOutputStream(w);for(let x of E)this.state.PushToOutputStream(x);y=y.reverse();let P=new Zn.StringBuilder;for(let x of y)P.Append(x.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new N.StringValue(P.toString()));break}case j.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new N.IntValue(a));break;case j.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new N.IntValue(this.state.currentTurnIndex+1));break;case j.ControlCommand.CommandType.TurnsSince:case j.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof N.DivertTargetValue)){let y="";s instanceof N.IntValue&&(y=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+y);break}let o=(0, B.asOrThrows)(s,N.DivertTargetValue),u=(0, B.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,$e.Container),l;u!=null?t.commandType==j.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(t.commandType==j.ControlCommand.CommandType.TurnsSince?l=-1:l=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new N.IntValue(l));break;case j.ControlCommand.CommandType.Random:{let y=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue),E=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(E==null||!(E instanceof N.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(y==null||!(y instanceof N.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(y.value===null)return (0, ee.throwNullException)("maxInt.value");if(E.value===null)return (0, ee.throwNullException)("minInt.value");let w=y.value-E.value+1;(!isFinite(w)||w>Number.MAX_SAFE_INTEGER)&&(w=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),w<=0&&this.Error("RANDOM was called with minimum as "+E.value+" and maximum as "+y.value+". The maximum must be larger");let P=this.state.storySeed+this.state.previousRandom,H=new Pf.PRNG(P).next(),be=H%w+E.value;this.state.PushEvaluationStack(new N.IntValue(be)),this.state.previousRandom=H;break}case j.ControlCommand.CommandType.SeedRandom:let c=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(c==null||!(c instanceof N.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(c.value===null)return (0, ee.throwNullException)("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new ls.Void);break;case j.ControlCommand.CommandType.VisitIndex:let h=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new N.IntValue(h));break;case j.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new N.IntValue(f));break;case j.ControlCommand.CommandType.StartThread:break;case j.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=En.Pointer.Null);break;case j.ControlCommand.CommandType.End:this.state.ForceEnd();break;case j.ControlCommand.CommandType.ListFromInt:let p=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue),g=(0, B.asOrThrows)(this.state.PopEvaluationStack(),N.StringValue);if(p===null)throw new Yn.StoryException("Passed non-integer when creating a list element from a numerical value.");let m=null;if(this.listDefinitions===null)return (0, ee.throwNullException)("this.listDefinitions");let C=this.listDefinitions.TryListGetDefinition(g.value,null);if(C.exists){if(p.value===null)return (0, ee.throwNullException)("minInt.value");let y=C.result.TryGetItemWithValue(p.value,cs.InkListItem.Null);y.exists&&(m=new N.ListValue(y.result,p.value));}else throw new Yn.StoryException("Failed to find LIST called "+g.value);m==null&&(m=new N.ListValue),this.state.PushEvaluationStack(m);break;case j.ControlCommand.CommandType.ListRange:let b=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.Value),v=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.Value),d=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.ListValue);if(d===null||v===null||b===null)throw new Yn.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(d.value===null)return (0, ee.throwNullException)("targetList.value");let _=d.value.ListWithSubRange(v.valueObject,b.valueObject);this.state.PushEvaluationStack(new N.ListValue(_));break;case j.ControlCommand.CommandType.ListRandom:{let y=this.state.PopEvaluationStack();if(y===null)throw new Yn.StoryException("Expected list for LIST_RANDOM");let E=y.value,w=null;if(E===null)throw (0, ee.throwNullException)("list");if(E.Count==0)w=new cs.InkList;else {let P=this.state.storySeed+this.state.previousRandom,H=new Pf.PRNG(P).next(),be=H%E.Count,Jt=E.entries();for(let Yf=0;Yf<=be-1;Yf++)Jt.next();let Kr=Jt.next().value,tr={Key:cs.InkListItem.fromSerializedKey(Kr[0]),Value:Kr[1]};if(tr.Key.originName===null)return (0, ee.throwNullException)("randomItem.Key.originName");w=new cs.InkList(tr.Key.originName,this),w.Add(tr.Key,tr.Value),this.state.previousRandom=H;}this.state.PushEvaluationStack(new N.ListValue(w));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof hT.VariableAssignment){let t=e,r=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,r),true}else if(e instanceof dT.VariableReference){let t=e,r=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);r=new N.IntValue(a);}else r=this.state.variablesState.GetVariableWithName(t.name),r==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."),r=new N.IntValue(0));return this.state.PushEvaluationStack(r),true}else if(e instanceof fT.NativeFunctionCall){let t=e,r=this.state.PopEvaluationStack(t.numberOfParameters),i=t.Call(r);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(e,t=true,r=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,r),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==vt.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:
35
- `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(r),this.ChoosePath(new Af.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 r=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(r),r.threadAtGeneration===null)return (0, ee.throwNullException)("choiceToChoose.threadAtGeneration");if(r.targetPath===null)return (0, ee.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=r.threadAtGeneration,this.ChoosePath(r.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],r=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(e,t),this.IfAsyncWeCant("evaluate a function"),e==null)throw new Error("Function is null");if(e==""||e.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(e);if(i==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,t);let s=new Zn.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let u=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,u),r?{returned:u,output:o}:u}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(vt.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let r=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>r?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, ee.throwNullException)("funcName");let r=this._externals.get(e),i=null,a=typeof r<"u";if(a&&!r.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&&!r.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(vt.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=En.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let l=0;l<t;++l){let h=(0, B.asOrThrows)(this.state.PopEvaluationStack(),N.Value).valueObject;s.push(h);}s.reverse();let o=r.function(s),u=null;o!=null?(u=N.Value.Create(o),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof o)):u=new ls.Void,this.state.PushEvaluationStack(u);}BindExternalFunctionGeneral(e,t,r=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:r});}TryCoerce(e){return e}BindExternalFunction(e,t,r=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,i=>{this.Assert(i.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=i.length;s<o;s++)a[s]=this.TryCoerce(i[s]);return t.apply(null,a)},r);}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,r=arguments[1]||new Set;if(arguments[0]instanceof $e.Container&&(e=arguments[0]),arguments[0]instanceof wf.InkObject&&(t=arguments[0]),e===null&&t===null)if(this.ValidateExternalBindings(this._mainContentContainer,r),this._hasValidatedExternals=true,r.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=r.size>1?"s":"",i+=": '",i+=Array.from(r).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,r);}for(let[,i]of e.namedContent)this.ValidateExternalBindings((0, B.asOrNull)(i,wf.InkObject),r);}else if(t!=null){let i=(0, B.asOrNull)(t,Kv.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, ee.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||r.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 r=0,i=e.length;r<i;r++)this.ObserveVariable(e[r],t[r]);}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 r=this._variableObservers.get(t);r!=null&&(r.splice(r.indexOf(e),1),r.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let r=this._variableObservers.keys();for(let i of r){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 r=this._variableObservers.get(e);if(typeof r<"u"){if(!(t instanceof N.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, B.asOrThrows)(t,N.Value);for(let a of r)a(e,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new Af.Path(e),r=this.ContentAtPath(t).container;if(r===null)return (0, ee.throwNullException)("flowContainer");for(;;){let s=r.content[0];if(s instanceof $e.Container)r=s;else break}let i=false,a=null;for(let s of r.content){let o=(0, B.asOrNull)(s,j.ControlCommand);if(o!=null)o.commandType==j.ControlCommand.CommandType.BeginTag?i=true:o.commandType==j.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, B.asOrNull)(s,N.StringValue);u!==null?(a===null&&(a=[]),u.value!==null&&a.push(u.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let e=new Zn.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new Zn.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=En.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(vt.PushPopType.Function)?(this.state.PopCallStack(vt.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new ls.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, ee.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let r=(0, B.asOrNull)(t.container.parent,$e.Container);if(!(r instanceof $e.Container))break;let i=r.content.indexOf(t.container);if(i==-1)break;if(t=new En.Pointer(r,i),t.index++,e=true,t.container===null)return (0, ee.throwNullException)("pointer.container")}return e||(t=En.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 r=t[0];return r.targetPath===null?(0, ee.throwNullException)("choice.targetPath"):r.threadAtGeneration===null?(0, ee.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=r.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(r.targetPath,false),true)}NextSequenceShuffleIndex(){let e=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(!(e instanceof N.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, ee.throwNullException)("seqContainer");if(e.value===null)return (0, ee.throwNullException)("numElementsIntVal.value");let r=e.value,a=(0, B.asOrThrows)(this.state.PopEvaluationStack(),N.IntValue).value;if(a===null)return (0, ee.throwNullException)("seqCount");let s=a/r,o=a%r,u=t.path.toString(),l=0;for(let p=0,g=u.length;p<g;p++)l+=u.charCodeAt(p)||0;let c=l+s+this.state.storySeed,h=new Pf.PRNG(Math.floor(c)),f=[];for(let p=0;p<r;++p)f.push(p);for(let p=0;p<=o;++p){let g=h.next()%f.length,m=f[g];if(f.splice(g,1),p==o)return m}throw new Error("Should never reach here")}Error(e,t=false){let r=new Yn.StoryException(e);throw r.useEndLineNumber=t,r}Warning(e){this.AddError(e,true);}AddError(e,t=false,r=false){let i=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(i!=null){let s=r?i.endLineNumber:i.startLineNumber;e="RUNTIME "+a+": '"+i.fileName+"' line "+s+": "+e;}else this.state.currentPointer.isNull?e="RUNTIME "+a+": "+e:e="RUNTIME "+a+": ("+this.state.currentPointer+"): "+e;this.state.AddError(e,t),t||this.state.ForceEnd();}Assert(e,t=null){if(e==false)throw t==null&&(t="Story assert"),new Error(t+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let e,t=this.state.currentPointer;if(!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let r=this.state.callStack.elements.length-1;r>=0;--r)if(t=this.state.callStack.elements[r].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let r=this.state.outputStream.length-1;r>=0;--r)if(e=this.state.outputStream[r].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};Qn.Story=Gr;Gr.inkVersionCurrent=21;(function(n){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(n.OutputStateChange||(n.OutputStateChange={}));})(Gr||(Qn.Story=Gr={}));});var Qv=S(bu=>{Object.defineProperty(bu,"__esModule",{value:true});bu.Story=void 0;var yT=da(),vT=Ya(),gu=ye(),yu=Ve(),hs=wr(),vu=qt(),Zv=Vr(),CT=Ud(),bT=Oo(),_T=ef(),ST=is(),Jr=Qt(),ET=Cn(),wT=yn(),ds=ne(),DT=Ki(),AT=Xi(),PT=Un(),Cu=class n extends vu.FlowBase{get flowLevel(){return Zv.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=(r=null)=>{var i,a;this._errorHandler=r,this.constants=new Map;for(let c of this.FindAll(vT.ConstantDeclaration)()){let h=this.constants.get(c.constantName);if(h&&!h.Equals(c.expression)){let f=`CONST '${c.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 ${h.debugMetadata}.`;this.Error(f,c,false);}this.constants.set(c.constantName,c.expression);}this._listDefs=new Map;for(let c of this.FindAll(bT.ListDefinition)())!((i=c.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=c.identifier)===null||a===void 0?void 0:a.name,c);this.externals=new Map,this.ResolveWeavePointNaming();let s=this.runtimeObject,o=new gu.Container;o.AddContent(yu.ControlCommand.EvalStart());let u=[];for(let[c,h]of this.variableDeclarations)if(h.isGlobalDeclaration){if(h.listDefinition)this._listDefs.set(c,h.listDefinition),o.AddContent(h.listDefinition.runtimeObject),u.push(h.listDefinition.runtimeListDefinition);else {if(!h.expression)throw new Error;h.expression.GenerateIntoContainer(o);}let f=new wT.VariableAssignment(c,true);f.isGlobal=true,o.AddContent(f);}o.AddContent(yu.ControlCommand.EvalEnd()),o.AddContent(yu.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(yu.ControlCommand.Done());let l=new ST.Story(s,u);return this.runtimeObject=l,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(l.ResetState(),l)},this.ResolveList=r=>{let i=this._listDefs.get(r);return i||null},this.ResolveListItem=(r,i,a=null)=>{let s=null;if(r)return (s=this._listDefs.get(r))?s.ItemNamed(i):null;{let o=null,u=null;for(let[,l]of this._listDefs.entries()){let c=l.ItemNamed(i);c&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${u.identifier} and ${l.identifier}`,a,false):(o=c,u=l));}return o}},this.FlattenContainersIn=r=>{let i=new Set;if(r.content)for(let a of r.content){let s=(0, ds.asOrNull)(a,gu.Container);s&&i.add(s);}if(r.namedContent)for(let[,a]of r.namedContent){let s=(0, ds.asOrNull)(a,gu.Container);s&&i.add(s);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=r=>{if(r.namedContent&&r.namedContent.size>0||r.hasValidName||this._dontFlattenContainers.has(r))return;let i=(0, ds.asOrNull)(r.parent,gu.Container);if(i){let a=i.content.indexOf(r);i.content.splice(a,1);let s=r.ownDebugMetadata;if(r.content)for(let o of r.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),i.InsertContent(o,a),a+=1;}},this.Error=(r,i,a)=>{let s=a?hs.ErrorType.Warning:hs.ErrorType.Error,o="";if(i instanceof yT.AuthorWarning?(o+="TODO: ",s=hs.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+=r,r=o,this._errorHandler!==null)this._errorHandler(r,s);else throw new Error(r);this._hadError=s===hs.ErrorType.Error,this._hadWarning=s===hs.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=r=>this.externals.has(r),this.AddExternal=r=>{this.externals.has(r.name)?this.Error(`Duplicate EXTERNAL definition of '${r.name}'`,r,false):r.name&&this.externals.set(r.name,r);},this.DontFlattenContainer=r=>{this._dontFlattenContainers.add(r);},this.NameConflictError=(r,i,a,s)=>{r.Error(`${s} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(r,i,a,s="")=>{var o;let u=s||r.typeName;if(n.IsReservedKeyword(i?.name)){r.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a reserved keyword`);return}else if(AT.FunctionCall.IsBuiltIn(i?.name||"")){r.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a built in function`);return}let l=this.ContentWithNameAtLevel(i?.name||"",Zv.FlowLevel.Knot),c=(0, ds.asOrNull)(l,vu.FlowBase);if(c&&(c!==r||a===Jr.SymbolType.Arg)){this.NameConflictError(r,i?.name||"",c,u);return}if(a<Jr.SymbolType.List)return;for(let[g,m]of this._listDefs)if(i?.name===g&&r!==m&&m.variableAssignment!==r&&this.NameConflictError(r,i?.name,m,u),!(r instanceof _T.ListElementDefinition))for(let C of m.itemDefinitions)i?.name===C.name&&this.NameConflictError(r,i?.name||"",C,u);if(a<=Jr.SymbolType.Var)return;let h=i?.name&&this.variableDeclarations.get(i?.name)||null;if(h&&h!==r&&h.isGlobalDeclaration&&h.listDefinition==null&&this.NameConflictError(r,i?.name||"",h,u),a<Jr.SymbolType.SubFlowAndWeave)return;let p=new PT.Path(i).ResolveFromContext(r);if(p&&p!==r){this.NameConflictError(r,i?.name||"",p,u);return}if(!(a<Jr.SymbolType.Arg)&&a!==Jr.SymbolType.Arg){let g=(0, ds.asOrNull)(r,vu.FlowBase);if(g||(g=(0, DT.ClosestFlowBase)(r)),g&&g.hasParameters&&g.args){for(let m of g.args)if(((o=m.identifier)===null||o===void 0?void 0:o.name)===i?.name){r.Error(`${u} '${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 r of e)if(r instanceof CT.IncludedFile){let i=r,a=e.indexOf(r);if(e.splice(a,1),i.includedStory){let s=[],o=i.includedStory;if(o.content!=null){for(let u of o.content)u instanceof vu.FlowBase?t.push(u):s.push(u);s.push(new ET.Text(`
36
- `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};bu.Story=Cu;Cu.IsReservedKeyword=n=>{switch(n){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 t0=S(_u=>{Object.defineProperty(_u,"__esModule",{value:true});_u.StringExpression=void 0;var e0=Ve(),OT=ft(),xT=Cn(),TT=ne(),Of=class n extends OT.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof xT.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(e0.ControlCommand.BeginString());for(let r of this.content)t.AddContent(r.runtimeObject);t.AddContent(e0.ControlCommand.EndString());},this.toString=()=>{let t="";for(let r of this.content)t+=r;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, TT.asOrNull)(e,n);if(t===null||!this.isSingleString||!t.isSingleString)return false;let r=this.toString(),i=t.toString();return r===i}};_u.StringExpression=Of;});var r0=S(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.LegacyTag=zr.Tag=void 0;var NT=de(),n0=Ve(),xf=class extends NT.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?n0.ControlCommand.BeginTag():n0.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};zr.Tag=xf;var FT=Md(),Tf=class extends FT.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};zr.LegacyTag=Tf;});var i0=S(Su=>{Object.defineProperty(Su,"__esModule",{value:true});Su.DefaultFileHandler=void 0;var Nf=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.")};}};Su.DefaultFileHandler=Nf;});var Vf=S(Au=>{Object.defineProperty(Au,"__esModule",{value:true});Au.InkParser=void 0;var IT=Py(),kT=da(),VT=jh(),Pt=qy(),Ae=Gi(),RT=kr(),$T=Ky(),jT=Ua(),fs=vd(),rt=uo(),LT=Ya(),Eu=yv(),qT=vv(),er=jr(),Ff=$r(),BT=ft(),WT=Cv(),s0=bv(),wu=Xi(),MT=Ui(),GT=_v(),JT=Wo(),Du=Ev(),a0=Ud(),zT=wv(),HT=Yd(),o0=Av(),UT=Oo(),KT=ef(),XT=pd(),u0=de(),YT=Un(),l0=sd(),c0=Pd(),De=wd(),Me=tf(),ZT=rf(),h0=Qv(),ps=t0(),en=Kh(),Hr=r0(),tn=Cn(),d0=xd(),If=Vd(),kf=qr(),QT=Rh(),wn=ne(),ms=so(),Ur=Oa(),f0=wr(),e1=i0(),se=class n extends en.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,r=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel(Me.StatementLevel.Top);return new h0.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let u=this.Parse(s);if(u===null)return null;let l=[];l.push(u);do{let c=this.BeginRule();if(o()===null){this.FailRule(c);break}let f=this.Parse(s);if(f===null){this.FailRule(c);break}this.SucceedRule(c),l.push(f);}while(true);return l},this.CreateDebugMetadata=(s,o)=>{let u=new qT.DebugMetadata;return u.startLineNumber=(s?.lineIndex||0)+1,u.endLineNumber=o.lineIndex+1,u.startCharacterNumber=(s?.characterInLineIndex||0)+1,u.endCharacterNumber=o.characterInLineIndex+1,u.fileName=this._filename,u},this.RuleDidSucceed=(s,o,u)=>{let l=(0, wn.asOrNull)(s,u0.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(o,u));let c=Array.isArray(s)?s:null;if(c!==null)for(let f of c)(0, wn.asOrNull)(f,u0.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,u)));let h=(0, wn.asOrNull)(s,ms.Identifier);h!=null&&(h.debugMetadata=this.CreateDebugMetadata(o,u));},this.OnStringParserError=(s,o,u=0,l=false)=>{let h=l?"WARNING:":"ERROR:";if(this._filename!==null&&(h+=` '${this._filename}'`),h+=` line ${u+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(h,l?f0.ErrorType.Warning:f0.ErrorType.Error);else throw new Error(h)},this.AuthorWarning=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
37
- \r`);return o?new kT.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=n.ListAllCharacterRanges();for(let u of o)s.AddCharacters(u.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let s=true,o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!o){if(o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),o===null)return null;s=false;}let u=this.Parse(this.BracketedName);this.Whitespace(),u!=null&&this.Newline();let l=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let c=null,h=this.Parse(this.MixedTextAndLogic);h&&(c=new rt.ContentList(h));let f=null,p=null,g=this.ParseString("[")!==null;if(g){this.EndTagIfNecessary(c);let v=this.Parse(this.MixedTextAndLogic);v!==null&&(f=new rt.ContentList(v)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(p=new rt.ContentList(d));}this.Whitespace(),this.EndTagIfNecessary(p??c);let m=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let C=!c&&!p&&!f;if(C&&m===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!c&&g&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),p||(p=new rt.ContentList),this.EndTagIfNecessary(p),m!==null)for(let v of m){let d=(0, wn.asOrNull)(v,er.Divert);d&&d.isEmpty||p.AddContent(v);}p.AddContent(new tn.Text(`
38
- `));let b=new RT.Choice(c,f,p);return u&&(b.identifier=u),b.indentationDepth=o.length,b.hasWeaveStyleInlineBrackets=g,b.condition=l,b.onceOnly=s,b.isInvisibleDefault=C,b},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new XT.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),en.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let s=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(s),this.Expect(this.String("}"),"closing '}' for choice condition"),s},this.Gather=()=>{let s=this.Parse(this.GatherDashes);if(s===null)return null;let o=Number(s),u=this.Parse(this.BracketedName),l=new MT.Gather(u,o);return this.Newline(),l},this.GatherDashes=()=>{this.Whitespace();let s=0;for(;this.ParseDashNotArrow()!==null;)s+=1,this.Whitespace();return s===0?null:s},this.ParseDashNotArrow=()=>{let s=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(s):this.FailRule(s)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),s)},this.InnerConditionalContent=s=>{if(s===void 0){let h=this.Parse(this.ConditionExpression),f=this.Parse(()=>this.InnerConditionalContent(h));return f===null?null:f}let o,u=s!==null,l=this.Parse(this.Newline)===null;if(l&&!u)return null;if(l)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let h=this.StatementsAtLevel(Me.StatementLevel.InnerBlock);if(h!==null){o=[new fs.ConditionalSingleBranch(h)];let p=this.Parse(this.SingleMultilineCondition);p&&(p.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",p),p.isElse=true),o.push(p));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let h=new fs.ConditionalSingleBranch(null);h.isTrueBranch=true,o.unshift(h);}if(s){let h=false;for(let f=0;f<o.length;++f){let p=o[f],g=f===o.length-1;p.ownExpression?(p.matchingEquality=true,h=true):h&&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 h=0;h<o.length;++h){let f=o[h],p=h===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 h of o)h.isInline=l;return new jT.Conditional(s,o)},this.InlineConditionalBranches=()=>{let s=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(s===null||s.length===0)return null;let o=[];if(s.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let u=new fs.ConditionalSingleBranch(s[0]);if(u.isTrueBranch=true,o.push(u),s.length>1){let l=new fs.ConditionalSingleBranch(s[1]);l.isElse=true,o.push(l);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineCondition);return s===null?null:(this.MultilineWhitespace(),s)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=null,o=this.Parse(this.ElseExpression)!==null;o||(s=this.Parse(this.ConditionExpression));let u=this.StatementsAtLevel(Me.StatementLevel.InnerBlock);s===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new tn.Text("")]),this.MultilineWhitespace();let l=new fs.ConditionalSingleBranch(u);return l.ownExpression=s,l.isElse=o,l},this.ConditionExpression=()=>{let s=this.Parse(this.Expression);return s===null||(this.DisallowIncrement(s),this.Whitespace(),this.ParseString(":")===null)?null:s},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:en.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let u=s.length-1,l=s[u];if(l instanceof tn.Text){let c=l;c.text=c.text.replace(new RegExp(/[ \t]+$/g),""),o?c.text+=" ":c.text.length===0&&(s.splice(u,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof er.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof Hr.Tag&&s[0].isStart||s.push(new tn.Text(`
39
- `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),s)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let o=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let u=this.Parse(this.MultiDivert);u!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...u));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),u=this.ParseString("\\")!==null;if(u||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),u){let l=this.ParseSingleCharacter();s+=l;}}else break}while(true);return s!==null?new tn.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new Ae.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new Ae.CharacterSet(`{}|
40
- \r\\#`),this._notTextEndCharactersChoice=new Ae.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new Ae.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let s=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let u=this.ParseUntil(s,this._nonTextPauseCharacters,o);return u!==null?u:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let u=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!u)return null;s=[],this.EndTagIfNecessary(s);for(let l=0;l<u.length;++l)if(l%2===0){if(u[l]==="->->"){l===0||l===u.length-1||l===u.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let f=new d0.TunnelOnwards;if(l<u.length-1){let p=(0, wn.asOrNull)(u[l+1],er.Divert);f.divertAfter=p;}s.push(f);break}}else {let h=u[l];l<u.length-1&&(h.isTunnel=true),s.push(h);}if(s.length===0&&u.length===1){let l=new er.Divert(null);l.isEmpty=true,s.push(l),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new er.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let u=new YT.Path(s);return new er.Divert(u,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof d0.TunnelOnwards)return null;let u=s[0];return u.isTunnel?null:u},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let s=0;for(;this.ParseString("->")!==null;)s+=1;return s===0?null:s===1?"->":(s===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let s=this.ParseTempKeyword();this.Whitespace();let o=null;if(s?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let u=this.ParseString("+")!==null,l=this.ParseString("-")!==null;if(u&&l&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return s&&this.Error("Expected '='"),null;let c=this.Expect(this.Expression,"value expression to be assigned");return u||l?new Du.IncDecExpression(o,c,u):new If.VariableAssignment({variableIdentifier:o,assignedExpression:c,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof Du.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let s=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(s),true):(this.FailRule(s),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new l0.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let u=this.BeginRule(),l=this.ParseInfixOperator();if(l!==null&&l.precedence>s){let c=`right side of '${l.type}' expression`,h=this.Expect(()=>this.ExpressionInfixRight(o,l),c);if(h===null)return this.FailRule(u),null;o=this.SucceedRule(u,h);continue}this.FailRule(u);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let s=this.Parse(this.ExpressionDivertTarget);if(s!==null)return s;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let u=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(u===null&&o!==null&&(u=this.ExpressionUnary()),u===null)return null;o!==null&&(u=QT.UnaryExpression.WithInner(u,o)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let c=l==="++";if(!(u instanceof kf.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let h=u;u=new Du.IncDecExpression(h.identifier,c);}}return u},this.ExpressionNot=()=>{let s=this.Identifier();return s==="not"?s:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let s=this.Parse(this.SingleDivert);return !s||s&&s.isThread?null:(this.Whitespace(),new Ff.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new Ur.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new Ur.NumberExpression(s,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let o=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,o===null?o=[new tn.Text("")]:o.find(u=>u instanceof er.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new ps.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new Ur.NumberExpression(true,"bool"):s==="false"?new Ur.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new wu.FunctionCall(s,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,s);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let s=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return s===null||h0.Story.IsReservedKeyword(s[0].name)?null:new kf.VariableReference(s)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let s=this.Parse(this.Expression);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),s)},this.ExpressionInfixRight=(s,o)=>{if(!s)return null;this.Whitespace();let u=this.Parse(()=>this.Expression(o.precedence));return u?new VT.BinaryExpression(s,u,o.type):null},this.ParseInfixOperator=()=>{for(let s of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(s.type)!==null){if(s.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,s)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let s=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new o0.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let u=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${u?.name}`;}return this.Whitespace(),s},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(s,o,u=false)=>{let l=new zT.InfixOperator(s,o,u);this._binaryOperators.push(l),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,s.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let s=this.Expect(()=>this.ParseUntilCharactersFromString(`
31
+ `)a==-1&&(a=c),s=c;else {if(h==" "||h==" ")continue;break}}if(r==-1&&a==-1)return null;let o=[],u=0,l=t.length;if(r!=-1){if(r>0){let c=new De.StringValue(t.substring(0,r));o.push(c);}o.push(new De.StringValue(`
32
+ `)),u=i+1;}if(a!=-1&&(l=s),l>u){let c=t.substring(u,l);o.push(new De.StringValue(c));}if(a!=-1&&s>i&&(o.push(new De.StringValue(`
33
+ `)),a<t.length-1)){let c=t.length-a-1,h=new De.StringValue(t.substring(a+1,a+1+c));o.push(h);}return o}PushToOutputStreamIndividual(e){let t=(0, _e.asOrNull)(e,Sp.Glue),r=(0, _e.asOrNull)(e,De.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(r){let a=-1,s=this.callStack.currentElement;s.type==wn.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let l=this.outputStream.length-1;l>=0;l--){let c=this.outputStream[l],h=c instanceof Ge.ControlCommand?c:null;if((c instanceof Sp.Glue?c:null)!=null){o=l;break}else if(h!=null&&h.commandType==Ge.ControlCommand.CommandType.BeginString){l>=a&&(a=-1);break}}let u=-1;if(o!=-1&&a!=-1?u=Math.min(a,o):o!=-1?u=o:u=a,u!=-1){if(r.isNewline)i=false;else if(r.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let l=this.callStack.elements;for(let c=l.length-1;c>=0;c--){let h=l[c];if(h.type==wn.PushPopType.Function)h.functionStartInOutputStream=-1;else break}}}else r.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, bt.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let r=this.outputStream[t],i=(0, _e.asOrNull)(r,Ge.ControlCommand),a=(0, _e.asOrNull)(r,De.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, _e.asOrNull)(this.outputStream[t],De.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 Sp.Glue)this.outputStream.splice(e,1);else if(t instanceof Ge.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof Ge.ControlCommand);e--){let r=this.outputStream[e];if(r instanceof De.StringValue){if(r.isNewline)return true;if(r.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof De.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, _e.asOrNull)(this.outputStream[e],Ge.ControlCommand);if(t instanceof Ge.ControlCommand&&t.commandType==Ge.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, _e.asOrNull)(e,De.ListValue);if(t){let r=t.value;if(r===null)return (0, bt.throwNullException)("rawList");if(r.originNames!=null){r.origins||(r.origins=[]),r.origins.length=0;for(let i of r.originNames){if(this.story.listDefinitions===null)return (0, bt.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, bt.throwNullException)("StoryState def.result");r.origins.indexOf(a.result)<0&&r.origins.push(a.result);}}}if(e===null)return (0, bt.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, _e.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, _e.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Jr.Pointer.Null,this.previousPointer=Jr.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){aT.Debug.Assert(this.callStack.currentElement.type==wn.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let r=this.outputStream[t],i=(0, _e.asOrNull)(r,De.StringValue),a=(0, _e.asOrNull)(r,Ge.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==wn.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let r=this.story.PointerAtPath(e);!r.isNull&&r.index==-1&&(r.index=0),this.currentPointer=r,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(wn.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Jr.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 lT.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, _e.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(De.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==wn.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Jr.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=wn.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 r=this.PopEvaluationStack();t===null&&(t=r);}if(this.PopCallStack(wn.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof sT.Void)return null;let r=(0, _e.asOrThrows)(t,De.Value);return r.valueType==De.ValueType.DivertTarget?"-> "+r.valueObject.toString():r.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;}};fu.StoryState=wp;});var Uv=_(mu=>{Object.defineProperty(mu,"__esModule",{value:true});mu.Stopwatch=void 0;var Ep=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;}};mu.Stopwatch=Ep;});var Xv=_(gu=>{Object.defineProperty(gu,"__esModule",{value:true});gu.ErrorType=void 0;var Kv;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(Kv||(gu.ErrorType=Kv={}));});var as=_(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.Story=tr.InkList=void 0;var $e=ve(),Dp=et(),Ap=Gr(),cT=Hv(),$=Re(),Ct=Un(),hT=Ra(),dT=up(),Yv=Bt(),N=fe(),Op=Qe(),hs=Hn(),yu=eu(),pT=bn(),fT=Br(),mT=qt(),Qn=ji(),Pp=yp(),er=Jn(),gT=cp(),yT=Uv(),Dn=Ui(),ds=nt(),B=re(),te=Ve(),Zv=bp(),Qv=Xv(),vT=nt();Object.defineProperty(tr,"InkList",{enumerable:true,get:function(){return vT.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var zr=class n extends Dp.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, te.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,r=null;if(arguments[0]instanceof $e.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let i=arguments[0];r=Zv.SimpleJson.TextToDictionary(i);}else r=arguments[0];if(t!=null&&(this._listDefinitions=new gT.ListDefinitionsOrigin(t)),this._externals=new Map,r!==null){let i=r,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let s=parseInt(a);if(s>n.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(s<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");s!=n.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${n.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=i.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let u;(u=i.listDefs)&&(this._listDefinitions=Ap.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, B.asOrThrows)(Ap.JsonSerialisation.JTokenToRuntimeObject(o),$e.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new Zv.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",n.inkVersionCurrent),e.WriteProperty("root",r=>Ap.JsonSerialisation.WriteRuntimeContainer(r,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let r of this._listDefinitions.lists){e.WritePropertyStart(r.name),e.WriteObjectStart();for(let[i,a]of r.items){let s=ds.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(s.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new cT.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, te.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, te.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new Op.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 r=new yT.Stopwatch;r.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof Qn.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(i||this._asyncContinueActive&&r.ElapsedMilliseconds>e)break}while(this.canContinue);r.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(Ct.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(Ct.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(a=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let s of this.state.currentErrors)this.onError(s,Qv.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,Qv.ErrorType.Warning);this.ResetErrors();}else {let s=new er.StringBuilder;throw s.Append("Ink had "),this.state.hasError&&(s.Append(`${this.state.currentErrors.length}`),s.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&s.Append(" and ")),this.state.hasWarning&&(s.Append(`${this.state.currentWarnings.length}`),s.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&s.Append(" and ")),s.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),s.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new Qn.StoryException(s.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, te.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, te.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==n.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==n.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,r,i){if(e===null)return (0, te.throwNullException)("prevText");if(t===null)return (0, te.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
34
+ `;if(r==i&&e.length==t.length&&a)return n.OutputStateChange.NoChange;if(!a)return n.OutputStateChange.NewlineRemoved;if(i>r)return n.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return n.OutputStateChange.ExtendedBeyondNewline}return n.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new er.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 $e.Container?t:null}PointerAtPath(e){if(e.length==0)return Dn.Pointer.Null;let t=new Dn.Pointer,r=e.length,i=null;return e.lastComponent===null?(0, te.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(r=e.length-1,i=this.mainContentContainer.ContentAtPath(e,void 0,r),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&&r>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, te.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 r=(0, B.asOrNull)(t.Resolve(),$e.Container);for(;r&&(this.VisitContainer(r,true),r.content.length!=0);)t=Dn.Pointer.StartOf(r),r=(0, B.asOrNull)(t.Resolve(),$e.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=t.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, B.asOrNull)(i,hT.ChoicePoint);if(s){let u=this.ProcessChoice(s);u&&this.state.generatedChoices.push(u),i=null,e=false;}if(i instanceof $e.Container&&(e=false),e){let u=(0, B.asOrNull)(i,N.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new N.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, B.asOrNull)(i,$.ControlCommand);o&&o.commandType==$.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let s=e.Resolve(),o=(0, B.asOrNull)(s,$e.Container)||(0, B.asOrNull)(e.container,$e.Container);for(;o;)this._prevContainers.push(o),o=(0, B.asOrNull)(o.parent,$e.Container);}let r=t.Resolve();if(r==null)return;let i=(0, B.asOrNull)(r.parent,$e.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let s=i.content.length>0&&r==i.content[0]&&a;s||(a=false),this.VisitContainer(i,s),r=i,i=(0, B.asOrNull)(i.parent,$e.Container);}}PopChoiceStringAndTags(e){let t=(0, B.asOrThrows)(this.state.PopEvaluationStack(),N.StringValue);for(;this.state.evaluationStack.length>0&&(0, B.asOrNull)(this.state.PeekEvaluationStack(),yu.Tag)!=null;){let r=(0, B.asOrNull)(this.state.PopEvaluationStack(),yu.Tag);r&&e.push(r.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let r="",i="",a=[];if(e.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(r=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new dT.Choice;return s.targetPath=e.pathOnChoice,s.sourcePath=e.path.toString(),s.isInvisibleDefault=e.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(r+i).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof N.Value){let r=e;if(r instanceof N.DivertTargetValue){let i=r;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 r.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof Yv.Divert){let t=e;if(t.isConditional){let r=this.state.PopEvaluationStack();if(!this.IsTruthy(r))return true}if(t.hasVariableTarget){let r=t.variableDivertName,i=this.state.variablesState.GetVariableWithName(r);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+r+")");else if(!(i instanceof N.DivertTargetValue)){let s=(0, B.asOrNull)(i,N.IntValue),o="Tried to divert to a target from a variable, but the variable ("+r+") didn't contain a divert target, it ";s instanceof N.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, B.asOrThrows)(i,N.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),true;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),true}else if(e instanceof $.ControlCommand){let t=e;switch(t.commandType){case $.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case $.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case $.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let y=this.state.PopEvaluationStack();if(!(y instanceof hs.Void)){let w=new N.StringValue(y.toString());this.state.PushToOutputStream(w);}}break;case $.ControlCommand.CommandType.NoOp:break;case $.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case $.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case $.ControlCommand.CommandType.PopFunction:case $.ControlCommand.CommandType.PopTunnel:let r=t.commandType==$.ControlCommand.CommandType.PopFunction?Ct.PushPopType.Function:Ct.PushPopType.Tunnel,i=null;if(r==Ct.PushPopType.Tunnel){let y=this.state.PopEvaluationStack();i=(0, B.asOrNull)(y,N.DivertTargetValue),i===null&&this.Assert(y instanceof hs.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=r||!this.state.callStack.canPop){let y=new Map;y.set(Ct.PushPopType.Function,"function return statement (~ return)"),y.set(Ct.PushPopType.Tunnel,"tunnel onwards statement (->->)");let w=y.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(w="end of flow (-> END or choice)");let E="Found "+y.get(r)+", when expected "+w;this.Error(E);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case $.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 $.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case $.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let y=[],w=0;for(let x=this.state.outputStream.length-1;x>=0;--x){let U=this.state.outputStream[x];w++;let Se=(0, B.asOrNull)(U,$.ControlCommand);if(Se!=null){if(Se.commandType==$.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}U instanceof N.StringValue&&y.push(U);}this.state.PopFromOutputStream(w);let E=new er.StringBuilder;for(let x of y.reverse())E.Append(x.toString());let O=new yu.Tag(this.state.CleanOutputWhitespace(E.toString()));this.state.PushEvaluationStack(O);}else this.state.PushToOutputStream(t);break}case $.ControlCommand.CommandType.EndString:{let y=[],w=[],E=0;for(let x=this.state.outputStream.length-1;x>=0;--x){let U=this.state.outputStream[x];E++;let Se=(0, B.asOrNull)(U,$.ControlCommand);if(Se&&Se.commandType==$.ControlCommand.CommandType.BeginString)break;U instanceof yu.Tag&&w.push(U),U instanceof N.StringValue&&y.push(U);}this.state.PopFromOutputStream(E);for(let x of w)this.state.PushToOutputStream(x);y=y.reverse();let O=new er.StringBuilder;for(let x of y)O.Append(x.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new N.StringValue(O.toString()));break}case $.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new N.IntValue(a));break;case $.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new N.IntValue(this.state.currentTurnIndex+1));break;case $.ControlCommand.CommandType.TurnsSince:case $.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof N.DivertTargetValue)){let y="";s instanceof N.IntValue&&(y=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+y);break}let o=(0, B.asOrThrows)(s,N.DivertTargetValue),u=(0, B.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,$e.Container),l;u!=null?t.commandType==$.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(t.commandType==$.ControlCommand.CommandType.TurnsSince?l=-1:l=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new N.IntValue(l));break;case $.ControlCommand.CommandType.Random:{let y=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue),w=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(w==null||!(w instanceof N.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(y==null||!(y instanceof N.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(y.value===null)return (0, te.throwNullException)("maxInt.value");if(w.value===null)return (0, te.throwNullException)("minInt.value");let E=y.value-w.value+1;(!isFinite(E)||E>Number.MAX_SAFE_INTEGER)&&(E=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),E<=0&&this.Error("RANDOM was called with minimum as "+w.value+" and maximum as "+y.value+". The maximum must be larger");let O=this.state.storySeed+this.state.previousRandom,U=new Pp.PRNG(O).next(),Se=U%E+w.value;this.state.PushEvaluationStack(new N.IntValue(Se)),this.state.previousRandom=U;break}case $.ControlCommand.CommandType.SeedRandom:let c=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(c==null||!(c instanceof N.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(c.value===null)return (0, te.throwNullException)("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new hs.Void);break;case $.ControlCommand.CommandType.VisitIndex:let h=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new N.IntValue(h));break;case $.ControlCommand.CommandType.SequenceShuffleIndex:let p=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new N.IntValue(p));break;case $.ControlCommand.CommandType.StartThread:break;case $.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Dn.Pointer.Null);break;case $.ControlCommand.CommandType.End:this.state.ForceEnd();break;case $.ControlCommand.CommandType.ListFromInt:let f=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue),g=(0, B.asOrThrows)(this.state.PopEvaluationStack(),N.StringValue);if(f===null)throw new Qn.StoryException("Passed non-integer when creating a list element from a numerical value.");let m=null;if(this.listDefinitions===null)return (0, te.throwNullException)("this.listDefinitions");let b=this.listDefinitions.TryListGetDefinition(g.value,null);if(b.exists){if(f.value===null)return (0, te.throwNullException)("minInt.value");let y=b.result.TryGetItemWithValue(f.value,ds.InkListItem.Null);y.exists&&(m=new N.ListValue(y.result,f.value));}else throw new Qn.StoryException("Failed to find LIST called "+g.value);m==null&&(m=new N.ListValue),this.state.PushEvaluationStack(m);break;case $.ControlCommand.CommandType.ListRange:let C=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.Value),v=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.Value),d=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.ListValue);if(d===null||v===null||C===null)throw new Qn.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(d.value===null)return (0, te.throwNullException)("targetList.value");let S=d.value.ListWithSubRange(v.valueObject,C.valueObject);this.state.PushEvaluationStack(new N.ListValue(S));break;case $.ControlCommand.CommandType.ListRandom:{let y=this.state.PopEvaluationStack();if(y===null)throw new Qn.StoryException("Expected list for LIST_RANDOM");let w=y.value,E=null;if(w===null)throw (0, te.throwNullException)("list");if(w.Count==0)E=new ds.InkList;else {let O=this.state.storySeed+this.state.previousRandom,U=new Pp.PRNG(O).next(),Se=U%w.Count,Ht=w.entries();for(let Zp=0;Zp<=Se-1;Zp++)Ht.next();let Yr=Ht.next().value,rr={Key:ds.InkListItem.fromSerializedKey(Yr[0]),Value:Yr[1]};if(rr.Key.originName===null)return (0, te.throwNullException)("randomItem.Key.originName");E=new ds.InkList(rr.Key.originName,this),E.Add(rr.Key,rr.Value),this.state.previousRandom=U;}this.state.PushEvaluationStack(new N.ListValue(E));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof pT.VariableAssignment){let t=e,r=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,r),true}else if(e instanceof fT.VariableReference){let t=e,r=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);r=new N.IntValue(a);}else r=this.state.variablesState.GetVariableWithName(t.name),r==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."),r=new N.IntValue(0));return this.state.PushEvaluationStack(r),true}else if(e instanceof mT.NativeFunctionCall){let t=e,r=this.state.PopEvaluationStack(t.numberOfParameters),i=t.Call(r);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(e,t=true,r=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,r),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==Ct.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:
35
+ `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(r),this.ChoosePath(new Op.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 r=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(r),r.threadAtGeneration===null)return (0, te.throwNullException)("choiceToChoose.threadAtGeneration");if(r.targetPath===null)return (0, te.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=r.threadAtGeneration,this.ChoosePath(r.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],r=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(e,t),this.IfAsyncWeCant("evaluate a function"),e==null)throw new Error("Function is null");if(e==""||e.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(e);if(i==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,t);let s=new er.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let u=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,u),r?{returned:u,output:o}:u}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(Ct.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let r=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>r?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, te.throwNullException)("funcName");let r=this._externals.get(e),i=null,a=typeof r<"u";if(a&&!r.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&&!r.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(Ct.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Dn.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let l=0;l<t;++l){let h=(0, B.asOrThrows)(this.state.PopEvaluationStack(),N.Value).valueObject;s.push(h);}s.reverse();let o=r.function(s),u=null;o!=null?(u=N.Value.Create(o),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof o)):u=new hs.Void,this.state.PushEvaluationStack(u);}BindExternalFunctionGeneral(e,t,r=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:r});}TryCoerce(e){return e}BindExternalFunction(e,t,r=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,i=>{this.Assert(i.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=i.length;s<o;s++)a[s]=this.TryCoerce(i[s]);return t.apply(null,a)},r);}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,r=arguments[1]||new Set;if(arguments[0]instanceof $e.Container&&(e=arguments[0]),arguments[0]instanceof Dp.InkObject&&(t=arguments[0]),e===null&&t===null)if(this.ValidateExternalBindings(this._mainContentContainer,r),this._hasValidatedExternals=true,r.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=r.size>1?"s":"",i+=": '",i+=Array.from(r).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,r);}for(let[,i]of e.namedContent)this.ValidateExternalBindings((0, B.asOrNull)(i,Dp.InkObject),r);}else if(t!=null){let i=(0, B.asOrNull)(t,Yv.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, te.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||r.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 r=0,i=e.length;r<i;r++)this.ObserveVariable(e[r],t[r]);}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 r=this._variableObservers.get(t);r!=null&&(r.splice(r.indexOf(e),1),r.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let r=this._variableObservers.keys();for(let i of r){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 r=this._variableObservers.get(e);if(typeof r<"u"){if(!(t instanceof N.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, B.asOrThrows)(t,N.Value);for(let a of r)a(e,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new Op.Path(e),r=this.ContentAtPath(t).container;if(r===null)return (0, te.throwNullException)("flowContainer");for(;;){let s=r.content[0];if(s instanceof $e.Container)r=s;else break}let i=false,a=null;for(let s of r.content){let o=(0, B.asOrNull)(s,$.ControlCommand);if(o!=null)o.commandType==$.ControlCommand.CommandType.BeginTag?i=true:o.commandType==$.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, B.asOrNull)(s,N.StringValue);u!==null?(a===null&&(a=[]),u.value!==null&&a.push(u.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let e=new er.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new er.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=Dn.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(Ct.PushPopType.Function)?(this.state.PopCallStack(Ct.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new hs.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, te.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let r=(0, B.asOrNull)(t.container.parent,$e.Container);if(!(r instanceof $e.Container))break;let i=r.content.indexOf(t.container);if(i==-1)break;if(t=new Dn.Pointer(r,i),t.index++,e=true,t.container===null)return (0, te.throwNullException)("pointer.container")}return e||(t=Dn.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 r=t[0];return r.targetPath===null?(0, te.throwNullException)("choice.targetPath"):r.threadAtGeneration===null?(0, te.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=r.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(r.targetPath,false),true)}NextSequenceShuffleIndex(){let e=(0, B.asOrNull)(this.state.PopEvaluationStack(),N.IntValue);if(!(e instanceof N.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, te.throwNullException)("seqContainer");if(e.value===null)return (0, te.throwNullException)("numElementsIntVal.value");let r=e.value,a=(0, B.asOrThrows)(this.state.PopEvaluationStack(),N.IntValue).value;if(a===null)return (0, te.throwNullException)("seqCount");let s=a/r,o=a%r,u=t.path.toString(),l=0;for(let f=0,g=u.length;f<g;f++)l+=u.charCodeAt(f)||0;let c=l+s+this.state.storySeed,h=new Pp.PRNG(Math.floor(c)),p=[];for(let f=0;f<r;++f)p.push(f);for(let f=0;f<=o;++f){let g=h.next()%p.length,m=p[g];if(p.splice(g,1),f==o)return m}throw new Error("Should never reach here")}Error(e,t=false){let r=new Qn.StoryException(e);throw r.useEndLineNumber=t,r}Warning(e){this.AddError(e,true);}AddError(e,t=false,r=false){let i=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(i!=null){let s=r?i.endLineNumber:i.startLineNumber;e="RUNTIME "+a+": '"+i.fileName+"' line "+s+": "+e;}else this.state.currentPointer.isNull?e="RUNTIME "+a+": "+e:e="RUNTIME "+a+": ("+this.state.currentPointer+"): "+e;this.state.AddError(e,t),t||this.state.ForceEnd();}Assert(e,t=null){if(e==false)throw t==null&&(t="Story assert"),new Error(t+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let e,t=this.state.currentPointer;if(!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let r=this.state.callStack.elements.length-1;r>=0;--r)if(t=this.state.callStack.elements[r].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let r=this.state.outputStream.length-1;r>=0;--r)if(e=this.state.outputStream[r].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};tr.Story=zr;zr.inkVersionCurrent=21;(function(n){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(n.OutputStateChange||(n.OutputStateChange={}));})(zr||(tr.Story=zr={}));});var tb=_(_u=>{Object.defineProperty(_u,"__esModule",{value:true});_u.Story=void 0;var bT=fa(),CT=Qa(),vu=ve(),bu=Re(),ps=Ar(),Cu=Wt(),eb=jr(),ST=Xd(),_T=To(),wT=np(),ET=as(),Hr=tn(),DT=Sn(),AT=bn(),fs=re(),OT=Yi(),PT=Zi(),xT=Xn(),Su=class n extends Cu.FlowBase{get flowLevel(){return eb.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=(r=null)=>{var i,a;this._errorHandler=r,this.constants=new Map;for(let c of this.FindAll(CT.ConstantDeclaration)()){let h=this.constants.get(c.constantName);if(h&&!h.Equals(c.expression)){let p=`CONST '${c.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 ${h.debugMetadata}.`;this.Error(p,c,false);}this.constants.set(c.constantName,c.expression);}this._listDefs=new Map;for(let c of this.FindAll(_T.ListDefinition)())!((i=c.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=c.identifier)===null||a===void 0?void 0:a.name,c);this.externals=new Map,this.ResolveWeavePointNaming();let s=this.runtimeObject,o=new vu.Container;o.AddContent(bu.ControlCommand.EvalStart());let u=[];for(let[c,h]of this.variableDeclarations)if(h.isGlobalDeclaration){if(h.listDefinition)this._listDefs.set(c,h.listDefinition),o.AddContent(h.listDefinition.runtimeObject),u.push(h.listDefinition.runtimeListDefinition);else {if(!h.expression)throw new Error;h.expression.GenerateIntoContainer(o);}let p=new AT.VariableAssignment(c,true);p.isGlobal=true,o.AddContent(p);}o.AddContent(bu.ControlCommand.EvalEnd()),o.AddContent(bu.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(bu.ControlCommand.Done());let l=new ET.Story(s,u);return this.runtimeObject=l,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(l.ResetState(),l)},this.ResolveList=r=>{let i=this._listDefs.get(r);return i||null},this.ResolveListItem=(r,i,a=null)=>{let s=null;if(r)return (s=this._listDefs.get(r))?s.ItemNamed(i):null;{let o=null,u=null;for(let[,l]of this._listDefs.entries()){let c=l.ItemNamed(i);c&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${u.identifier} and ${l.identifier}`,a,false):(o=c,u=l));}return o}},this.FlattenContainersIn=r=>{let i=new Set;if(r.content)for(let a of r.content){let s=(0, fs.asOrNull)(a,vu.Container);s&&i.add(s);}if(r.namedContent)for(let[,a]of r.namedContent){let s=(0, fs.asOrNull)(a,vu.Container);s&&i.add(s);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=r=>{if(r.namedContent&&r.namedContent.size>0||r.hasValidName||this._dontFlattenContainers.has(r))return;let i=(0, fs.asOrNull)(r.parent,vu.Container);if(i){let a=i.content.indexOf(r);i.content.splice(a,1);let s=r.ownDebugMetadata;if(r.content)for(let o of r.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),i.InsertContent(o,a),a+=1;}},this.Error=(r,i,a)=>{let s=a?ps.ErrorType.Warning:ps.ErrorType.Error,o="";if(i instanceof bT.AuthorWarning?(o+="TODO: ",s=ps.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+=r,r=o,this._errorHandler!==null)this._errorHandler(r,s);else throw new Error(r);this._hadError=s===ps.ErrorType.Error,this._hadWarning=s===ps.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=r=>this.externals.has(r),this.AddExternal=r=>{this.externals.has(r.name)?this.Error(`Duplicate EXTERNAL definition of '${r.name}'`,r,false):r.name&&this.externals.set(r.name,r);},this.DontFlattenContainer=r=>{this._dontFlattenContainers.add(r);},this.NameConflictError=(r,i,a,s)=>{r.Error(`${s} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(r,i,a,s="")=>{var o;let u=s||r.typeName;if(n.IsReservedKeyword(i?.name)){r.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a reserved keyword`);return}else if(PT.FunctionCall.IsBuiltIn(i?.name||"")){r.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a built in function`);return}let l=this.ContentWithNameAtLevel(i?.name||"",eb.FlowLevel.Knot),c=(0, fs.asOrNull)(l,Cu.FlowBase);if(c&&(c!==r||a===Hr.SymbolType.Arg)){this.NameConflictError(r,i?.name||"",c,u);return}if(a<Hr.SymbolType.List)return;for(let[g,m]of this._listDefs)if(i?.name===g&&r!==m&&m.variableAssignment!==r&&this.NameConflictError(r,i?.name,m,u),!(r instanceof wT.ListElementDefinition))for(let b of m.itemDefinitions)i?.name===b.name&&this.NameConflictError(r,i?.name||"",b,u);if(a<=Hr.SymbolType.Var)return;let h=i?.name&&this.variableDeclarations.get(i?.name)||null;if(h&&h!==r&&h.isGlobalDeclaration&&h.listDefinition==null&&this.NameConflictError(r,i?.name||"",h,u),a<Hr.SymbolType.SubFlowAndWeave)return;let f=new xT.Path(i).ResolveFromContext(r);if(f&&f!==r){this.NameConflictError(r,i?.name||"",f,u);return}if(!(a<Hr.SymbolType.Arg)&&a!==Hr.SymbolType.Arg){let g=(0, fs.asOrNull)(r,Cu.FlowBase);if(g||(g=(0, OT.ClosestFlowBase)(r)),g&&g.hasParameters&&g.args){for(let m of g.args)if(((o=m.identifier)===null||o===void 0?void 0:o.name)===i?.name){r.Error(`${u} '${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 r of e)if(r instanceof ST.IncludedFile){let i=r,a=e.indexOf(r);if(e.splice(a,1),i.includedStory){let s=[],o=i.includedStory;if(o.content!=null){for(let u of o.content)u instanceof Cu.FlowBase?t.push(u):s.push(u);s.push(new DT.Text(`
36
+ `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};_u.Story=Su;Su.IsReservedKeyword=n=>{switch(n){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 rb=_(wu=>{Object.defineProperty(wu,"__esModule",{value:true});wu.StringExpression=void 0;var nb=Re(),TT=mt(),NT=Sn(),FT=re(),xp=class n extends TT.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof NT.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(nb.ControlCommand.BeginString());for(let r of this.content)t.AddContent(r.runtimeObject);t.AddContent(nb.ControlCommand.EndString());},this.toString=()=>{let t="";for(let r of this.content)t+=r;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, FT.asOrNull)(e,n);if(t===null||!this.isSingleString||!t.isSingleString)return false;let r=this.toString(),i=t.toString();return r===i}};wu.StringExpression=xp;});var sb=_(Ur=>{Object.defineProperty(Ur,"__esModule",{value:true});Ur.LegacyTag=Ur.Tag=void 0;var IT=pe(),ib=Re(),Tp=class extends IT.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?ib.ControlCommand.BeginTag():ib.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};Ur.Tag=Tp;var kT=Jd(),Np=class extends kT.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};Ur.LegacyTag=Np;});var ab=_(Eu=>{Object.defineProperty(Eu,"__esModule",{value:true});Eu.DefaultFileHandler=void 0;var Fp=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.")};}};Eu.DefaultFileHandler=Fp;});var Rp=_(Pu=>{Object.defineProperty(Pu,"__esModule",{value:true});Pu.InkParser=void 0;var VT=xy(),RT=fa(),jT=qh(),xt=Wy(),Oe=zi(),$T=Rr(),LT=Yy(),qT=Xa(),ms=Cd(),st=co(),BT=Qa(),Du=bv(),WT=Cv(),nr=qr(),Ip=Lr(),MT=mt(),GT=Sv(),ob=_v(),Au=Zi(),JT=Xi(),zT=wv(),HT=Go(),Ou=Dv(),ub=Xd(),UT=Av(),KT=Qd(),lb=Pv(),XT=To(),YT=np(),ZT=gd(),cb=pe(),QT=Xn(),hb=od(),db=xd(),Ae=Ad(),Je=rp(),e1=sp(),pb=tb(),gs=rb(),nn=Yh(),Kr=sb(),rn=Sn(),fb=Nd(),kp=jd(),Vp=Wr(),t1=$h(),An=re(),ys=oo(),Xr=Ta(),mb=Ar(),n1=ab(),ae=class n extends nn.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,r=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel(Je.StatementLevel.Top);return new pb.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let u=this.Parse(s);if(u===null)return null;let l=[];l.push(u);do{let c=this.BeginRule();if(o()===null){this.FailRule(c);break}let p=this.Parse(s);if(p===null){this.FailRule(c);break}this.SucceedRule(c),l.push(p);}while(true);return l},this.CreateDebugMetadata=(s,o)=>{let u=new WT.DebugMetadata;return u.startLineNumber=(s?.lineIndex||0)+1,u.endLineNumber=o.lineIndex+1,u.startCharacterNumber=(s?.characterInLineIndex||0)+1,u.endCharacterNumber=o.characterInLineIndex+1,u.fileName=this._filename,u},this.RuleDidSucceed=(s,o,u)=>{let l=(0, An.asOrNull)(s,cb.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(o,u));let c=Array.isArray(s)?s:null;if(c!==null)for(let p of c)(0, An.asOrNull)(p,cb.ParsedObject)&&(p.hasOwnDebugMetadata||(p.debugMetadata=this.CreateDebugMetadata(o,u)));let h=(0, An.asOrNull)(s,ys.Identifier);h!=null&&(h.debugMetadata=this.CreateDebugMetadata(o,u));},this.OnStringParserError=(s,o,u=0,l=false)=>{let h=l?"WARNING:":"ERROR:";if(this._filename!==null&&(h+=` '${this._filename}'`),h+=` line ${u+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(h,l?mb.ErrorType.Warning:mb.ErrorType.Error);else throw new Error(h)},this.AuthorWarning=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
37
+ \r`);return o?new RT.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=n.ListAllCharacterRanges();for(let u of o)s.AddCharacters(u.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let s=true,o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!o){if(o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),o===null)return null;s=false;}let u=this.Parse(this.BracketedName);this.Whitespace(),u!=null&&this.Newline();let l=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let c=null,h=this.Parse(this.MixedTextAndLogic);h&&(c=new st.ContentList(h));let p=null,f=null,g=this.ParseString("[")!==null;if(g){this.EndTagIfNecessary(c);let v=this.Parse(this.MixedTextAndLogic);v!==null&&(p=new st.ContentList(v)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(p);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(f=new st.ContentList(d));}this.Whitespace(),this.EndTagIfNecessary(f??c);let m=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let b=!c&&!f&&!p;if(b&&m===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!c&&g&&!p&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),f||(f=new st.ContentList),this.EndTagIfNecessary(f),m!==null)for(let v of m){let d=(0, An.asOrNull)(v,nr.Divert);d&&d.isEmpty||f.AddContent(v);}f.AddContent(new rn.Text(`
38
+ `));let C=new $T.Choice(c,p,f);return u&&(C.identifier=u),C.indentationDepth=o.length,C.hasWeaveStyleInlineBrackets=g,C.condition=l,C.onceOnly=s,C.isInvisibleDefault=b,C},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new ZT.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),nn.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let s=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(s),this.Expect(this.String("}"),"closing '}' for choice condition"),s},this.Gather=()=>{let s=this.Parse(this.GatherDashes);if(s===null)return null;let o=Number(s),u=this.Parse(this.BracketedName),l=new JT.Gather(u,o);return this.Newline(),l},this.GatherDashes=()=>{this.Whitespace();let s=0;for(;this.ParseDashNotArrow()!==null;)s+=1,this.Whitespace();return s===0?null:s},this.ParseDashNotArrow=()=>{let s=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(s):this.FailRule(s)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),s)},this.InnerConditionalContent=s=>{if(s===void 0){let h=this.Parse(this.ConditionExpression),p=this.Parse(()=>this.InnerConditionalContent(h));return p===null?null:p}let o,u=s!==null,l=this.Parse(this.Newline)===null;if(l&&!u)return null;if(l)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let h=this.StatementsAtLevel(Je.StatementLevel.InnerBlock);if(h!==null){o=[new ms.ConditionalSingleBranch(h)];let f=this.Parse(this.SingleMultilineCondition);f&&(f.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",f),f.isElse=true),o.push(f));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let h=new ms.ConditionalSingleBranch(null);h.isTrueBranch=true,o.unshift(h);}if(s){let h=false;for(let p=0;p<o.length;++p){let f=o[p],g=p===o.length-1;f.ownExpression?(f.matchingEquality=true,h=true):h&&g?(f.matchingEquality=true,f.isElse=true):!g&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",f):p===0?f.isTrueBranch=true:f.isElse=true;}}else {for(let h=0;h<o.length;++h){let p=o[h],f=h===o.length-1;if(p.ownExpression===null)if(f)p.isElse=true;else if(p.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",p);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",p);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let h of o)h.isInline=l;return new qT.Conditional(s,o)},this.InlineConditionalBranches=()=>{let s=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(s===null||s.length===0)return null;let o=[];if(s.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let u=new ms.ConditionalSingleBranch(s[0]);if(u.isTrueBranch=true,o.push(u),s.length>1){let l=new ms.ConditionalSingleBranch(s[1]);l.isElse=true,o.push(l);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineCondition);return s===null?null:(this.MultilineWhitespace(),s)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=null,o=this.Parse(this.ElseExpression)!==null;o||(s=this.Parse(this.ConditionExpression));let u=this.StatementsAtLevel(Je.StatementLevel.InnerBlock);s===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new rn.Text("")]),this.MultilineWhitespace();let l=new ms.ConditionalSingleBranch(u);return l.ownExpression=s,l.isElse=o,l},this.ConditionExpression=()=>{let s=this.Parse(this.Expression);return s===null||(this.DisallowIncrement(s),this.Whitespace(),this.ParseString(":")===null)?null:s},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:nn.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let u=s.length-1,l=s[u];if(l instanceof rn.Text){let c=l;c.text=c.text.replace(new RegExp(/[ \t]+$/g),""),o?c.text+=" ":c.text.length===0&&(s.splice(u,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof nr.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof Kr.Tag&&s[0].isStart||s.push(new rn.Text(`
39
+ `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),s)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let o=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let u=this.Parse(this.MultiDivert);u!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...u));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),u=this.ParseString("\\")!==null;if(u||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),u){let l=this.ParseSingleCharacter();s+=l;}}else break}while(true);return s!==null?new rn.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new Oe.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new Oe.CharacterSet(`{}|
40
+ \r\\#`),this._notTextEndCharactersChoice=new Oe.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new Oe.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let s=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let u=this.ParseUntil(s,this._nonTextPauseCharacters,o);return u!==null?u:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let u=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!u)return null;s=[],this.EndTagIfNecessary(s);for(let l=0;l<u.length;++l)if(l%2===0){if(u[l]==="->->"){l===0||l===u.length-1||l===u.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let p=new fb.TunnelOnwards;if(l<u.length-1){let f=(0, An.asOrNull)(u[l+1],nr.Divert);p.divertAfter=f;}s.push(p);break}}else {let h=u[l];l<u.length-1&&(h.isTunnel=true),s.push(h);}if(s.length===0&&u.length===1){let l=new nr.Divert(null);l.isEmpty=true,s.push(l),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new nr.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let u=new QT.Path(s);return new nr.Divert(u,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof fb.TunnelOnwards)return null;let u=s[0];return u.isTunnel?null:u},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let s=0;for(;this.ParseString("->")!==null;)s+=1;return s===0?null:s===1?"->":(s===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let s=this.ParseTempKeyword();this.Whitespace();let o=null;if(s?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let u=this.ParseString("+")!==null,l=this.ParseString("-")!==null;if(u&&l&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return s&&this.Error("Expected '='"),null;let c=this.Expect(this.Expression,"value expression to be assigned");return u||l?new Ou.IncDecExpression(o,c,u):new kp.VariableAssignment({variableIdentifier:o,assignedExpression:c,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof Ou.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let s=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(s),true):(this.FailRule(s),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new hb.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let u=this.BeginRule(),l=this.ParseInfixOperator();if(l!==null&&l.precedence>s){let c=`right side of '${l.type}' expression`,h=this.Expect(()=>this.ExpressionInfixRight(o,l),c);if(h===null)return this.FailRule(u),null;o=this.SucceedRule(u,h);continue}this.FailRule(u);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let s=this.Parse(this.ExpressionDivertTarget);if(s!==null)return s;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let u=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(u===null&&o!==null&&(u=this.ExpressionUnary()),u===null)return null;o!==null&&(u=t1.UnaryExpression.WithInner(u,o)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let c=l==="++";if(!(u instanceof Vp.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let h=u;u=new Ou.IncDecExpression(h.identifier,c);}}return u},this.ExpressionNot=()=>{let s=this.Identifier();return s==="not"?s:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let s=this.Parse(this.SingleDivert);return !s||s&&s.isThread?null:(this.Whitespace(),new Ip.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new Xr.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new Xr.NumberExpression(s,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let o=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,o===null?o=[new rn.Text("")]:o.find(u=>u instanceof nr.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new gs.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new Xr.NumberExpression(true,"bool"):s==="false"?new Xr.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new Au.FunctionCall(s,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,s);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let s=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return s===null||pb.Story.IsReservedKeyword(s[0].name)?null:new Vp.VariableReference(s)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let s=this.Parse(this.Expression);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),s)},this.ExpressionInfixRight=(s,o)=>{if(!s)return null;this.Whitespace();let u=this.Parse(()=>this.Expression(o.precedence));return u?new jT.BinaryExpression(s,u,o.type):null},this.ParseInfixOperator=()=>{for(let s of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(s.type)!==null){if(s.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,s)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let s=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new lb.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let u=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${u?.name}`;}return this.Whitespace(),s},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(s,o,u=false)=>{let l=new UT.InfixOperator(s,o,u);this._binaryOperators.push(l),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,s.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let s=this.Expect(()=>this.ParseUntilCharactersFromString(`
41
41
  \r`),"filename for include statement");s=s.replace(new RegExp(/[ \t]+$/g),"");let o=this.fileHandler.ResolveInkFilename(s,this._filename);if(this.FilenameIsAlreadyOpen(o))return this.Error(`Recursive INCLUDE detected: '${o}' is already open.`),this.ParseUntilCharactersFromString(`\r
42
- `),new a0.IncludedFile(null);this.AddOpenFilename(o);let u=null,l="";try{l=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(c){this.Error(`Failed to load: '${s}'.
43
- Error:${c}`);}return l!=null&&(u=new n(l,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new a0.IncludedFile(u)},this.FilenameIsAlreadyOpen=s=>this._rootParser._openFilenames.includes(s),this.AddOpenFilename=s=>{this._rootParser._openFilenames.push(s);},this.RemoveOpenFilename=s=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(s),1);},this.KnotDefinition=()=>{let s=this.Parse(this.KnotDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(Me.StatementLevel.Knot),u=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new HT.Knot(s.name,u,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,u=s?.name==="function";u?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=s,o===null&&(this.Error(`Expected the name of the ${u?"function":"knot"}`),o=new ms.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new s0.FlowDecl(o,l,u)},this.KnotTitleEquals=()=>{let s=this.ParseCharactersFromString("=");return s===null||s.length<=1?null:s},this.StitchDefinition=()=>{let s=this.Parse(this.StitchDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(Me.StatementLevel.Stitch),u=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new ZT.Stitch(s.name,u,s.args,s.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let s=this.ParseString("function")!==null;s&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new s0.FlowDecl(o,u,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new Ae.CharacterSet("="),null),[new tn.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),s===null&&(s=[]),s},this.FlowDeclArgument=()=>{let s=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(s==null&&u===null)return null;let l=new IT.Argument;return o!==null&&(l.isDivertTarget=true),s!==null&&s.name==="ref"?(u===null&&this.Error("Expected an parameter name after 'ref'"),l.identifier=u,l.isByReference=true):(l.isDivertTarget?l.identifier=u:l.identifier=s,l.identifier===null&&this.Error("Expected an parameter name"),l.isByReference=false),l},this.ExternalDeclaration=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new ms.Identifier("");this.Whitespace();let u=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);u===null&&(u=[]);let l=u.map(c=>{var h;return (h=c.identifier)===null||h===void 0?void 0:h.name}).filter(wn.filterUndef);return new WT.ExternalDeclaration(o,l)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let s=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(s,"expression after '~'",this.SkipToNextLine);if(o===null)return new rt.ContentList;o instanceof BT.Expression&&!(o instanceof wu.FunctionCall||o instanceof Du.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
42
+ `),new ub.IncludedFile(null);this.AddOpenFilename(o);let u=null,l="";try{l=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(c){this.Error(`Failed to load: '${s}'.
43
+ Error:${c}`);}return l!=null&&(u=new n(l,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new ub.IncludedFile(u)},this.FilenameIsAlreadyOpen=s=>this._rootParser._openFilenames.includes(s),this.AddOpenFilename=s=>{this._rootParser._openFilenames.push(s);},this.RemoveOpenFilename=s=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(s),1);},this.KnotDefinition=()=>{let s=this.Parse(this.KnotDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(Je.StatementLevel.Knot),u=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new KT.Knot(s.name,u,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,u=s?.name==="function";u?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=s,o===null&&(this.Error(`Expected the name of the ${u?"function":"knot"}`),o=new ys.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new ob.FlowDecl(o,l,u)},this.KnotTitleEquals=()=>{let s=this.ParseCharactersFromString("=");return s===null||s.length<=1?null:s},this.StitchDefinition=()=>{let s=this.Parse(this.StitchDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel(Je.StatementLevel.Stitch),u=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new e1.Stitch(s.name,u,s.args,s.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let s=this.ParseString("function")!==null;s&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new ob.FlowDecl(o,u,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new Oe.CharacterSet("="),null),[new rn.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),s===null&&(s=[]),s},this.FlowDeclArgument=()=>{let s=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(s==null&&u===null)return null;let l=new VT.Argument;return o!==null&&(l.isDivertTarget=true),s!==null&&s.name==="ref"?(u===null&&this.Error("Expected an parameter name after 'ref'"),l.identifier=u,l.isByReference=true):(l.isDivertTarget?l.identifier=u:l.identifier=s,l.identifier===null&&this.Error("Expected an parameter name"),l.isByReference=false),l},this.ExternalDeclaration=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new ys.Identifier("");this.Whitespace();let u=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);u===null&&(u=[]);let l=u.map(c=>{var h;return (h=c.identifier)===null||h===void 0?void 0:h.name}).filter(An.filterUndef);return new GT.ExternalDeclaration(o,l)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let s=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(s,"expression after '~'",this.SkipToNextLine);if(o===null)return new st.ContentList;o instanceof MT.Expression&&!(o instanceof Au.FunctionCall||o instanceof Ou.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
44
44
  ~ return
45
45
  ~ var x = blah
46
46
  ~ x++
47
- ~ myFunction()`);let u=(0, wn.asOrNull)(o,wu.FunctionCall);return u&&(u.shouldPopReturnedValue=true),o.Find(wu.FunctionCall)()!==null&&(o=new rt.ContentList(o,new tn.Text(`
48
- `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l?(l instanceof Ur.NumberExpression||l instanceof ps.StringExpression||l instanceof Ff.DivertTarget||l instanceof kf.VariableReference||l instanceof o0.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):l instanceof ps.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new If.VariableAssignment({assignedExpression:l,isGlobalDeclaration:true,variableIdentifier:o})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let u=this.Expect(this.ListDefinition,"list item names");return u?(u.identifier=new ms.Identifier(o.name),new If.VariableAssignment({variableIdentifier:o,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new UT.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(u===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let l=null;if(this.ParseString("=")!==null){this.Whitespace();let c=this.Expect(this.ExpressionInt,"value to be assigned to list item");c!==null&&(l=c.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new KT.ListElementDefinition(u,s,l)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u instanceof Ur.NumberExpression||u instanceof Ff.DivertTarget||u instanceof ps.StringExpression?u instanceof ps.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new LT.ConstantDeclaration(o,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new GT.Glue(new JT.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let u=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(u===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(u);let l=(0, wn.asOrNull)(u,rt.ContentList);return l||(l=new rt.ContentList(u)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(l),l},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let l=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return l===null?null:new c0.Sequence(l,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let u=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let l of u){let c=this.BeginRule(),h=this.ParseObject(l);if(h)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(c);else return this.SucceedRule(c,h);else this.FailRule(c);}return null},this.InnerExpression=()=>{let s=this.Parse(this.Expression);return s&&(s.outputWhenComplete=true),s},this.IdentifierWithMetadata=()=>{let s=this.Identifier();return s===null?null:new ms.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let u of s)if(!(u>="0"&&u<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new Ae.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=De.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let u=this.Parse(this.InnerSequenceObjects);return u===null||u.length<=1?null:new c0.Sequence(u,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case De.SequenceType.Once:case De.SequenceType.Cycle:case De.SequenceType.Stopping:case De.SequenceType.Shuffle:case De.SequenceType.Shuffle|De.SequenceType.Stopping:case De.SequenceType.Shuffle|De.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),De.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new Ae.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let u of o)switch(u){case "!":s|=De.SequenceType.Once;break;case "&":s|=De.SequenceType.Cycle;break;case "~":s|=De.SequenceType.Shuffle;break;case "$":s|=De.SequenceType.Stopping;break}return s===0?null:s},this.SequenceTypeWordAnnotation=()=>{let s=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(s===null||s.length===0||this.ParseString(":")===null)return null;let o=0;for(let u of s)o|=u;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=De.SequenceType.Once;break;case "cycle":s=De.SequenceType.Cycle;break;case "shuffle":s=De.SequenceType.Shuffle;break;case "stopping":s=De.SequenceType.Stopping;break}return s===null?null:s},this.InnerSequenceObjects=()=>{let s=this.Parse(this.Newline)!==null,o=null;return s?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let s=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(s===null)return null;let o=[],u=false;for(let l of s)if(l==="|")u||o.push(new rt.ContentList),u=false;else {let c=l;c===null?this.Error(`Expected content, but got ${l} (this is an ink compiler bug!)`):o.push(new rt.ContentList(c)),u=true;}return u||o.push(new rt.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineSequenceElement);return s===null?null:s},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=this.StatementsAtLevel(Me.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new tn.Text(`
49
- `)),new rt.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===Me.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(s),()=>this.StatementsBreakForLevel(s))),this.StatementAtLevel=s=>{let o=this._statementRulesAtLevel[s],u=this.OneOf(o);return s===Me.StatementLevel.Top&&u instanceof l0.ReturnType&&this.Error("should not have return statement outside of a knot"),u},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],u=this.OneOf(o);return u===null?null:u},this.GenerateStatementLevelRules=()=>{let s=Object.values(Me.StatementLevel);this._statementRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]);for(let o of s){let u=[],l=[];u.push(this.Line(this.MultiDivert)),o>=Me.StatementLevel.Top&&u.push(this.KnotDefinition),u.push(this.Line(this.Choice)),u.push(this.Line(this.AuthorWarning)),o>Me.StatementLevel.InnerBlock&&u.push(this.Gather),o>=Me.StatementLevel.Knot&&u.push(this.StitchDefinition),u.push(this.Line(this.ListDeclaration)),u.push(this.Line(this.VariableDeclaration)),u.push(this.Line(this.ConstDeclaration)),u.push(this.Line(this.ExternalDeclaration)),u.push(this.Line(this.IncludeStatement)),u.push(this.LogicLine),u.push(this.LineOfMixedTextAndLogic),o<=Me.StatementLevel.Knot&&l.push(this.KnotDeclaration),o<=Me.StatementLevel.Stitch&&l.push(this.StitchDeclaration),o<=Me.StatementLevel.InnerBlock&&(l.push(this.ParseDashNotArrow),l.push(this.String("}"))),this._statementRulesAtLevel[o]=u,this._statementBreakRulesAtLevel[o]=l;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
50
- \r`),this.ParseNewline(),en.ParseSuccess),this.Line=s=>()=>{let o=this.ParseObject(s);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let s=null;if(this.tagActive){let o=new rt.ContentList;o.AddContent(new Hr.Tag(false)),o.AddContent(new Hr.Tag(true)),s=o;}else s=new Hr.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new Ae.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?en.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?en.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?en.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?en.ParseSuccess:null,this.Spaced=s=>()=>{this.Whitespace();let o=this.ParseObject(s);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let s=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)s=true;return s?en.ParseSuccess:null},this.MultiSpaced=s=>()=>{this.AnyWhitespace();let o=this.ParseObject(s);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=r,a===null?this._fileHandler=new e1.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=i;}PreProcessInputString(e){return new $T.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(Eu.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(Eu.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(Eu.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(Eu.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new Ae.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 rt.ContentList?e.AddContent(new Hr.Tag(false)):e.push(new Hr.Tag(false))),this.tagActive=false);}};Au.InkParser=se;se.LatinBasic=Pt.CharacterRange.Define("A","z",new Ae.CharacterSet().AddRange("[","`"));se.LatinExtendedA=Pt.CharacterRange.Define("\u0100","\u017F");se.LatinExtendedB=Pt.CharacterRange.Define("\u0180","\u024F");se.Greek=Pt.CharacterRange.Define("\u0370","\u03FF",new Ae.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));se.Cyrillic=Pt.CharacterRange.Define("\u0400","\u04FF",new Ae.CharacterSet().AddRange("\u0482","\u0489"));se.Armenian=Pt.CharacterRange.Define("\u0530","\u058F",new Ae.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));se.Hebrew=Pt.CharacterRange.Define("\u0590","\u05FF",new Ae.CharacterSet);se.Arabic=Pt.CharacterRange.Define("\u0600","\u06FF",new Ae.CharacterSet);se.Korean=Pt.CharacterRange.Define("\uAC00","\uD7AF",new Ae.CharacterSet);se.Latin1Supplement=Pt.CharacterRange.Define("\x80","\xFF",new Ae.CharacterSet);se.Chinese=Pt.CharacterRange.Define("\u4E00","\u9FFF",new Ae.CharacterSet);se.ListAllCharacterRanges=()=>[se.LatinBasic,se.LatinExtendedA,se.LatinExtendedB,se.Arabic,se.Armenian,se.Cyrillic,se.Greek,se.Hebrew,se.Korean,se.Latin1Supplement,se.Chinese];});var p0=S(Pu=>{Object.defineProperty(Pu,"__esModule",{value:true});Pu.GenerateStoryStats=void 0;var t1=kr(),n1=jr(),r1=Ui(),i1=Yd(),s1=rf(),a1=Cn();function o1(n){let e=n.FindAll(a1.Text)(),t=0;for(let u of e){let l=0,c=true;for(let h of u.text)h==" "||h==" "||h==`
51
- `||h=="\r"?c=true:c&&(l++,c=false);t+=l;}let r=n.FindAll(i1.Knot)(),i=n.FindAll(s1.Stitch)(),a=n.FindAll(t1.Choice)(),s=n.FindAll(r1.Gather)(u=>u.debugMetadata!=null),o=n.FindAll(n1.Divert)();return {words:t,knots:r.length,functions:r.filter(u=>u.isFunction).length,stitches:i.length,gathers:s.length,diverts:o.length-1,choices:a.length}}Pu.GenerateStoryStats=o1;});var m0=S(Ou=>{Object.defineProperty(Ou,"__esModule",{value:true});Ou.JsonFileHandler=void 0;var Rf=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}.`)};}};Ou.JsonFileHandler=Rf;});var y0=S(je=>{Object.defineProperty(je,"__esModule",{value:true});je.Compiler=je.Story=je.InkList=je.JsonFileHandler=je.StatementLevel=je.InkParser=je.CompilerOptions=void 0;var u1=Ch(),l1=Dy(),$f=wr(),c1=Vf(),h1=fe(),d1=ne(),f1=p0(),p1=Ch();Object.defineProperty(je,"CompilerOptions",{enumerable:true,get:function(){return p1.CompilerOptions}});var m1=Vf();Object.defineProperty(je,"InkParser",{enumerable:true,get:function(){return m1.InkParser}});var g1=tf();Object.defineProperty(je,"StatementLevel",{enumerable:true,get:function(){return g1.StatementLevel}});var y1=m0();Object.defineProperty(je,"JsonFileHandler",{enumerable:true,get:function(){return y1.JsonFileHandler}});var g0=is();Object.defineProperty(je,"InkList",{enumerable:true,get:function(){return g0.InkList}});Object.defineProperty(je,"Story",{enumerable:true,get:function(){return g0.Story}});var jf=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 c1.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 r;for(let i of this.runtimeStory.state.outputStream){let a=(0, d1.asOrNull)(i,h1.StringValue);if(a!==null){let s=new l1.DebugSourceRange(((r=a.value)===null||r===void 0?void 0:r.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, f1.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=r=>{let i=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),r>=i&&r<i+s.length)return a;i+=s.length;}return null},this.OnError=(r,i)=>{switch(i){case $f.ErrorType.Author:this._authorMessages.push(r);break;case $f.ErrorType.Warning:this._warnings.push(r);break;case $f.ErrorType.Error:this._errors.push(r);break}this.options.errorHandler!==null&&this.options.errorHandler(r,i);},this._inputString=e,this._options=t||new u1.CompilerOptions;}};je.Compiler=jf;});var Cs="global decl",An="___external_value___";var U;(i=>(i.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),i.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),i.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),i.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(U||={});var oC=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,uC=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,lC=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,Bu={Space_Separator:oC,ID_Start:uC,ID_Continue:lC},me={isSpaceSeparator(n){return typeof n=="string"&&Bu.Space_Separator.test(n)},isIdStartChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="$"||n==="_"||Bu.ID_Start.test(n))},isIdContinueChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||n==="$"||n==="_"||n==="\u200C"||n==="\u200D"||Bu.ID_Continue.test(n))},isDigit(n){return typeof n=="string"&&/[0-9]/.test(n)},isHexDigit(n){return typeof n=="string"&&/[0-9A-Fa-f]/.test(n)}},Mu,Le,Ht,_s,rn,_t,Se,zu,Zr,cC=function(e,t){Mu=String(e),Le="start",Ht=[],_s=0,rn=1,_t=0,Se=void 0,zu=void 0,Zr=void 0;do Se=hC(),pC[Le]();while(Se.type!=="eof");return typeof t=="function"?Gu({"":Zr},"",t):Zr};function Gu(n,e,t){let r=n[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let i=0;i<r.length;i++){let a=String(i),s=Gu(r,a,t);s===void 0?delete r[a]:Object.defineProperty(r,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let i in r){let a=Gu(r,i,t);a===void 0?delete r[i]:Object.defineProperty(r,i,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(n,e,r)}var R,I,Yr,zt,W;function hC(){for(R="default",I="",Yr=false,zt=1;;){W=Ut();let n=ep[R]();if(n)return n}}function Ut(){if(Mu[_s])return String.fromCodePoint(Mu.codePointAt(_s))}function D(){let n=Ut();return n===`
52
- `?(rn++,_t=0):n?_t+=n.length:_t++,n&&(_s+=n.length),n}var ep={default(){switch(W){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
53
- `:case "\r":case "\u2028":case "\u2029":D();return;case "/":D(),R="comment";return;case void 0:return D(),ae("eof")}if(me.isSpaceSeparator(W)){D();return}return ep[Le]()},comment(){switch(W){case "*":D(),R="multiLineComment";return;case "/":D(),R="singleLineComment";return}throw oe(D())},multiLineComment(){switch(W){case "*":D(),R="multiLineCommentAsterisk";return;case void 0:throw oe(D())}D();},multiLineCommentAsterisk(){switch(W){case "*":D();return;case "/":D(),R="default";return;case void 0:throw oe(D())}D(),R="multiLineComment";},singleLineComment(){switch(W){case `
54
- `:case "\r":case "\u2028":case "\u2029":D(),R="default";return;case void 0:return D(),ae("eof")}D();},value(){switch(W){case "{":case "[":return ae("punctuator",D());case "n":return D(),Pn("ull"),ae("null",null);case "t":return D(),Pn("rue"),ae("boolean",true);case "f":return D(),Pn("alse"),ae("boolean",false);case "-":case "+":D()==="-"&&(zt=-1),R="sign";return;case ".":I=D(),R="decimalPointLeading";return;case "0":I=D(),R="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=D(),R="decimalInteger";return;case "I":return D(),Pn("nfinity"),ae("numeric",1/0);case "N":return D(),Pn("aN"),ae("numeric",NaN);case '"':case "'":Yr=D()==='"',I="",R="string";return}throw oe(D())},identifierNameStartEscape(){if(W!=="u")throw oe(D());D();let n=Ju();switch(n){case "$":case "_":break;default:if(!me.isIdStartChar(n))throw Qf();break}I+=n,R="identifierName";},identifierName(){switch(W){case "$":case "_":case "\u200C":case "\u200D":I+=D();return;case "\\":D(),R="identifierNameEscape";return}if(me.isIdContinueChar(W)){I+=D();return}return ae("identifier",I)},identifierNameEscape(){if(W!=="u")throw oe(D());D();let n=Ju();switch(n){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!me.isIdContinueChar(n))throw Qf();break}I+=n,R="identifierName";},sign(){switch(W){case ".":I=D(),R="decimalPointLeading";return;case "0":I=D(),R="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=D(),R="decimalInteger";return;case "I":return D(),Pn("nfinity"),ae("numeric",zt*(1/0));case "N":return D(),Pn("aN"),ae("numeric",NaN)}throw oe(D())},zero(){switch(W){case ".":I+=D(),R="decimalPoint";return;case "e":case "E":I+=D(),R="decimalExponent";return;case "x":case "X":I+=D(),R="hexadecimal";return}return ae("numeric",zt*0)},decimalInteger(){switch(W){case ".":I+=D(),R="decimalPoint";return;case "e":case "E":I+=D(),R="decimalExponent";return}if(me.isDigit(W)){I+=D();return}return ae("numeric",zt*Number(I))},decimalPointLeading(){if(me.isDigit(W)){I+=D(),R="decimalFraction";return}throw oe(D())},decimalPoint(){switch(W){case "e":case "E":I+=D(),R="decimalExponent";return}if(me.isDigit(W)){I+=D(),R="decimalFraction";return}return ae("numeric",zt*Number(I))},decimalFraction(){switch(W){case "e":case "E":I+=D(),R="decimalExponent";return}if(me.isDigit(W)){I+=D();return}return ae("numeric",zt*Number(I))},decimalExponent(){switch(W){case "+":case "-":I+=D(),R="decimalExponentSign";return}if(me.isDigit(W)){I+=D(),R="decimalExponentInteger";return}throw oe(D())},decimalExponentSign(){if(me.isDigit(W)){I+=D(),R="decimalExponentInteger";return}throw oe(D())},decimalExponentInteger(){if(me.isDigit(W)){I+=D();return}return ae("numeric",zt*Number(I))},hexadecimal(){if(me.isHexDigit(W)){I+=D(),R="hexadecimalInteger";return}throw oe(D())},hexadecimalInteger(){if(me.isHexDigit(W)){I+=D();return}return ae("numeric",zt*Number(I))},string(){switch(W){case "\\":D(),I+=dC();return;case '"':if(Yr)return D(),ae("string",I);I+=D();return;case "'":if(!Yr)return D(),ae("string",I);I+=D();return;case `
55
- `:case "\r":throw oe(D());case "\u2028":case "\u2029":mC(W);break;case void 0:throw oe(D())}I+=D();},start(){switch(W){case "{":case "[":return ae("punctuator",D())}R="value";},beforePropertyName(){switch(W){case "$":case "_":I=D(),R="identifierName";return;case "\\":D(),R="identifierNameStartEscape";return;case "}":return ae("punctuator",D());case '"':case "'":Yr=D()==='"',R="string";return}if(me.isIdStartChar(W)){I+=D(),R="identifierName";return}throw oe(D())},afterPropertyName(){if(W===":")return ae("punctuator",D());throw oe(D())},beforePropertyValue(){R="value";},afterPropertyValue(){switch(W){case ",":case "}":return ae("punctuator",D())}throw oe(D())},beforeArrayValue(){if(W==="]")return ae("punctuator",D());R="value";},afterArrayValue(){switch(W){case ",":case "]":return ae("punctuator",D())}throw oe(D())},end(){throw oe(D())}};function ae(n,e){return {type:n,value:e,line:rn,column:_t}}function Pn(n){for(let e of n){if(Ut()!==e)throw oe(D());D();}}function dC(){switch(Ut()){case "b":return D(),"\b";case "f":return D(),"\f";case "n":return D(),`
56
- `;case "r":return D(),"\r";case "t":return D()," ";case "v":return D(),"\v";case "0":if(D(),me.isDigit(Ut()))throw oe(D());return "\0";case "x":return D(),fC();case "u":return D(),Ju();case `
57
- `:case "\u2028":case "\u2029":return D(),"";case "\r":return D(),Ut()===`
58
- `&&D(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw oe(D());case void 0:throw oe(D())}return D()}function fC(){let n="",e=Ut();if(!me.isHexDigit(e)||(n+=D(),e=Ut(),!me.isHexDigit(e)))throw oe(D());return n+=D(),String.fromCodePoint(parseInt(n,16))}function Ju(){let n="",e=4;for(;e-- >0;){let t=Ut();if(!me.isHexDigit(t))throw oe(D());n+=D();}return String.fromCodePoint(parseInt(n,16))}var pC={start(){if(Se.type==="eof")throw On();Wu();},beforePropertyName(){switch(Se.type){case "identifier":case "string":zu=Se.value,Le="afterPropertyName";return;case "punctuator":bs();return;case "eof":throw On()}},afterPropertyName(){if(Se.type==="eof")throw On();Le="beforePropertyValue";},beforePropertyValue(){if(Se.type==="eof")throw On();Wu();},beforeArrayValue(){if(Se.type==="eof")throw On();if(Se.type==="punctuator"&&Se.value==="]"){bs();return}Wu();},afterPropertyValue(){if(Se.type==="eof")throw On();switch(Se.value){case ",":Le="beforePropertyName";return;case "}":bs();}},afterArrayValue(){if(Se.type==="eof")throw On();switch(Se.value){case ",":Le="beforeArrayValue";return;case "]":bs();}},end(){}};function Wu(){let n;switch(Se.type){case "punctuator":switch(Se.value){case "{":n={};break;case "[":n=[];break}break;case "null":case "boolean":case "numeric":case "string":n=Se.value;break}if(Zr===void 0)Zr=n;else {let e=Ht[Ht.length-1];Array.isArray(e)?e.push(n):Object.defineProperty(e,zu,{value:n,writable:true,enumerable:true,configurable:true});}if(n!==null&&typeof n=="object")Ht.push(n),Array.isArray(n)?Le="beforeArrayValue":Le="beforePropertyName";else {let e=Ht[Ht.length-1];e==null?Le="end":Array.isArray(e)?Le="afterArrayValue":Le="afterPropertyValue";}}function bs(){Ht.pop();let n=Ht[Ht.length-1];n==null?Le="end":Array.isArray(n)?Le="afterArrayValue":Le="afterPropertyValue";}function oe(n){return Ss(n===void 0?`JSON5: invalid end of input at ${rn}:${_t}`:`JSON5: invalid character '${tp(n)}' at ${rn}:${_t}`)}function On(){return Ss(`JSON5: invalid end of input at ${rn}:${_t}`)}function Qf(){return _t-=5,Ss(`JSON5: invalid identifier character at ${rn}:${_t}`)}function mC(n){console.warn(`JSON5: '${tp(n)}' in strings is not valid ECMAScript; consider escaping`);}function tp(n){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[n])return e[n];if(n<" "){let t=n.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return n}function Ss(n){let e=new SyntaxError(n);return e.lineNumber=rn,e.columnNumber=_t,e}var gC=function(e,t,r){let i=[],a="",s,o,u="",l;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(r=t.space,l=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let m of t){let C;typeof m=="string"?C=m:(typeof m=="number"||m instanceof String||m instanceof Number)&&(C=String(m)),C!==void 0&&s.indexOf(C)<0&&s.push(C);}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),u=" ".substr(0,r)):typeof r=="string"&&(u=r.substr(0,10)),c("",{"":e});function c(m,C){let b=C[m];switch(b!=null&&(typeof b.toJSON5=="function"?b=b.toJSON5(m):typeof b.toJSON=="function"&&(b=b.toJSON(m))),o&&(b=o.call(C,m,b)),b instanceof Number?b=Number(b):b instanceof String?b=String(b):b instanceof Boolean&&(b=b.valueOf()),b){case null:return "null";case true:return "true";case false:return "false"}if(typeof b=="string")return h(b);if(typeof b=="number")return String(b);if(typeof b=="object")return Array.isArray(b)?g(b):f(b)}function h(m){let C={"'":.1,'"':.2},b={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},v="";for(let _=0;_<m.length;_++){let y=m[_];switch(y){case "'":case '"':C[y]++,v+=y;continue;case "\0":if(me.isDigit(m[_+1])){v+="\\x00";continue}}if(b[y]){v+=b[y];continue}if(y<" "){let E=y.charCodeAt(0).toString(16);v+="\\x"+("00"+E).substring(E.length);continue}v+=y;}let d=l||Object.keys(C).reduce((_,y)=>C[_]<C[y]?_:y);return v=v.replace(new RegExp(d,"g"),b[d]),d+v+d}function f(m){if(i.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");i.push(m);let C=a;a=a+u;let b=s||Object.keys(m),v=[];for(let _ of b){let y=c(_,m);if(y!==void 0){let E=p(_)+":";u!==""&&(E+=" "),E+=y,v.push(E);}}let d;if(v.length===0)d="{}";else {let _;if(u==="")_=v.join(","),d="{"+_+"}";else {let y=`,
59
- `+a;_=v.join(y),d=`{
60
- `+a+_+`,
61
- `+C+"}";}}return i.pop(),a=C,d}function p(m){if(m.length===0)return h(m);let C=String.fromCodePoint(m.codePointAt(0));if(!me.isIdStartChar(C))return h(m);for(let b=C.length;b<m.length;b++)if(!me.isIdContinueChar(String.fromCodePoint(m.codePointAt(b))))return h(m);return m}function g(m){if(i.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");i.push(m);let C=a;a=a+u;let b=[];for(let d=0;d<m.length;d++){let _=c(String(d),m);b.push(_!==void 0?_:"null");}let v;if(b.length===0)v="[]";else if(u==="")v="["+b.join(",")+"]";else {let d=`,
62
- `+a,_=b.join(d);v=`[
63
- `+a+_+`,
64
- `+C+"]";}return i.pop(),a=C,v}},yC={parse:cC,stringify:gC},vC=yC,Qr=vC;var rp="\xA7SPACE\xA7",ip="\xA7DOUBLE_QUOTES\xA7",sp="\xA7QUOTES\xA7",ap="SPECIAL_\xA7QUOTES\xA7",op="\xA7CURLY_BRACKETS1\xA7",CC="\xA7INK_VAR\xA7",up="\xA7CURLY_BRACKETS2\xA7",xt;(v=>{let n=[],e=[];async function t(d,_){for(let y=0;y<n.length;y++)try{let{validation:E}=n[y].opts;if(E instanceof RegExp){if(!E.test(d.join(" ")))continue}else if(E instanceof zod.ZodType&&!E.safeParse(d).success)continue;let w=await n[y].fn(d,_,h);if(w===!0||typeof w=="string")return w}catch{}return false}function r(d,_={name:"custom-command",validation:/^/}){n.unshift({fn:d,opts:_});}v.add=r;function i(){return [...e.map(d=>d.opts),...n.map(d=>d.opts)]}v.info=i;function a(d,_){e.unshift({fn:d,opts:_});}v.addMapper=a;function s(){n.length=0;}v.clear=s;function o(){e.length=0;}v.clearMappers=o;async function u(d,_,y){try{let E=l(d),w=await t(E,y);return w===!0?void 0:typeof w=="string"?(w.startsWith("#")&&(w=w.substring(1)),await v.run(w,_,y)):c(E,_)}catch(E){throw U.error("Error parsing ink hashtag-command",d),E}}v.run=u;function l(d,_){if(d=d.replaceAll('\\"',ip),d=d.replaceAll("\\'",sp),d=d.replaceAll("\\`",ap),d=d.replaceAll("\\{",op),d=d.replaceAll("\\}",up),_?.mergeInkVariables){let P;do P=d,d=d.replace(/\{[^{}:]*\}/g,CC);while(d!==P)}d=d.replaceAll("{"," { "),d=d.replaceAll("}"," } "),d=d.replaceAll(op,"{"),d=d.replaceAll(up,"}");let y=[],E,w="";for(let P=0;P<d.length;P++){let x=d[P];x==='"'||x==="'"||x==="`"?E===void 0?(y.push(w),w="",E=x,w+=x):E===x?(E=void 0,w+=x,y.push(w),w=""):w+=x:w+=x;}return w!==""&&y.push(w),y.forEach((P,x)=>{x%2===1&&(y[x]=P.replaceAll(" ",rp));}),d=y.join(""),y=d.split(" ").filter(P=>P!==""),y=y.map(P=>P.replaceAll(rp," ").replaceAll(ip,'"').replaceAll(sp,"'").replaceAll(ap,"`")),y=g(y),y=y.flatMap(P=>b(P)),y=y.map(P=>P.startsWith('"')&&P.endsWith('"')||P.startsWith("'")&&P.endsWith("'")||P.startsWith("`")&&P.endsWith("`")?P.slice(1,-1):P),y}v.convertTagTolist=l;function c(d,_,y){for(let E of e){let{validation:w}=E.opts,P=false;if(w instanceof RegExp?P=w.test(d.join(" ")):w instanceof zod.ZodType&&(P=w.safeParse(d).success),P)return E.fn(d,_)}y?.silent||U.error("The operation is not valid",d);}v.convertOperation=c;function h(d){if(d.length===0)return {};if(d.length%2!==0)throw U.error("The props list must have a pair number of elements",d),new Error("The props list must have a pair number of elements");let _="{";d.forEach((y,E)=>{if(E%2===0)_+=`"${y}": `;else {switch(y){case "null":case "undefined":case "true":case "false":_+=`${y}`;break;default:p(y)?(y=f(y),_+=`"${y}"`):y.startsWith("{")&&y.endsWith("}")?_+=`${y}`:y.startsWith('"')&&y.endsWith('"')?_+=`${y}`:Number.isNaN(parseFloat(y))?_+=`"${y}"`:_+=`${y}`;}E<d.length-1&&(_+=", ");}}),_+="}";try{return Qr.parse(_)}catch(y){throw U.error("Error parsing ink json",_),y}}v.convertListStringToObj=h;function f(d){return d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`")?d.substring(1,d.length-1):d}function p(d){return !!(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`"))}function g(d){return m(d).tokens}v.mergeJsonBlocks=g;function m(d){let _=[],y=false;for(let E=0;E<d.length;E++){let w=d[E];if(w!=="{"){_.push(w);continue}let P=C(d,E);if(P===-1){_.push(w);continue}let x=m(d.slice(E+1,P)),H=["{",...x.tokens,"}"],be=H.join(" ");if(!x.hasInvalidMatchedBlock)try{Qr.parse(be),_.push(be),E=P;continue}catch{}y=true,_.push(...H),E=P;}return {tokens:_,hasInvalidMatchedBlock:y}}function C(d,_){let y=0;for(let E=_;E<d.length;E++)if(d[E]==="{")y++;else if(d[E]==="}"&&(y--,y===0))return E;return -1}function b(d){if(d==="["||d==="]")return [d];let _=0,y=d.length,E=[];for(;_<y&&d[_]==="[";)E.push("["),_++;let w=[];for(;y>_&&d[y-1]==="]";)w.unshift("]"),y--;let P=d.slice(_,y);return P===""?[...E,...w]:[...E,P,...w]}})(xt||={});var lp=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],cp=["+","-","/","*","%","POW","RANDOM","L^"],hp=["INT","FLOOR","FLOAT"];function nr(n,e){if(n.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(n)&&(n=n.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!n.startsWith(".")))return n.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(n)&&n.includes("g-")){let r=n.split("g-");return Hu(e)+"_|_"+"g-"+r[r.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(n);)t++,n=n.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(n)&&e){let r=n.substring(1);return Hu(e,t)+"_|_"+r.replaceAll(".","_|_")}return n.replaceAll(".","_|_")||Hu(e,t).replaceAll(".","_|_")}function Hu(n,e=0){let t=n.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var dp="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Tt(n){return n.startsWith("^")&&(n=n.substring(1)),n=n.replaceAll("\\\\",dp),n=n.replaceAll("\\n",`
65
- `),n=n.replaceAll("\\t"," "),n=n.replaceAll(" "," "),n=n.replaceAll(dp,"\\\\"),n}var bC={version:"1.14.0"};var fp=`https://pixi-vn.com/schemas/${bC.version}/schema.json`,pp=["==","!=","<","<=",">",">=","CONTAINS"];function sn(n,e,t,r){let{functions:i}=r;n=n.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return n.forEach(s=>{if(typeof s=="string")switch(s){case "&&":case "||":if(a.length>=2){let o={type:"union",unionType:s==="&&"?"and":"or",conditions:[a[a.length-2],a[a.length-1]]};a.pop(),a.pop(),a.push(o);}break;case "!":if(a.length===0)U.error("Error parsing ink file: Conditional statement is not valid",n);else {let o={type:"union",unionType:"not",condition:a[a.length-1]};a[a.length-1]=o;}break;case "!?":if(a.length>1){let o={type:"union",unionType:"not",condition:{type:"compare",operator:"CONTAINS",leftValue:a[a.length-2],rightValue:a[a.length-1]}};a.pop(),a.pop(),a.push(o);}else U.error("Error parsing ink file: Conditional statement is not valid",n);break;default:if(pp.includes(s))if(a.length<2)U.error("Error parsing ink file: Conditional statement is not valid",n);else {let o={type:"compare",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(cp.includes(s))if(a.length<2)U.error("Error parsing ink file: Conditional statement is not valid",n);else {s==="L^"&&(s="INTERSECTION");let o={type:"arithmetic",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(hp.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(Tt(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),u=o.pop(),l=o.pop();if(l===void 0||u===void 0){U.error("Error parsing ink file: Conditional statement is not valid",n);return}let c=Number(l),h=o.join(".");if(h.includes("^.")){let p=h.split("."),g=p[p.length-1].replaceAll(".","_|_");p.pop(),h=`${p.join(".")}.${g}`,u.includes("c-")&&(h=h+"_|_"+u);}else h=h.replaceAll(".","_|_");let f=nr(h,e);if(!f)return;a.push({type:"compare",leftValue:Uu(f),operator:">=",rightValue:{type:"value",value:c}});}else {let o=nr(s["CNT?"],e);if(!o)return;a.push(Uu(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(xn({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],u=i.find(c=>c.name===o);if(!u){U.error(`Error parsing ink file: Function ${o} is not defined`,n);return}let l=[];for(let c=0;c<u.args;c++)a.length!==0&&l.push(a.pop());a.push({type:"function",functionName:o,args:l.reverse()});}else if(typeof s=="object"&&"^->"in s)s["^->"].includes("$r")||a.push(s["^->"]);else if(typeof s=="object"&&"list"in s){let o=Object.values(s.list).map(u=>u);a.push(o);}else a.push(s);}),a}function Ku(n,e,t,r){return sn(n,e,t,r)}function xn(n,e,t){let{key:r,defaultType:i}=n,a=e.indexOf(r);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:i,key:r}}function ei(n,e,t){let{key:r,value:i,defaultType:a,artmeticValue:s}=n,o=e.indexOf(r);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:i}];if(s){if(typeof i=="object"&&"list"in i){let u=Object.values(i.list).map(l=>l);return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:u}]}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:i}]}else if(typeof i=="object"){if("list"in i&&typeof i.list=="object"){if("origins"in i&&Array.isArray(i.origins)&&i.origins.length>0)return i.origins.reduce(u=>(u.push({type:"value",storageOperationType:"set",storageType:a,key:r,value:Object.values(t.enums[r])}),Object.entries(t.enums[r]).forEach(([l,c])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${r}.${l}`,value:c});}),u),[]);{let u=new Set,l=Object.entries(i.list).reduce((c,[h,f])=>{let[p,g]=h.split(".");return c.push({type:"value",storageOperationType:"set",storageType:a,key:g,value:f}),u.add(p),c},[]);return u.forEach(c=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:c,value:Object.values(t.enums[c])});}),r in t.enums?Object.entries(t.enums[r]).forEach(([c,h])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${r}.${c}`,value:h});}):l.push({type:"value",storageOperationType:"set",storageType:a,key:r,value:Object.values(i.list)}),l}}else if(typeof i=="object"&&"VAR?"in i){if(typeof i["VAR?"]=="string"&&i["VAR?"].includes(".")){let[u,l]=i["VAR?"].split(".");if(u in t.enums&&l in t.enums[u])return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:t.enums[u][l]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:xn({key:i["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:i}]}function Uu(n){return {type:"value",storageType:"label",storageOperationType:"get",label:n}}function Xu(n,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(n)?"call":"jump"}function Es(n,e){if(e){if(typeof e=="string")e.startsWith("^")&&n.push(Tt(e));else if(typeof e=="object"&&"type"in e)switch(e.type){case "value":case "function":console.warn("Warning: trying to add a value or function operation as text. This is likely a mistake, so it will be ignored.");break;default:n.push(e);}}}function Yu(n,e,t,r,i,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:u=false}=a;return SC(n,e,t,r,i,{isNewLine:s,isHashtagScript:o,isThreads:u})}function SC(n,e,t,r,i,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:u}=a;if(o){if(Array.isArray(e)&&e.length>0){let l={goNextStep:true},c=[];try{if(e.length===1&&typeof e[0]=="string"){let h=e[0],f=xt.convertTagTolist(h),p=xt.convertOperation(f,l,{silent:!0});p&&(p.$origin=h,c.push(p));}}catch{}c.length===0&&c.push({type:"operationtoconvert",values:e}),n.push({...l,operations:c});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&n.length>0){let l=n[n.length-1];!l.glueEnabled&&!l.operations&&!l.labelToOpen&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),n[n.length-1]=l;}typeof e=="string"?n.push(EC(Tt(e),r.characterIds)):n.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")n.push({end:"game_end"});else if(e==="done")n.push({end:"label_end",goNextStep:true});else if(e==="<>")if(n.length>0){let l=n[n.length-1];l.glueEnabled=true;let c=l.operations!==void 0&&l.dialogue===void 0;l.labelToOpen||(l.goNextStep=c?true:!s),n[n.length-1]=l;}else n.push({glueEnabled:true,goNextStep:true});}else if(typeof e=="object"){if("type"in e)switch(e.type){case "value":e.storageOperationType==="set"?(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=Tt(e.value)),n.push({goNextStep:true,operations:[e]})):console.warn("Warning: trying to add a value get operation as step. This is likely a mistake, so it will be ignored.");break;case "function":n.push({goNextStep:true,operations:[e]});break;default:if(!s&&n.length>0){let l=n[n.length-1];!l.glueEnabled&&!l.operations&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),n[n.length-1]=l;}n.push({conditionalStep:e});}else if("->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&n.length>0&&n[n.length-1]?.dialogue===void 0&&(l=void 0),!s&&n.length>0){let c=n[n.length-1];c.labelToOpen||(c.goNextStep=true),n[n.length-1]=c;}if(e.params&&e.params.length===0&&delete e.params,e.var)n.push({labelToOpen:{label:xn({key:e["->"],defaultType:"storage"},i),type:u?"call":"jump",params:e.params},glueEnabled:l});else {let c=nr(e["->"],t);if(!c)return;n.push({labelToOpen:{label:c,type:Xu(c,u),params:e.params},glueEnabled:l});}}else if("->t->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&n.length>0&&n[n.length-1]?.dialogue===void 0&&(l=void 0),!s&&n.length>0){let h=n[n.length-1];h.labelToOpen||(h.goNextStep=true),n[n.length-1]=h;}e.params&&e.params.length===0&&delete e.params;let c=nr(e["->t->"],t);if(!c)return;n.push({labelToOpen:{label:c,type:"call",params:e.params},glueEnabled:l});}}}function EC(n,e){let t;if(n.includes(": ")){let r=n.split(": "),i=r[0],a=r.slice(1).join(": ");(e?.has(i)||characters.RegisteredCharacters.has(i))&&(t=i,n=a);}return t?{dialogue:{character:t,text:n}}:{dialogue:n}}function Zu(n,e,t,r=true,i=false){return wC(n,e,t,r,i)}function wC(n,e,t,r,i=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?n.push(Tt(e)):n.push(e):typeof e=="object"&&"type"in e&&n.push(e));}function ws(n,e,t,r){if(n.length===0){U.error("Error parsing ink file: Arithmetic statement is not valid",n);return}let i=sn(n,e,t,r);if(i.length===1){let a=i[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function rr(n,e,t,r="",i,a,s=void 0){let o=[],u="sequential",l=false,c=true;n.forEach(p=>{p==="%"&&(u="loop"),p==="seq"&&(u="random"),p==="MIN"&&(l=true);});let h=n[n.length-1];return Object.keys(h).forEach(p=>{let g=h[p];if(Array.isArray(g)&&g.length>3){g=g.slice(1,g.length-2);let m=[];an(g,r,i,m,e,e,t,ir,s,true,a),m.length===1?o.push(m[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:m});}else Array.isArray(g)&&g.length===3&&(c=false);}),u==="sequential"?{type:"stepswitch",elements:o,choiceType:u,end:c?"lastItem":void 0,nestedId:s}:l&&u==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:c?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:u}}function an(n,e,t,r=[],i,a,s,o,u=void 0,l=true,c=[]){let h=false,f=[],p=false,g=false,m=false,C=[],b=[];if(t.preDialog[e]&&(l=false,i(r,`^${t.preDialog[e].text}`,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),t.preDialog[e].glue&&i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),delete t.preDialog[e]),n.includes("visit")){let d=rr(n,a,s,e,t,c,u);d&&(!l&&r.length>0&&i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}));return}let v=n[0];if(v&&typeof v=="object"&&"temp="in v){for(;n[0]&&typeof n[0]=="object"&&"temp="in n[0];)c.push(n[0]["temp="]),n.shift();c=c.reverse();}if(n.forEach((d,_)=>{if(g){if(typeof d=="string"&&d==="/#"){let y=[];an(b,e,t,y,Zu,Zu,s,o,u,l),i(r,y,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),g=false,b=[];}else b.push(d);return}else if(h)if(Array.isArray(d))f.push(d);else if(d&&typeof d=="object")"CNT?"in d?_>0&&n[_-1]==="ev"?(p=true,C.push(d)):p?C.push(d):(f.push(d),l=false):"VAR="in d||"temp="in d?ei({key:"VAR="in d?d["VAR="]:d["temp="],value:n[_-1],defaultType:"VAR="in d?"storage":"tempstorage"},c,t).forEach(E=>{if(E.value&&typeof E.value=="string"&&E.value==="/str"&&(E.value=n[_-2]),E.value&&typeof E.value=="object"&&"^->"in E.value&&(E.value=E.value["^->"]),f.length>1){let w=ws(f,e,c,t);f=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"&&(E.value=w.operation);}(typeof E.key!="string"||!E.key.includes("$r"))&&(i(r,E,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=true);}):"VAR?"in d?f.push(d):"^->"in d?d["^->"].includes("$r")||f.push(d):("f()"in d||"list"in d&&typeof d.list=="object")&&f.push(d);else switch(d){case "/ev":p&&C.push(d),h=false,f.push(d);break;case "out":if(f.length>0){let y=f[f.length-1];if(y&&typeof y=="object"&&"VAR?"in y){f.pop();let E=xn({key:y["VAR?"],defaultType:"storage"},c);i(r,E,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m});}else {let E=[];for(;f.length>0&&f[f.length-1]!=="/ev";)E.push(f.pop());E=E.reverse();let w=ws(E,e,c,t);f=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"?i(r,{storageOperationType:"get",storageType:"logic",operation:w.operation,type:"value"},e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}):(i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),w=`^${w}`,i(r,w,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}));}l=false;}break;case "pop":{let y=f[f.length-1];if(y&&typeof y=="object"&&"f()"in y){let E=[];for(;f.length>0&&f[f.length-1]!=="/ev";)E.push(f.pop());E=E.reverse();let w=sn(E,e,c,t);f=[],w.forEach(P=>{P&&typeof P=="object"&&"type"in P&&P.type==="function"?i(r,P,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}):U.warn("Unhandled case: value is not a function",P);}),l=false;}else f.push(d);return}default:f.push(d);}else if(typeof d=="string")if(d.startsWith("^"))i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;else if(d==="ev")h=true;else if(d===`
66
- `)l=true;else if(d==="done"||d==="end")i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;else if(d==="<>")i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;else if(d==="nop"&&p){let y=mp(C,a,s,e,t,c,u);y&&i(r,y,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),p=false,C=[];}else d==="#"?g=true:d==="thread"&&(m=true);else if(Array.isArray(d))if(p)C.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 y=[],E=[];for(;f.length>0&&f[f.length-1]!=="/ev";)y.push(f.pop());C=[...C,...y.reverse()],p=true,E.push(d.pop()),E.push(d.pop()),C=[...C,...d],C.push(E);}else if(d.length>1&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"#n"in d[d.length-1]){let y=d.pop();if(!y){U.error("Error parsing ink file: el is undefined");return}let E=y["#n"];delete y["#n"],d.push(y),i(r,{"->":e?e+"_|_"+E:E},e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),s({[E]:d},e,t);}else an(d,e,t,r,i,a,s,o,u,l,c);else if(d&&typeof d=="object")if("->"in d&&typeof d["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->"])){let y=[];f.length>0&&(y=Ku(["ev",...f],e,c,t)),d.params=y,i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;}else if("->t->"in d&&typeof d["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->t->"])){let y=[];f.length>0&&(y=Ku(["ev",...f],e,c,t)),d.params=y,i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(f.push(d),l=false);else if("s"in d&&Array.isArray(d.s))f.push(d),l=false;else if("CNT?"in d)f.push(d),l=false;else if("VAR="in d||"temp="in d){let y="VAR="in d?d["VAR="]:d["temp="],E,w=[];if(y!=="$r"){for(f.pop(),f[f.length-1]==="/ev"&&f.pop();f.length>0&&f[f.length-1]!=="/ev";)w.push(f.pop());w=w.reverse(),E=ws(w,e,c,t),f=[],ei({key:y,value:E,defaultType:"VAR="in d?"storage":"tempstorage",artmeticValue:true},c,t).forEach(x=>{(x.value!==void 0||x.value!==null)&&i(r,x,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m});}),l=false;}}else s(d,e,t);}),o(f,r,e,t,c),e.includes("_|_")&&r.length===2){let d=r[0],_=r[1];d&&_&&typeof d=="object"&&"dialogue"in d&&typeof _=="object"&&"labelToOpen"in _&&d.dialogue===" "&&_.labelToOpen&&(r.shift(),delete _.glueEnabled,r[0]=_);}}function el(n,e,t,r,i,a){if(e.length===0)return;let s=sn(e,r,t,i);if(s.length===1){let o={type:"ifelse",condition:s[0],then:n,else:a};return o.else||delete o.else,o}else if(s.length>1){let o={type:"ifelse",condition:{type:"union",unionType:"and",conditions:s},then:n,else:a};return o.else||delete o.else,o}}function mp(n,e,t,r,i,a,s=void 0){if(n.length===0){U.error("Error parsing ink file: Conditional statement is not valid",n);return}let o=[],u=[];if(n.forEach(h=>{Array.isArray(h)?u.push(h):typeof h=="string"&&h==="du"?i.du?o.push(i.du):i.du=o[o.length-1]:(typeof h!="string"||h!=="/ev")&&o.push(h);}),u.length===0){U.error("Error parsing ink file: Conditional statement is not valid",u);return}let l=Qu(u[0],e,t,`${r}${"_|_"}then`,i,a,`${s||""}then`),c;return u.length===2?c=Qu(u[1],e,t,`${r}${"_|_"}else`,i,a,`${s||""}else`):u.length>2?(u.shift(),u.push("nop"),u=[{b:u}],c=Qu(u,e,t,r,i,a,`${s||""}else`)):c=void 0,i.du=void 0,el(l,o,a,r,i,c)}function Qu(n,e,t,r,i,a,s=void 0){let o=[];for(let l of n)typeof l=="object"&&"b"in l&&(l.b=l.b.filter(c=>c!==null&&!(typeof c=="object"&&"->"in c&&new RegExp(/.*\.[0-9]/).test(c["->"]))),an(l.b,r,i,o,e,e,t,ir,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function tl(n="",e=""){let t=Array.isArray(n)?n:[n],r=Array.isArray(e)?e:[e];return [...new Set([...t,...r])]}function ir(n,e,t,r,i){if(n.length>0){let a={};gp(n,a,i,r);for(let[s,o]of Object.entries(a)){let u=t+"_|_"+s,l={text:o.text.length===1?o.text[0]:o.text,label:u,props:{},type:Xu(u,false),oneTime:o.onetime};o.text.length===0&&(l.onlyHaveNoChoice=true,l.autoSelect=true),l.oneTime===false&&delete l.oneTime;let c=el(l,o.conditions,i,t,r)||l,h=e[e.length-1];if(typeof h=="object"&&h&&"type"in h&&(h={conditionalStep:h}),e.length>0&&typeof h=="object"&&h&&"choices"in h&&h.choices){let f=h.choices;f&&Array.isArray(f)?f.push(c):U.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,f),h.choices=f.sort((p,g)=>{try{let m=p.label.split("."),C=m[m.length-1].replaceAll(".","_|_"),b=g.label.split("."),v=b[b.length-1].replaceAll(".","_|_");if(C.includes("c-")&&v.includes("c-")){let d=C.split("c-")[1],_=Number(d),y=v.split("c-")[1],E=Number(y);return _-E}}catch{}return 0});}else e.push({choices:[c]});o.preDialog&&(r.preDialog[u]={...o.preDialog});}}}function gp(n,e,t,r,i){let a=[],s="",o="",u=false,l=[];for(let c=0;c<n.length;c++){let h=n[c];if(typeof h=="string")h.startsWith("^")?a.push(Tt(h)):lp.includes(h)&&l.push(h);else if(Array.isArray(h)&&h.includes("visit")){let f=rr(h,Es,(p,g,m)=>{},i,r,t);a.push(f);}else if(h&&typeof h=="object")if("*"in h&&typeof h["*"]&&typeof h["*"]=="string")h["*"].includes("c")&&(s=`c${h["*"].split("c")[1]}`,h.flg&16&&(u=true));else if("s"in h&&Array.isArray(h.s)){let f=yp(h.s),p=h.s.includes("<>");f&&(i&&e[i]?(e[i].preDialog={text:f,glue:p},e[i].text=tl(f,e[i].text)):(a.push(f),o=f));}else ("CNT?"in h||"VAR?"in h)&&l.push(h);else l.push(h);if(s){e[s]?e[s].text=tl(a,e[s].text):e[s]={text:a,onetime:u,conditions:l},o&&(e[s].preDialog={text:o,glue:false});let f=n.slice(c+1);gp(f,e,t,r,s);return}}}function yp(n){for(let e of n)if(typeof e=="string"){if(e.startsWith("^"))return Tt(e)}else if(Array.isArray(e)){let t=yp(e);if(t)return t}}var nl;(i=>{function n(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:u=[],enums:l={},functions:c=[],preDialog:h={},characterIds:f}=s,p={$schema:fp};if(p.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:u,enums:l,functions:c,preDialog:h,characterIds:f}),p.labels&&Cs in p.labels){let g=p.labels[Cs];delete p.labels[Cs],g.forEach(m=>{m.operations&&(p.initialOperations=p.initialOperations?[...p.initialOperations,...m.operations]:[...m.operations]);});}if(p.labels&&An in p.labels){let g=p.labels[An];delete p.labels[An],g.forEach(m=>{m.operations&&(p.initialOperations=p.initialOperations?[...p.initialOperations,...m.operations]:[...m.operations]);});}return o.forEach(g=>{p.labels&&g in p.labels&&delete p.labels[g];}),u.forEach(g=>{p.initialOperations&&(p.initialOperations=p.initialOperations.filter(m=>!(m.type==="value"&&m.key===g)));}),p}i.inkToJson=n;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){U.error("Error parsing ink file",o);}}function t(a,s,o){for(let u of a)if(u)if(Array.isArray(u))if(u.includes("visit")){let l=rr(u,Es,(c,h,f)=>{},"",o,[]);l&&(o.externalSwitch=l);}else t(u,s,o);else typeof u=="object"&&(u&&"VAR="in u&&o.externalSwitch&&(s[An]||(s[An]=[]),s[An].push({operations:ei({defaultType:"storage",key:u["VAR="],value:o.externalSwitch},[],o)})),r(u,s,"",o));}function r(a,s,o="",u){if(a!==null){for(let[l,c]of Object.entries(a))if(Array.isArray(c)){let h=[],f={},p=(o?o+"_|_":"")+l;an(c,p,u,h,Yu,Yu,(g,m,C)=>{r(g,f,m,C);},ir);for(let[g,m]of Object.entries(f))s[g]=m;h.length>0&&(s[p]=h);}}}})(nl||={});var Wf=Xr(Ug()),S0=Xr(wy()),E0=Xr(y0()),w0=Xr(wr()),v1=/(?:^|<>)\s*#\s*([^\r\n]+)/g,C1=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,b1=new Set(["DONE","END"]),_1="_|_",v0=new Map;function D0(n,e){let t=JSON.stringify([e,n]),r=v0.get(t);if(r)return r;let i=new RegExp(n,e);return v0.set(t,i),i}function gs(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(s=>gs(n,s));let i=t.oneOf;if(Array.isArray(i))return i.some(s=>gs(n,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>gs(n,s));if(typeof t.const=="string")return n===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===n);if(t.type!=="string"||typeof t.minLength=="number"&&n.length<t.minLength||typeof t.maxLength=="number"&&n.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!D0(t.pattern,"").test(n))return !1}catch{return false}return true}function xu(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(o=>xu(n,o));let i=t.oneOf;if(Array.isArray(i))return i.some(o=>xu(n,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>xu(n,o));if(t.type!=="array"||typeof t.minItems=="number"&&n.length<t.minItems||typeof t.maxItems=="number"&&n.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(n.length<s.length)return false;for(let o=0;o<s.length;o++)if(!gs(n[o],s[o]))return false;return n.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:n.slice(s.length).every(o=>gs(o,t.items))}function Lf(n,e){if(e.type==="regexp")try{let t=D0(e.source,e.flags);return t.lastIndex=0,t.test(n.join(" "))}catch{return false}return e.type==="literal"?n.join(" ")===e.value:xu(n,e.schema)}function Tu(n){if(!n||typeof n!="object")return [];let e=n;if(Array.isArray(e.anyOf))return e.anyOf.flatMap(Tu);if(Array.isArray(e.oneOf))return e.oneOf.flatMap(Tu);if(Array.isArray(e.allOf)){let t={};for(let r of e.allOf)r&&typeof r=="object"&&Object.assign(t,r);return Tu(t)}return e.type==="array"&&Array.isArray(e.prefixItems)?[e]:[]}function C0(n,e){if(n===e)return 1;let t=Math.max(n.length,e.length);return t===0?1:Math.max(0,1-A0(n,e)/t)}function S1(n,e){if(e&&typeof e=="object"){let t=e;if(typeof t.const=="string")return {weight:2,matched:n===void 0?0:2*C0(n,t.const)};if(Array.isArray(t.enum))return {weight:2,matched:2*(n===void 0?0:Math.max(0,...t.enum.filter(i=>typeof i=="string").map(i=>C0(n,i))))}}return {weight:1,matched:n===void 0?0:1}}function E1(n,e){let t=Array.isArray(e.prefixItems)?e.prefixItems:[],r=Math.min(t.length,n.length),i=0,a=0,s=false;for(let o=0;o<r;o++){let u=S1(n[o],t[o]);i+=u.weight,a+=u.matched,u.weight>1&&(s=true);}return {score:i===0?0:a/i,hasDiscriminant:s}}var w1=.8,b0=new Map;function D1(n){let e=JSON.stringify(n),t=b0.get(e);if(t)return t;let r=new S0.default({strict:false,allErrors:true}).compile(n);return b0.set(e,r),r}function A1(n){if("items"in n)return n;let e=Array.isArray(n.prefixItems)?n.prefixItems.length:0;return {...n,minItems:e,maxItems:e,items:false}}function P1(n,e){let[t]=ku(n.instancePath);if(t!==void 0&&/^\d+$/.test(t)){let r=Number(t);if(r<e.length)return e[r]}return Mf(n)}function O1(n){return n.keyword==="const"?`must be "${n.params.allowedValue}"`:n.keyword==="enum"?`must be one of ${(n.params.allowedValues??[]).map(t=>`"${t}"`).join(", ")}`:n.message??"invalid value"}function qf(n){let e=n.split(/\r?\n/),t=[];for(let r=0;r<e.length;r++){let i=e[r];for(let a of i.matchAll(v1)){let s=(a[1]??"").trim();if(!s)continue;let o=xt.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:r+1,command:s,tokens:o});}}return t}function Mf(n){return n.keyword==="required"&&typeof n.params?.missingProperty=="string"?n.params.missingProperty:n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"?n.params.additionalProperty:n.instancePath.split("/").pop()||"(root)"}function A0(n,e){let t=n.length+1,r=e.length+1,i=Array.from({length:t},(a,s)=>[s,...Array(r-1).fill(0)]);for(let a=1;a<r;a++)i[0][a]=a;for(let a=1;a<t;a++)for(let s=1;s<r;s++){let o=n[a-1]===e[s-1]?0:1;i[a][s]=Math.min(i[a-1][s]+1,i[a][s-1]+1,i[a-1][s-1]+o);}return i[t-1][r-1]}function x1(n,e){let t,r=1/0;for(let a of e){let s=A0(n,a);s<r&&(r=s,t=a);}let i=Math.max(1,Math.floor(n.length/3));return r<=i?t:void 0}function T1(n,e){if(n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"){let t=n.params.additionalProperty,r=e&&x1(t,e),i=r?` (did you mean "${r}"?)`:"";return `has an unrecognised property "${t}"${i}`}return n.message??"invalid value"}function ku(n){return n.split("/").filter(Boolean).map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~"))}function N1(n,e){let t=n,r,i=a=>{a&&typeof a=="object"&&typeof a.$origin=="string"&&(r=a.$origin);};i(t);for(let a of ku(e)){if(t===null||typeof t!="object")break;t=t[a],i(t);}return r}function F1(n,e){let t=ku(e);for(let r=t.length;r>=0;r--){let i=t.slice(0,r),a=n;for(let s of i){if(a===null||typeof a!="object"){a=void 0;break}a=a[s];}if(a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.type=="string")return {path:`/${i.map(o=>o.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`,node:a}}}function Fu(n,e,t=new Set){if(!n||typeof n!="object")return n;let r=n.$ref;if(typeof r!="string")return n;let i=r.match(/^#\/definitions\/([^/]+)$/);return !i?.[1]||t.has(i[1])||!(i[1]in e)?{}:(t.add(i[1]),Fu(e[i[1]],e,t))}function Iu(n,e){let t=Fu(n,e);if(!t||typeof t!="object")return;let r=t;if(!(r.anyOf||r.oneOf)){if(Array.isArray(r.allOf)){let i={properties:{},required:[]};for(let a of r.allOf){let s=Iu(a,e);if(!s)return;Object.assign(i.properties,s.properties),i.required.push(...s.required);}return i}return {properties:r.properties??{},required:r.required??[]}}}function _0(n,e){if(!n||typeof n!="object")return true;let t=n;return "const"in t?t.const===e:Array.isArray(t.enum)?t.enum.includes(e):true}function I1(n,e){let t=n.definitions??{},r=[];for(let[i,a]of Object.entries(t)){let s=Iu(a,t);if(!s)continue;let o=s.properties.type;o&&typeof o=="object"&&("const"in o||Array.isArray(o.enum))&&_0(o,e.type)&&_0(s.properties.operationType,e.operationType)&&r.push(i);}return r}function k1(n,e,t){let r=n.definitions??{},i={definitions:r,...r[e]},a=new Wf.default({strict:false,allErrors:true}).compile(i);return a(t)?[]:a.errors??[]}function V1(n,e,t){let r=n.definitions??{},i=Fu(r[e],r);for(let a of ku(t)){let o=Iu(i,r)?.properties[a];if(o===void 0)return [];i=Fu(o,r);}return Object.keys(Iu(i,r)?.properties??{})}function Nu(n){let e=n.map(o=>o.instancePath),t=o=>e.some(u=>u!==o&&u.startsWith(`${o}/`)),r=n.filter(o=>!t(o.instancePath)),i=new Map;for(let o of r){let u=i.get(o.instancePath)??[];u.push(o),i.set(o.instancePath,u);}let a=[];for(let o of i.values()){let u=o.filter(l=>l.keyword!=="anyOf"&&l.keyword!=="oneOf");a.push(...u.length>0?u:o);}let s=new Set;return a.filter(o=>{let u=`${Mf(o)}|${o.message}`;return s.has(u)?false:(s.add(u),true)})}function Bf(n,e,t){return n.map(r=>({instancePath:r.instancePath||"(root)",element:Mf(r),message:T1(r,t?.(r)),origin:N1(e,r.instancePath)}))}function R1(n,e,t){let r=n.map(c=>c.instancePath),i=c=>r.some(h=>h!==c&&h.startsWith(`${c}/`)),a=n.filter(c=>!i(c.instancePath)),s=t&&typeof t=="object"?t:void 0,o=new Map,u=[];for(let c of a){let h=s?F1(e,c.instancePath):void 0;if(!h){u.push(c);continue}let f=o.get(h.path);f?f.errors.push(c):o.set(h.path,{node:h.node,errors:[c]});}let l=Bf(Nu(u),e);for(let[c,h]of o){let f=s?I1(s,h.node):[],p=f.length===1?f[0]:void 0;if(!p||!s){l.push(...Bf(Nu(h.errors),e));continue}let m=Nu(k1(s,p,h.node)).map(C=>({...C,instancePath:`${c}${C.instancePath}`}));l.push(...Bf(m,e,C=>V1(s,p,C.instancePath.slice(c.length))));}return l}var Gf;(h=>{function n(f,p={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let g=[];try{return {json:new E0.Compiler(f,{errorHandler:(v,d)=>{let _=v.replace(/^[A-Z]+: line \d+: ?/,""),y=v.match(/line (\d+)/);g.push({message:_,type:d,line:y?Number(y[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:v=>v,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:g}}catch{let C=false,b={...p,textSource:f};return e(g,()=>{C=true;},b),C?n(b.textSource,p):{issues:g}}}h.compile=n;function e(f,p,g){let{functions:m,initialVarsToRemove:C,labelToRemove:b}=g,v=f.find(d=>d.type===w0.ErrorType.Error);if(v){if(v.message.includes("Divert target not found")){let d=v.message.match(/Divert target not found: '-> (\w+)'/);if(d?.[1]){let _=d[1],y=`
67
-
68
- === ${_} ===
69
-
70
- -> DONE`;return g.textSource=g.textSource.concat(y),b.push(_),p()}}if(v.message.includes("Unresolved variable")){let d=v.message.match(/Unresolved variable: (\w+)/);if(d?.[1]){let _=d[1],y=`VAR ${_} = ""
71
-
72
- `;return g.textSource=y.concat(g.textSource),C.push(_),p()}}if(v.message.includes("Variable could not be found to assign to")){let d=v.message.match(/Variable could not be found to assign to: (\w+)/);if(d?.[1]){let _=d[1],y=`VAR ${_} = ""
73
-
74
- `;return g.textSource=y.concat(g.textSource),C.push(_),p()}}if(v.message.includes("Variable could not be found to assign to")){let d=v.message.match(/Variable could not be found to assign to: '(\w+)'/);if(d?.[1]){let _=d[1],y=`VAR ${_} = ""
75
-
76
- `;return g.textSource=y.concat(g.textSource),C.push(_),p()}}if(v.message.includes("Function call target not found")){let d=v.message.match(/Function call target not found: '-> (\w+)'/);if(d?.[1]){let _=d[1],y=`
77
-
78
- === function ${_}() ===
47
+ ~ myFunction()`);let u=(0, An.asOrNull)(o,Au.FunctionCall);return u&&(u.shouldPopReturnedValue=true),o.Find(Au.FunctionCall)()!==null&&(o=new st.ContentList(o,new rn.Text(`
48
+ `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l?(l instanceof Xr.NumberExpression||l instanceof gs.StringExpression||l instanceof Ip.DivertTarget||l instanceof Vp.VariableReference||l instanceof lb.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):l instanceof gs.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new kp.VariableAssignment({assignedExpression:l,isGlobalDeclaration:true,variableIdentifier:o})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let u=this.Expect(this.ListDefinition,"list item names");return u?(u.identifier=new ys.Identifier(o.name),new kp.VariableAssignment({variableIdentifier:o,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new XT.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(u===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let l=null;if(this.ParseString("=")!==null){this.Whitespace();let c=this.Expect(this.ExpressionInt,"value to be assigned to list item");c!==null&&(l=c.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new YT.ListElementDefinition(u,s,l)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u instanceof Xr.NumberExpression||u instanceof Ip.DivertTarget||u instanceof gs.StringExpression?u instanceof gs.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new BT.ConstantDeclaration(o,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new zT.Glue(new HT.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let u=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(u===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(u);let l=(0, An.asOrNull)(u,st.ContentList);return l||(l=new st.ContentList(u)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(l),l},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let l=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return l===null?null:new db.Sequence(l,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let u=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let l of u){let c=this.BeginRule(),h=this.ParseObject(l);if(h)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(c);else return this.SucceedRule(c,h);else this.FailRule(c);}return null},this.InnerExpression=()=>{let s=this.Parse(this.Expression);return s&&(s.outputWhenComplete=true),s},this.IdentifierWithMetadata=()=>{let s=this.Identifier();return s===null?null:new ys.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let u of s)if(!(u>="0"&&u<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new Oe.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=Ae.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let u=this.Parse(this.InnerSequenceObjects);return u===null||u.length<=1?null:new db.Sequence(u,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case Ae.SequenceType.Once:case Ae.SequenceType.Cycle:case Ae.SequenceType.Stopping:case Ae.SequenceType.Shuffle:case Ae.SequenceType.Shuffle|Ae.SequenceType.Stopping:case Ae.SequenceType.Shuffle|Ae.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),Ae.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new Oe.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let u of o)switch(u){case "!":s|=Ae.SequenceType.Once;break;case "&":s|=Ae.SequenceType.Cycle;break;case "~":s|=Ae.SequenceType.Shuffle;break;case "$":s|=Ae.SequenceType.Stopping;break}return s===0?null:s},this.SequenceTypeWordAnnotation=()=>{let s=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(s===null||s.length===0||this.ParseString(":")===null)return null;let o=0;for(let u of s)o|=u;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=Ae.SequenceType.Once;break;case "cycle":s=Ae.SequenceType.Cycle;break;case "shuffle":s=Ae.SequenceType.Shuffle;break;case "stopping":s=Ae.SequenceType.Stopping;break}return s===null?null:s},this.InnerSequenceObjects=()=>{let s=this.Parse(this.Newline)!==null,o=null;return s?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let s=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(s===null)return null;let o=[],u=false;for(let l of s)if(l==="|")u||o.push(new st.ContentList),u=false;else {let c=l;c===null?this.Error(`Expected content, but got ${l} (this is an ink compiler bug!)`):o.push(new st.ContentList(c)),u=true;}return u||o.push(new st.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineSequenceElement);return s===null?null:s},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=this.StatementsAtLevel(Je.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new rn.Text(`
49
+ `)),new st.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===Je.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(s),()=>this.StatementsBreakForLevel(s))),this.StatementAtLevel=s=>{let o=this._statementRulesAtLevel[s],u=this.OneOf(o);return s===Je.StatementLevel.Top&&u instanceof hb.ReturnType&&this.Error("should not have return statement outside of a knot"),u},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],u=this.OneOf(o);return u===null?null:u},this.GenerateStatementLevelRules=()=>{let s=Object.values(Je.StatementLevel);this._statementRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]);for(let o of s){let u=[],l=[];u.push(this.Line(this.MultiDivert)),o>=Je.StatementLevel.Top&&u.push(this.KnotDefinition),u.push(this.Line(this.Choice)),u.push(this.Line(this.AuthorWarning)),o>Je.StatementLevel.InnerBlock&&u.push(this.Gather),o>=Je.StatementLevel.Knot&&u.push(this.StitchDefinition),u.push(this.Line(this.ListDeclaration)),u.push(this.Line(this.VariableDeclaration)),u.push(this.Line(this.ConstDeclaration)),u.push(this.Line(this.ExternalDeclaration)),u.push(this.Line(this.IncludeStatement)),u.push(this.LogicLine),u.push(this.LineOfMixedTextAndLogic),o<=Je.StatementLevel.Knot&&l.push(this.KnotDeclaration),o<=Je.StatementLevel.Stitch&&l.push(this.StitchDeclaration),o<=Je.StatementLevel.InnerBlock&&(l.push(this.ParseDashNotArrow),l.push(this.String("}"))),this._statementRulesAtLevel[o]=u,this._statementBreakRulesAtLevel[o]=l;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
50
+ \r`),this.ParseNewline(),nn.ParseSuccess),this.Line=s=>()=>{let o=this.ParseObject(s);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let s=null;if(this.tagActive){let o=new st.ContentList;o.AddContent(new Kr.Tag(false)),o.AddContent(new Kr.Tag(true)),s=o;}else s=new Kr.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new Oe.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?nn.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?nn.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?nn.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?nn.ParseSuccess:null,this.Spaced=s=>()=>{this.Whitespace();let o=this.ParseObject(s);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let s=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)s=true;return s?nn.ParseSuccess:null},this.MultiSpaced=s=>()=>{this.AnyWhitespace();let o=this.ParseObject(s);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=r,a===null?this._fileHandler=new n1.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=i;}PreProcessInputString(e){return new LT.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(Du.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(Du.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(Du.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(Du.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new Oe.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 st.ContentList?e.AddContent(new Kr.Tag(false)):e.push(new Kr.Tag(false))),this.tagActive=false);}};Pu.InkParser=ae;ae.LatinBasic=xt.CharacterRange.Define("A","z",new Oe.CharacterSet().AddRange("[","`"));ae.LatinExtendedA=xt.CharacterRange.Define("\u0100","\u017F");ae.LatinExtendedB=xt.CharacterRange.Define("\u0180","\u024F");ae.Greek=xt.CharacterRange.Define("\u0370","\u03FF",new Oe.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));ae.Cyrillic=xt.CharacterRange.Define("\u0400","\u04FF",new Oe.CharacterSet().AddRange("\u0482","\u0489"));ae.Armenian=xt.CharacterRange.Define("\u0530","\u058F",new Oe.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));ae.Hebrew=xt.CharacterRange.Define("\u0590","\u05FF",new Oe.CharacterSet);ae.Arabic=xt.CharacterRange.Define("\u0600","\u06FF",new Oe.CharacterSet);ae.Korean=xt.CharacterRange.Define("\uAC00","\uD7AF",new Oe.CharacterSet);ae.Latin1Supplement=xt.CharacterRange.Define("\x80","\xFF",new Oe.CharacterSet);ae.Chinese=xt.CharacterRange.Define("\u4E00","\u9FFF",new Oe.CharacterSet);ae.ListAllCharacterRanges=()=>[ae.LatinBasic,ae.LatinExtendedA,ae.LatinExtendedB,ae.Arabic,ae.Armenian,ae.Cyrillic,ae.Greek,ae.Hebrew,ae.Korean,ae.Latin1Supplement,ae.Chinese];});var gb=_(xu=>{Object.defineProperty(xu,"__esModule",{value:true});xu.GenerateStoryStats=void 0;var r1=Rr(),i1=qr(),s1=Xi(),a1=Qd(),o1=sp(),u1=Sn();function l1(n){let e=n.FindAll(u1.Text)(),t=0;for(let u of e){let l=0,c=true;for(let h of u.text)h==" "||h==" "||h==`
51
+ `||h=="\r"?c=true:c&&(l++,c=false);t+=l;}let r=n.FindAll(a1.Knot)(),i=n.FindAll(o1.Stitch)(),a=n.FindAll(r1.Choice)(),s=n.FindAll(s1.Gather)(u=>u.debugMetadata!=null),o=n.FindAll(i1.Divert)();return {words:t,knots:r.length,functions:r.filter(u=>u.isFunction).length,stitches:i.length,gathers:s.length,diverts:o.length-1,choices:a.length}}xu.GenerateStoryStats=l1;});var yb=_(Tu=>{Object.defineProperty(Tu,"__esModule",{value:true});Tu.JsonFileHandler=void 0;var jp=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}.`)};}};Tu.JsonFileHandler=jp;});var bb=_(Le=>{Object.defineProperty(Le,"__esModule",{value:true});Le.Compiler=Le.Story=Le.InkList=Le.JsonFileHandler=Le.StatementLevel=Le.InkParser=Le.CompilerOptions=void 0;var c1=Sh(),h1=Oy(),$p=Ar(),d1=Rp(),p1=fe(),f1=re(),m1=gb(),g1=Sh();Object.defineProperty(Le,"CompilerOptions",{enumerable:true,get:function(){return g1.CompilerOptions}});var y1=Rp();Object.defineProperty(Le,"InkParser",{enumerable:true,get:function(){return y1.InkParser}});var v1=rp();Object.defineProperty(Le,"StatementLevel",{enumerable:true,get:function(){return v1.StatementLevel}});var b1=yb();Object.defineProperty(Le,"JsonFileHandler",{enumerable:true,get:function(){return b1.JsonFileHandler}});var vb=as();Object.defineProperty(Le,"InkList",{enumerable:true,get:function(){return vb.InkList}});Object.defineProperty(Le,"Story",{enumerable:true,get:function(){return vb.Story}});var Lp=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 d1.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 r;for(let i of this.runtimeStory.state.outputStream){let a=(0, f1.asOrNull)(i,p1.StringValue);if(a!==null){let s=new h1.DebugSourceRange(((r=a.value)===null||r===void 0?void 0:r.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, m1.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=r=>{let i=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),r>=i&&r<i+s.length)return a;i+=s.length;}return null},this.OnError=(r,i)=>{switch(i){case $p.ErrorType.Author:this._authorMessages.push(r);break;case $p.ErrorType.Warning:this._warnings.push(r);break;case $p.ErrorType.Error:this._errors.push(r);break}this.options.errorHandler!==null&&this.options.errorHandler(r,i);},this._inputString=e,this._options=t||new c1.CompilerOptions;}};Le.Compiler=Lp;});var Ss="global decl",Pn="___external_value___";var K;(i=>(i.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),i.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),i.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),i.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(K||={});var l0=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,c0=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,h0=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,Mu={Space_Separator:l0,ID_Start:c0,ID_Continue:h0},ge={isSpaceSeparator(n){return typeof n=="string"&&Mu.Space_Separator.test(n)},isIdStartChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="$"||n==="_"||Mu.ID_Start.test(n))},isIdContinueChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||n==="$"||n==="_"||n==="\u200C"||n==="\u200D"||Mu.ID_Continue.test(n))},isDigit(n){return typeof n=="string"&&/[0-9]/.test(n)},isHexDigit(n){return typeof n=="string"&&/[0-9A-Fa-f]/.test(n)}},Ju,Be,Kt,ws,an,wt,we,Uu,ei,d0=function(e,t){Ju=String(e),Be="start",Kt=[],ws=0,an=1,wt=0,we=void 0,Uu=void 0,ei=void 0;do we=p0(),g0[Be]();while(we.type!=="eof");return typeof t=="function"?zu({"":ei},"",t):ei};function zu(n,e,t){let r=n[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let i=0;i<r.length;i++){let a=String(i),s=zu(r,a,t);s===void 0?delete r[a]:Object.defineProperty(r,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let i in r){let a=zu(r,i,t);a===void 0?delete r[i]:Object.defineProperty(r,i,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(n,e,r)}var R,I,Qr,Ut,W;function p0(){for(R="default",I="",Qr=false,Ut=1;;){W=Xt();let n=tf[R]();if(n)return n}}function Xt(){if(Ju[ws])return String.fromCodePoint(Ju.codePointAt(ws))}function D(){let n=Xt();return n===`
52
+ `?(an++,wt=0):n?wt+=n.length:wt++,n&&(ws+=n.length),n}var tf={default(){switch(W){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
53
+ `:case "\r":case "\u2028":case "\u2029":D();return;case "/":D(),R="comment";return;case void 0:return D(),oe("eof")}if(ge.isSpaceSeparator(W)){D();return}return tf[Be]()},comment(){switch(W){case "*":D(),R="multiLineComment";return;case "/":D(),R="singleLineComment";return}throw ue(D())},multiLineComment(){switch(W){case "*":D(),R="multiLineCommentAsterisk";return;case void 0:throw ue(D())}D();},multiLineCommentAsterisk(){switch(W){case "*":D();return;case "/":D(),R="default";return;case void 0:throw ue(D())}D(),R="multiLineComment";},singleLineComment(){switch(W){case `
54
+ `:case "\r":case "\u2028":case "\u2029":D(),R="default";return;case void 0:return D(),oe("eof")}D();},value(){switch(W){case "{":case "[":return oe("punctuator",D());case "n":return D(),xn("ull"),oe("null",null);case "t":return D(),xn("rue"),oe("boolean",true);case "f":return D(),xn("alse"),oe("boolean",false);case "-":case "+":D()==="-"&&(Ut=-1),R="sign";return;case ".":I=D(),R="decimalPointLeading";return;case "0":I=D(),R="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=D(),R="decimalInteger";return;case "I":return D(),xn("nfinity"),oe("numeric",1/0);case "N":return D(),xn("aN"),oe("numeric",NaN);case '"':case "'":Qr=D()==='"',I="",R="string";return}throw ue(D())},identifierNameStartEscape(){if(W!=="u")throw ue(D());D();let n=Hu();switch(n){case "$":case "_":break;default:if(!ge.isIdStartChar(n))throw ef();break}I+=n,R="identifierName";},identifierName(){switch(W){case "$":case "_":case "\u200C":case "\u200D":I+=D();return;case "\\":D(),R="identifierNameEscape";return}if(ge.isIdContinueChar(W)){I+=D();return}return oe("identifier",I)},identifierNameEscape(){if(W!=="u")throw ue(D());D();let n=Hu();switch(n){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!ge.isIdContinueChar(n))throw ef();break}I+=n,R="identifierName";},sign(){switch(W){case ".":I=D(),R="decimalPointLeading";return;case "0":I=D(),R="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":I=D(),R="decimalInteger";return;case "I":return D(),xn("nfinity"),oe("numeric",Ut*(1/0));case "N":return D(),xn("aN"),oe("numeric",NaN)}throw ue(D())},zero(){switch(W){case ".":I+=D(),R="decimalPoint";return;case "e":case "E":I+=D(),R="decimalExponent";return;case "x":case "X":I+=D(),R="hexadecimal";return}return oe("numeric",Ut*0)},decimalInteger(){switch(W){case ".":I+=D(),R="decimalPoint";return;case "e":case "E":I+=D(),R="decimalExponent";return}if(ge.isDigit(W)){I+=D();return}return oe("numeric",Ut*Number(I))},decimalPointLeading(){if(ge.isDigit(W)){I+=D(),R="decimalFraction";return}throw ue(D())},decimalPoint(){switch(W){case "e":case "E":I+=D(),R="decimalExponent";return}if(ge.isDigit(W)){I+=D(),R="decimalFraction";return}return oe("numeric",Ut*Number(I))},decimalFraction(){switch(W){case "e":case "E":I+=D(),R="decimalExponent";return}if(ge.isDigit(W)){I+=D();return}return oe("numeric",Ut*Number(I))},decimalExponent(){switch(W){case "+":case "-":I+=D(),R="decimalExponentSign";return}if(ge.isDigit(W)){I+=D(),R="decimalExponentInteger";return}throw ue(D())},decimalExponentSign(){if(ge.isDigit(W)){I+=D(),R="decimalExponentInteger";return}throw ue(D())},decimalExponentInteger(){if(ge.isDigit(W)){I+=D();return}return oe("numeric",Ut*Number(I))},hexadecimal(){if(ge.isHexDigit(W)){I+=D(),R="hexadecimalInteger";return}throw ue(D())},hexadecimalInteger(){if(ge.isHexDigit(W)){I+=D();return}return oe("numeric",Ut*Number(I))},string(){switch(W){case "\\":D(),I+=f0();return;case '"':if(Qr)return D(),oe("string",I);I+=D();return;case "'":if(!Qr)return D(),oe("string",I);I+=D();return;case `
55
+ `:case "\r":throw ue(D());case "\u2028":case "\u2029":y0(W);break;case void 0:throw ue(D())}I+=D();},start(){switch(W){case "{":case "[":return oe("punctuator",D())}R="value";},beforePropertyName(){switch(W){case "$":case "_":I=D(),R="identifierName";return;case "\\":D(),R="identifierNameStartEscape";return;case "}":return oe("punctuator",D());case '"':case "'":Qr=D()==='"',R="string";return}if(ge.isIdStartChar(W)){I+=D(),R="identifierName";return}throw ue(D())},afterPropertyName(){if(W===":")return oe("punctuator",D());throw ue(D())},beforePropertyValue(){R="value";},afterPropertyValue(){switch(W){case ",":case "}":return oe("punctuator",D())}throw ue(D())},beforeArrayValue(){if(W==="]")return oe("punctuator",D());R="value";},afterArrayValue(){switch(W){case ",":case "]":return oe("punctuator",D())}throw ue(D())},end(){throw ue(D())}};function oe(n,e){return {type:n,value:e,line:an,column:wt}}function xn(n){for(let e of n){if(Xt()!==e)throw ue(D());D();}}function f0(){switch(Xt()){case "b":return D(),"\b";case "f":return D(),"\f";case "n":return D(),`
56
+ `;case "r":return D(),"\r";case "t":return D()," ";case "v":return D(),"\v";case "0":if(D(),ge.isDigit(Xt()))throw ue(D());return "\0";case "x":return D(),m0();case "u":return D(),Hu();case `
57
+ `:case "\u2028":case "\u2029":return D(),"";case "\r":return D(),Xt()===`
58
+ `&&D(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw ue(D());case void 0:throw ue(D())}return D()}function m0(){let n="",e=Xt();if(!ge.isHexDigit(e)||(n+=D(),e=Xt(),!ge.isHexDigit(e)))throw ue(D());return n+=D(),String.fromCodePoint(parseInt(n,16))}function Hu(){let n="",e=4;for(;e-- >0;){let t=Xt();if(!ge.isHexDigit(t))throw ue(D());n+=D();}return String.fromCodePoint(parseInt(n,16))}var g0={start(){if(we.type==="eof")throw Tn();Gu();},beforePropertyName(){switch(we.type){case "identifier":case "string":Uu=we.value,Be="afterPropertyName";return;case "punctuator":_s();return;case "eof":throw Tn()}},afterPropertyName(){if(we.type==="eof")throw Tn();Be="beforePropertyValue";},beforePropertyValue(){if(we.type==="eof")throw Tn();Gu();},beforeArrayValue(){if(we.type==="eof")throw Tn();if(we.type==="punctuator"&&we.value==="]"){_s();return}Gu();},afterPropertyValue(){if(we.type==="eof")throw Tn();switch(we.value){case ",":Be="beforePropertyName";return;case "}":_s();}},afterArrayValue(){if(we.type==="eof")throw Tn();switch(we.value){case ",":Be="beforeArrayValue";return;case "]":_s();}},end(){}};function Gu(){let n;switch(we.type){case "punctuator":switch(we.value){case "{":n={};break;case "[":n=[];break}break;case "null":case "boolean":case "numeric":case "string":n=we.value;break}if(ei===void 0)ei=n;else {let e=Kt[Kt.length-1];Array.isArray(e)?e.push(n):Object.defineProperty(e,Uu,{value:n,writable:true,enumerable:true,configurable:true});}if(n!==null&&typeof n=="object")Kt.push(n),Array.isArray(n)?Be="beforeArrayValue":Be="beforePropertyName";else {let e=Kt[Kt.length-1];e==null?Be="end":Array.isArray(e)?Be="afterArrayValue":Be="afterPropertyValue";}}function _s(){Kt.pop();let n=Kt[Kt.length-1];n==null?Be="end":Array.isArray(n)?Be="afterArrayValue":Be="afterPropertyValue";}function ue(n){return Es(n===void 0?`JSON5: invalid end of input at ${an}:${wt}`:`JSON5: invalid character '${nf(n)}' at ${an}:${wt}`)}function Tn(){return Es(`JSON5: invalid end of input at ${an}:${wt}`)}function ef(){return wt-=5,Es(`JSON5: invalid identifier character at ${an}:${wt}`)}function y0(n){console.warn(`JSON5: '${nf(n)}' in strings is not valid ECMAScript; consider escaping`);}function nf(n){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[n])return e[n];if(n<" "){let t=n.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return n}function Es(n){let e=new SyntaxError(n);return e.lineNumber=an,e.columnNumber=wt,e}var v0=function(e,t,r){let i=[],a="",s,o,u="",l;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(r=t.space,l=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let m of t){let b;typeof m=="string"?b=m:(typeof m=="number"||m instanceof String||m instanceof Number)&&(b=String(m)),b!==void 0&&s.indexOf(b)<0&&s.push(b);}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),u=" ".substr(0,r)):typeof r=="string"&&(u=r.substr(0,10)),c("",{"":e});function c(m,b){let C=b[m];switch(C!=null&&(typeof C.toJSON5=="function"?C=C.toJSON5(m):typeof C.toJSON=="function"&&(C=C.toJSON(m))),o&&(C=o.call(b,m,C)),C instanceof Number?C=Number(C):C instanceof String?C=String(C):C instanceof Boolean&&(C=C.valueOf()),C){case null:return "null";case true:return "true";case false:return "false"}if(typeof C=="string")return h(C);if(typeof C=="number")return String(C);if(typeof C=="object")return Array.isArray(C)?g(C):p(C)}function h(m){let b={"'":.1,'"':.2},C={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},v="";for(let S=0;S<m.length;S++){let y=m[S];switch(y){case "'":case '"':b[y]++,v+=y;continue;case "\0":if(ge.isDigit(m[S+1])){v+="\\x00";continue}}if(C[y]){v+=C[y];continue}if(y<" "){let w=y.charCodeAt(0).toString(16);v+="\\x"+("00"+w).substring(w.length);continue}v+=y;}let d=l||Object.keys(b).reduce((S,y)=>b[S]<b[y]?S:y);return v=v.replace(new RegExp(d,"g"),C[d]),d+v+d}function p(m){if(i.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");i.push(m);let b=a;a=a+u;let C=s||Object.keys(m),v=[];for(let S of C){let y=c(S,m);if(y!==void 0){let w=f(S)+":";u!==""&&(w+=" "),w+=y,v.push(w);}}let d;if(v.length===0)d="{}";else {let S;if(u==="")S=v.join(","),d="{"+S+"}";else {let y=`,
59
+ `+a;S=v.join(y),d=`{
60
+ `+a+S+`,
61
+ `+b+"}";}}return i.pop(),a=b,d}function f(m){if(m.length===0)return h(m);let b=String.fromCodePoint(m.codePointAt(0));if(!ge.isIdStartChar(b))return h(m);for(let C=b.length;C<m.length;C++)if(!ge.isIdContinueChar(String.fromCodePoint(m.codePointAt(C))))return h(m);return m}function g(m){if(i.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");i.push(m);let b=a;a=a+u;let C=[];for(let d=0;d<m.length;d++){let S=c(String(d),m);C.push(S!==void 0?S:"null");}let v;if(C.length===0)v="[]";else if(u==="")v="["+C.join(",")+"]";else {let d=`,
62
+ `+a,S=C.join(d);v=`[
63
+ `+a+S+`,
64
+ `+b+"]";}return i.pop(),a=b,v}},b0={parse:d0,stringify:v0},C0=b0,ti=C0;var sf="\xA7SPACE\xA7",af="\xA7DOUBLE_QUOTES\xA7",of="\xA7QUOTES\xA7",uf="SPECIAL_\xA7QUOTES\xA7",lf="\xA7CURLY_BRACKETS1\xA7",S0="\xA7INK_VAR\xA7",cf="\xA7CURLY_BRACKETS2\xA7",Nt;(v=>{let n=[],e=[];async function t(d,S){for(let y=0;y<n.length;y++)try{let{validation:w}=n[y].opts;if(w instanceof RegExp){if(!w.test(d.join(" ")))continue}else if(w instanceof zod.ZodType&&!w.safeParse(d).success)continue;let E=await n[y].fn(d,S,h);if(E===!0||typeof E=="string")return E}catch{}return false}function r(d,S={name:"custom-command",validation:/^/}){n.unshift({fn:d,opts:S});}v.add=r;function i(){return [...e.map(d=>d.opts),...n.map(d=>d.opts)]}v.info=i;function a(d,S){e.unshift({fn:d,opts:S});}v.addMapper=a;function s(){n.length=0;}v.clear=s;function o(){e.length=0;}v.clearMappers=o;async function u(d,S,y){try{let w=l(d),E=await t(w,y);return E===!0?void 0:typeof E=="string"?(E.startsWith("#")&&(E=E.substring(1)),await v.run(E,S,y)):c(w,S)}catch(w){throw K.error("Error parsing ink hashtag-command",d),w}}v.run=u;function l(d,S){if(d=d.replaceAll('\\"',af),d=d.replaceAll("\\'",of),d=d.replaceAll("\\`",uf),d=d.replaceAll("\\{",lf),d=d.replaceAll("\\}",cf),S?.mergeInkVariables){let O;do O=d,d=d.replace(/\{[^{}:]*\}/g,S0);while(d!==O)}d=d.replaceAll("{"," { "),d=d.replaceAll("}"," } "),d=d.replaceAll(lf,"{"),d=d.replaceAll(cf,"}");let y=[],w,E="";for(let O=0;O<d.length;O++){let x=d[O];x==='"'||x==="'"||x==="`"?w===void 0?(y.push(E),E="",w=x,E+=x):w===x?(w=void 0,E+=x,y.push(E),E=""):E+=x:E+=x;}return E!==""&&y.push(E),y.forEach((O,x)=>{x%2===1&&(y[x]=O.replaceAll(" ",sf));}),d=y.join(""),y=d.split(" ").filter(O=>O!==""),y=y.map(O=>O.replaceAll(sf," ").replaceAll(af,'"').replaceAll(of,"'").replaceAll(uf,"`")),y=g(y),y=y.flatMap(O=>C(O)),y=y.map(O=>O.startsWith('"')&&O.endsWith('"')||O.startsWith("'")&&O.endsWith("'")||O.startsWith("`")&&O.endsWith("`")?O.slice(1,-1):O),y}v.convertTagTolist=l;function c(d,S,y){for(let w of e){let{validation:E}=w.opts,O=false;if(E instanceof RegExp?O=E.test(d.join(" ")):E instanceof zod.ZodType&&(O=E.safeParse(d).success),O)return w.fn(d,S)}y?.silent||K.error("The operation is not valid",d);}v.convertOperation=c;function h(d){if(d.length===0)return {};if(d.length%2!==0)throw K.error("The props list must have a pair number of elements",d),new Error("The props list must have a pair number of elements");let S="{";d.forEach((y,w)=>{if(w%2===0)S+=`"${y}": `;else {switch(y){case "null":case "undefined":case "true":case "false":S+=`${y}`;break;default:f(y)?(y=p(y),S+=`"${y}"`):y.startsWith("{")&&y.endsWith("}")?S+=`${y}`:y.startsWith('"')&&y.endsWith('"')?S+=`${y}`:Number.isNaN(parseFloat(y))?S+=`"${y}"`:S+=`${y}`;}w<d.length-1&&(S+=", ");}}),S+="}";try{return ti.parse(S)}catch(y){throw K.error("Error parsing ink json",S),y}}v.convertListStringToObj=h;function p(d){return d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`")?d.substring(1,d.length-1):d}function f(d){return !!(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`"))}function g(d){return m(d).tokens}v.mergeJsonBlocks=g;function m(d){let S=[],y=false;for(let w=0;w<d.length;w++){let E=d[w];if(E!=="{"){S.push(E);continue}let O=b(d,w);if(O===-1){S.push(E);continue}let x=m(d.slice(w+1,O)),U=["{",...x.tokens,"}"],Se=U.join(" ");if(!x.hasInvalidMatchedBlock)try{ti.parse(Se),S.push(Se),w=O;continue}catch{}y=true,S.push(...U),w=O;}return {tokens:S,hasInvalidMatchedBlock:y}}function b(d,S){let y=0;for(let w=S;w<d.length;w++)if(d[w]==="{")y++;else if(d[w]==="}"&&(y--,y===0))return w;return -1}function C(d){if(d==="["||d==="]")return [d];let S=0,y=d.length,w=[];for(;S<y&&d[S]==="[";)w.push("["),S++;let E=[];for(;y>S&&d[y-1]==="]";)E.unshift("]"),y--;let O=d.slice(S,y);return O===""?[...w,...E]:[...w,O,...E]}})(Nt||={});var hf=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],df=["+","-","/","*","%","POW","RANDOM","L^"],pf=["INT","FLOOR","FLOAT"];function ir(n,e){if(n.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(n)&&(n=n.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!n.startsWith(".")))return n.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(n)&&n.includes("g-")){let r=n.split("g-");return Ku(e)+"_|_"+"g-"+r[r.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(n);)t++,n=n.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(n)&&e){let r=n.substring(1);return Ku(e,t)+"_|_"+r.replaceAll(".","_|_")}return n.replaceAll(".","_|_")||Ku(e,t).replaceAll(".","_|_")}function Ku(n,e=0){let t=n.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var ff="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Ft(n){return n.startsWith("^")&&(n=n.substring(1)),n=n.replaceAll("\\\\",ff),n=n.replaceAll("\\n",`
65
+ `),n=n.replaceAll("\\t"," "),n=n.replaceAll(" "," "),n=n.replaceAll(ff,"\\\\"),n}var _0={version:"1.15.0"};var mf=`https://pixi-vn.com/schemas/${_0.version}/schema.json`,gf=["==","!=","<","<=",">",">=","CONTAINS"];function on(n,e,t,r){let{functions:i}=r;n=n.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return n.forEach(s=>{if(typeof s=="string")switch(s){case "&&":case "||":if(a.length>=2){let o={type:"union",unionType:s==="&&"?"and":"or",conditions:[a[a.length-2],a[a.length-1]]};a.pop(),a.pop(),a.push(o);}break;case "!":if(a.length===0)K.error("Error parsing ink file: Conditional statement is not valid",n);else {let o={type:"union",unionType:"not",condition:a[a.length-1]};a[a.length-1]=o;}break;case "!?":if(a.length>1){let o={type:"union",unionType:"not",condition:{type:"compare",operator:"CONTAINS",leftValue:a[a.length-2],rightValue:a[a.length-1]}};a.pop(),a.pop(),a.push(o);}else K.error("Error parsing ink file: Conditional statement is not valid",n);break;default:if(gf.includes(s))if(a.length<2)K.error("Error parsing ink file: Conditional statement is not valid",n);else {let o={type:"compare",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(df.includes(s))if(a.length<2)K.error("Error parsing ink file: Conditional statement is not valid",n);else {s==="L^"&&(s="INTERSECTION");let o={type:"arithmetic",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(pf.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(Ft(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),u=o.pop(),l=o.pop();if(l===void 0||u===void 0){K.error("Error parsing ink file: Conditional statement is not valid",n);return}let c=Number(l),h=o.join(".");if(h.includes("^.")){let f=h.split("."),g=f[f.length-1].replaceAll(".","_|_");f.pop(),h=`${f.join(".")}.${g}`,u.includes("c-")&&(h=h+"_|_"+u);}else h=h.replaceAll(".","_|_");let p=ir(h,e);if(!p)return;a.push({type:"compare",leftValue:Xu(p),operator:">=",rightValue:{type:"value",value:c}});}else {let o=ir(s["CNT?"],e);if(!o)return;a.push(Xu(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(Nn({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],u=i.find(c=>c.name===o);if(!u){K.error(`Error parsing ink file: Function ${o} is not defined`,n);return}let l=[];for(let c=0;c<u.args;c++)a.length!==0&&l.push(a.pop());a.push({type:"function",functionName:o,args:l.reverse()});}else if(typeof s=="object"&&"^->"in s)s["^->"].includes("$r")||a.push(s["^->"]);else if(typeof s=="object"&&"list"in s){let o=Object.values(s.list).map(u=>u);a.push(o);}else a.push(s);}),a}function Yu(n,e,t,r){return on(n,e,t,r)}function Nn(n,e,t){let{key:r,defaultType:i}=n,a=e.indexOf(r);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:i,key:r}}function ni(n,e,t){let{key:r,value:i,defaultType:a,artmeticValue:s}=n,o=e.indexOf(r);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:i}];if(s){if(typeof i=="object"&&"list"in i){let u=Object.values(i.list).map(l=>l);return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:u}]}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:i}]}else if(typeof i=="object"){if("list"in i&&typeof i.list=="object"){if("origins"in i&&Array.isArray(i.origins)&&i.origins.length>0)return i.origins.reduce(u=>(u.push({type:"value",storageOperationType:"set",storageType:a,key:r,value:Object.values(t.enums[r])}),Object.entries(t.enums[r]).forEach(([l,c])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${r}.${l}`,value:c});}),u),[]);{let u=new Set,l=Object.entries(i.list).reduce((c,[h,p])=>{let[f,g]=h.split(".");return c.push({type:"value",storageOperationType:"set",storageType:a,key:g,value:p}),u.add(f),c},[]);return u.forEach(c=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:c,value:Object.values(t.enums[c])});}),r in t.enums?Object.entries(t.enums[r]).forEach(([c,h])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${r}.${c}`,value:h});}):l.push({type:"value",storageOperationType:"set",storageType:a,key:r,value:Object.values(i.list)}),l}}else if(typeof i=="object"&&"VAR?"in i){if(typeof i["VAR?"]=="string"&&i["VAR?"].includes(".")){let[u,l]=i["VAR?"].split(".");if(u in t.enums&&l in t.enums[u])return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:t.enums[u][l]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:Nn({key:i["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:i}]}function Xu(n){return {type:"value",storageType:"label",storageOperationType:"get",label:n}}function Zu(n,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(n)?"call":"jump"}function Ds(n,e){if(e){if(typeof e=="string")e.startsWith("^")&&n.push(Ft(e));else if(typeof e=="object"&&"type"in e)switch(e.type){case "value":case "function":console.warn("Warning: trying to add a value or function operation as text. This is likely a mistake, so it will be ignored.");break;default:n.push(e);}}}function Qu(n,e,t,r,i,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:u=false}=a;return E0(n,e,t,r,i,{isNewLine:s,isHashtagScript:o,isThreads:u})}function E0(n,e,t,r,i,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:u}=a;if(o){if(Array.isArray(e)&&e.length>0){let l={goNextStep:true},c=[];try{if(e.length===1&&typeof e[0]=="string"){let h=e[0],p=Nt.convertTagTolist(h),f=Nt.convertOperation(p,l,{silent:!0});f&&(f.$origin=h,c.push(f));}}catch{}c.length===0&&c.push({type:"operationtoconvert",values:e}),n.push({...l,operations:c});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&n.length>0){let l=n[n.length-1];!l.glueEnabled&&!l.operations&&!l.labelToOpen&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),n[n.length-1]=l;}typeof e=="string"?n.push(D0(Ft(e),r.characterIds)):n.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")n.push({end:"game_end"});else if(e==="done")n.push({end:"label_end",goNextStep:true});else if(e==="<>")if(n.length>0){let l=n[n.length-1];l.glueEnabled=true;let c=l.operations!==void 0&&l.dialogue===void 0;l.labelToOpen||(l.goNextStep=c?true:!s),n[n.length-1]=l;}else n.push({glueEnabled:true,goNextStep:true});}else if(typeof e=="object"){if("type"in e)switch(e.type){case "value":e.storageOperationType==="set"?(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=Ft(e.value)),n.push({goNextStep:true,operations:[e]})):console.warn("Warning: trying to add a value get operation as step. This is likely a mistake, so it will be ignored.");break;case "function":n.push({goNextStep:true,operations:[e]});break;default:if(!s&&n.length>0){let l=n[n.length-1];!l.glueEnabled&&!l.operations&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),n[n.length-1]=l;}n.push({conditionalStep:e});}else if("->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&n.length>0&&n[n.length-1]?.dialogue===void 0&&(l=void 0),!s&&n.length>0){let c=n[n.length-1];c.labelToOpen||(c.goNextStep=true),n[n.length-1]=c;}if(e.params&&e.params.length===0&&delete e.params,e.var)n.push({labelToOpen:{label:Nn({key:e["->"],defaultType:"storage"},i),type:u?"call":"jump",params:e.params},glueEnabled:l});else {let c=ir(e["->"],t);if(!c)return;n.push({labelToOpen:{label:c,type:Zu(c,u),params:e.params},glueEnabled:l});}}else if("->t->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&n.length>0&&n[n.length-1]?.dialogue===void 0&&(l=void 0),!s&&n.length>0){let h=n[n.length-1];h.labelToOpen||(h.goNextStep=true),n[n.length-1]=h;}e.params&&e.params.length===0&&delete e.params;let c=ir(e["->t->"],t);if(!c)return;n.push({labelToOpen:{label:c,type:"call",params:e.params},glueEnabled:l});}}}function D0(n,e){let t;if(n.includes(": ")){let r=n.split(": "),i=r[0],a=r.slice(1).join(": ");(e?.has(i)||characters.RegisteredCharacters.has(i))&&(t=i,n=a);}return t?{dialogue:{character:t,text:n}}:{dialogue:n}}function el(n,e,t,r=true,i=false){return A0(n,e,t,r,i)}function A0(n,e,t,r,i=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?n.push(Ft(e)):n.push(e):typeof e=="object"&&"type"in e&&n.push(e));}function As(n,e,t,r){if(n.length===0){K.error("Error parsing ink file: Arithmetic statement is not valid",n);return}let i=on(n,e,t,r);if(i.length===1){let a=i[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function sr(n,e,t,r="",i,a,s=void 0){let o=[],u="sequential",l=false,c=true;n.forEach(f=>{f==="%"&&(u="loop"),f==="seq"&&(u="random"),f==="MIN"&&(l=true);});let h=n[n.length-1];return Object.keys(h).forEach(f=>{let g=h[f];if(Array.isArray(g)&&g.length>3){g=g.slice(1,g.length-2);let m=[];un(g,r,i,m,e,e,t,ar,s,true,a),m.length===1?o.push(m[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:m});}else Array.isArray(g)&&g.length===3&&(c=false);}),u==="sequential"?{type:"stepswitch",elements:o,choiceType:u,end:c?"lastItem":void 0,nestedId:s}:l&&u==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:c?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:u}}function un(n,e,t,r=[],i,a,s,o,u=void 0,l=true,c=[]){let h=false,p=[],f=false,g=false,m=false,b=[],C=[];if(t.preDialog[e]&&(l=false,i(r,`^${t.preDialog[e].text}`,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),t.preDialog[e].glue&&i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),delete t.preDialog[e]),n.includes("visit")){let d=sr(n,a,s,e,t,c,u);d&&(!l&&r.length>0&&i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}));return}let v=n[0];if(v&&typeof v=="object"&&"temp="in v){for(;n[0]&&typeof n[0]=="object"&&"temp="in n[0];)c.push(n[0]["temp="]),n.shift();c=c.reverse();}if(n.forEach((d,S)=>{if(g){if(typeof d=="string"&&d==="/#"){let y=[];un(C,e,t,y,el,el,s,o,u,l),i(r,y,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),g=false,C=[];}else C.push(d);return}else if(h)if(Array.isArray(d))p.push(d);else if(d&&typeof d=="object")"CNT?"in d?S>0&&n[S-1]==="ev"?(f=true,b.push(d)):f?b.push(d):(p.push(d),l=false):"VAR="in d||"temp="in d?ni({key:"VAR="in d?d["VAR="]:d["temp="],value:n[S-1],defaultType:"VAR="in d?"storage":"tempstorage"},c,t).forEach(w=>{if(w.value&&typeof w.value=="string"&&w.value==="/str"&&(w.value=n[S-2]),w.value&&typeof w.value=="object"&&"^->"in w.value&&(w.value=w.value["^->"]),p.length>1){let E=As(p,e,c,t);p=[],E&&typeof E=="object"&&"type"in E&&E.type==="value"&&"storageType"in E&&E.storageType==="logic"&&(w.value=E.operation);}(typeof w.key!="string"||!w.key.includes("$r"))&&(i(r,w,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=true);}):"VAR?"in d?p.push(d):"^->"in d?d["^->"].includes("$r")||p.push(d):("f()"in d||"list"in d&&typeof d.list=="object")&&p.push(d);else switch(d){case "/ev":f&&b.push(d),h=false,p.push(d);break;case "out":if(p.length>0){let y=p[p.length-1];if(y&&typeof y=="object"&&"VAR?"in y){p.pop();let w=Nn({key:y["VAR?"],defaultType:"storage"},c);i(r,w,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m});}else {let w=[];for(;p.length>0&&p[p.length-1]!=="/ev";)w.push(p.pop());w=w.reverse();let E=As(w,e,c,t);p=[],E&&typeof E=="object"&&"type"in E&&E.type==="value"&&"storageType"in E&&E.storageType==="logic"?i(r,{storageOperationType:"get",storageType:"logic",operation:E.operation,type:"value"},e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}):(i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),E=`^${E}`,i(r,E,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}));}l=false;}break;case "pop":{let y=p[p.length-1];if(y&&typeof y=="object"&&"f()"in y){let w=[];for(;p.length>0&&p[p.length-1]!=="/ev";)w.push(p.pop());w=w.reverse();let E=on(w,e,c,t);p=[],E.forEach(O=>{O&&typeof O=="object"&&"type"in O&&O.type==="function"?i(r,O,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}):K.warn("Unhandled case: value is not a function",O);}),l=false;}else p.push(d);return}default:p.push(d);}else if(typeof d=="string")if(d.startsWith("^"))i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;else if(d==="ev")h=true;else if(d===`
66
+ `)l=true;else if(d==="done"||d==="end")i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;else if(d==="<>")i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;else if(d==="nop"&&f){let y=yf(b,a,s,e,t,c,u);y&&i(r,y,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),f=false,b=[];}else d==="#"?g=true:d==="thread"&&(m=true);else if(Array.isArray(d))if(f)b.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]){p.pop();let y=[],w=[];for(;p.length>0&&p[p.length-1]!=="/ev";)y.push(p.pop());b=[...b,...y.reverse()],f=true,w.push(d.pop()),w.push(d.pop()),b=[...b,...d],b.push(w);}else if(d.length>1&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"#n"in d[d.length-1]){let y=d.pop();if(!y){K.error("Error parsing ink file: el is undefined");return}let w=y["#n"];delete y["#n"],d.push(y),i(r,{"->":e?e+"_|_"+w:w},e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),s({[w]:d},e,t);}else un(d,e,t,r,i,a,s,o,u,l,c);else if(d&&typeof d=="object")if("->"in d&&typeof d["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->"])){let y=[];p.length>0&&(y=Yu(["ev",...p],e,c,t)),d.params=y,i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;}else if("->t->"in d&&typeof d["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->t->"])){let y=[];p.length>0&&(y=Yu(["ev",...p],e,c,t)),d.params=y,i(r,d,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m}),l=false;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(p.push(d),l=false);else if("s"in d&&Array.isArray(d.s))p.push(d),l=false;else if("CNT?"in d)p.push(d),l=false;else if("VAR="in d||"temp="in d){let y="VAR="in d?d["VAR="]:d["temp="],w,E=[];if(y!=="$r"){for(p.pop(),p[p.length-1]==="/ev"&&p.pop();p.length>0&&p[p.length-1]!=="/ev";)E.push(p.pop());E=E.reverse(),w=As(E,e,c,t),p=[],ni({key:y,value:w,defaultType:"VAR="in d?"storage":"tempstorage",artmeticValue:true},c,t).forEach(x=>{(x.value!==void 0||x.value!==null)&&i(r,x,e,t,c,{isNewLine:l,isHashtagScript:g,isThreads:m});}),l=false;}}else s(d,e,t);}),o(p,r,e,t,c),e.includes("_|_")&&r.length===2){let d=r[0],S=r[1];d&&S&&typeof d=="object"&&"dialogue"in d&&typeof S=="object"&&"labelToOpen"in S&&d.dialogue===" "&&S.labelToOpen&&(r.shift(),delete S.glueEnabled,r[0]=S);}}function nl(n,e,t,r,i,a){if(e.length===0)return;let s=on(e,r,t,i);if(s.length===1){let o={type:"ifelse",condition:s[0],then:n,else:a};return o.else||delete o.else,o}else if(s.length>1){let o={type:"ifelse",condition:{type:"union",unionType:"and",conditions:s},then:n,else:a};return o.else||delete o.else,o}}function yf(n,e,t,r,i,a,s=void 0){if(n.length===0){K.error("Error parsing ink file: Conditional statement is not valid",n);return}let o=[],u=[];if(n.forEach(h=>{Array.isArray(h)?u.push(h):typeof h=="string"&&h==="du"?i.du?o.push(i.du):i.du=o[o.length-1]:(typeof h!="string"||h!=="/ev")&&o.push(h);}),u.length===0){K.error("Error parsing ink file: Conditional statement is not valid",u);return}let l=tl(u[0],e,t,`${r}${"_|_"}then`,i,a,`${s||""}then`),c;return u.length===2?c=tl(u[1],e,t,`${r}${"_|_"}else`,i,a,`${s||""}else`):u.length>2?(u.shift(),u.push("nop"),u=[{b:u}],c=tl(u,e,t,r,i,a,`${s||""}else`)):c=void 0,i.du=void 0,nl(l,o,a,r,i,c)}function tl(n,e,t,r,i,a,s=void 0){let o=[];for(let l of n)typeof l=="object"&&"b"in l&&(l.b=l.b.filter(c=>c!==null&&!(typeof c=="object"&&"->"in c&&new RegExp(/.*\.[0-9]/).test(c["->"]))),un(l.b,r,i,o,e,e,t,ar,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function rl(n="",e=""){let t=Array.isArray(n)?n:[n],r=Array.isArray(e)?e:[e];return [...new Set([...t,...r])]}function ar(n,e,t,r,i){if(n.length>0){let a={};vf(n,a,i,r);for(let[s,o]of Object.entries(a)){let u=t+"_|_"+s,l={text:o.text.length===1?o.text[0]:o.text,label:u,props:{},type:Zu(u,false),oneTime:o.onetime};o.text.length===0&&(l.onlyHaveNoChoice=true,l.autoSelect=true),l.oneTime===false&&delete l.oneTime;let c=nl(l,o.conditions,i,t,r)||l,h=e[e.length-1];if(typeof h=="object"&&h&&"type"in h&&(h={conditionalStep:h}),e.length>0&&typeof h=="object"&&h&&"choices"in h&&h.choices){let p=h.choices;p&&Array.isArray(p)?p.push(c):K.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,p),h.choices=p.sort((f,g)=>{try{let m=f.label.split("."),b=m[m.length-1].replaceAll(".","_|_"),C=g.label.split("."),v=C[C.length-1].replaceAll(".","_|_");if(b.includes("c-")&&v.includes("c-")){let d=b.split("c-")[1],S=Number(d),y=v.split("c-")[1],w=Number(y);return S-w}}catch{}return 0});}else e.push({choices:[c]});o.preDialog&&(r.preDialog[u]={...o.preDialog});}}}function vf(n,e,t,r,i){let a=[],s="",o="",u=false,l=[];for(let c=0;c<n.length;c++){let h=n[c];if(typeof h=="string")h.startsWith("^")?a.push(Ft(h)):hf.includes(h)&&l.push(h);else if(Array.isArray(h)&&h.includes("visit")){let p=sr(h,Ds,(f,g,m)=>{},i,r,t);a.push(p);}else if(h&&typeof h=="object")if("*"in h&&typeof h["*"]&&typeof h["*"]=="string")h["*"].includes("c")&&(s=`c${h["*"].split("c")[1]}`,h.flg&16&&(u=true));else if("s"in h&&Array.isArray(h.s)){let p=bf(h.s),f=h.s.includes("<>");p&&(i&&e[i]?(e[i].preDialog={text:p,glue:f},e[i].text=rl(p,e[i].text)):(a.push(p),o=p));}else ("CNT?"in h||"VAR?"in h)&&l.push(h);else l.push(h);if(s){e[s]?e[s].text=rl(a,e[s].text):e[s]={text:a,onetime:u,conditions:l},o&&(e[s].preDialog={text:o,glue:false});let p=n.slice(c+1);vf(p,e,t,r,s);return}}}function bf(n){for(let e of n)if(typeof e=="string"){if(e.startsWith("^"))return Ft(e)}else if(Array.isArray(e)){let t=bf(e);if(t)return t}}var il;(i=>{function n(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:u=[],enums:l={},functions:c=[],preDialog:h={},characterIds:p}=s,f={$schema:mf};if(f.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:u,enums:l,functions:c,preDialog:h,characterIds:p}),f.labels&&Ss in f.labels){let g=f.labels[Ss];delete f.labels[Ss],g.forEach(m=>{m.operations&&(f.initialOperations=f.initialOperations?[...f.initialOperations,...m.operations]:[...m.operations]);});}if(f.labels&&Pn in f.labels){let g=f.labels[Pn];delete f.labels[Pn],g.forEach(m=>{m.operations&&(f.initialOperations=f.initialOperations?[...f.initialOperations,...m.operations]:[...m.operations]);});}return o.forEach(g=>{f.labels&&g in f.labels&&delete f.labels[g];}),u.forEach(g=>{f.initialOperations&&(f.initialOperations=f.initialOperations.filter(m=>!(m.type==="value"&&m.key===g)));}),f}i.inkToJson=n;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){K.error("Error parsing ink file",o);}}function t(a,s,o){for(let u of a)if(u)if(Array.isArray(u))if(u.includes("visit")){let l=sr(u,Ds,(c,h,p)=>{},"",o,[]);l&&(o.externalSwitch=l);}else t(u,s,o);else typeof u=="object"&&(u&&"VAR="in u&&o.externalSwitch&&(s[Pn]||(s[Pn]=[]),s[Pn].push({operations:ni({defaultType:"storage",key:u["VAR="],value:o.externalSwitch},[],o)})),r(u,s,"",o));}function r(a,s,o="",u){if(a!==null){for(let[l,c]of Object.entries(a))if(Array.isArray(c)){let h=[],p={},f=(o?o+"_|_":"")+l;un(c,f,u,h,Qu,Qu,(g,m,b)=>{r(g,p,m,b);},ar);for(let[g,m]of Object.entries(p))s[g]=m;h.length>0&&(s[f]=h);}}}})(il||={});var Mp=Zr(Xg()),Eb=Zr(Ay()),Db=Zr(bb()),Ab=Zr(Ar()),C1=/(?:^|<>)\s*#\s*([^\r\n]+)/g,S1=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,_1=new Set(["DONE","END"]),w1="_|_",Cb=new Map;function Ob(n,e){let t=JSON.stringify([e,n]),r=Cb.get(t);if(r)return r;let i=new RegExp(n,e);return Cb.set(t,i),i}function vs(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(s=>vs(n,s));let i=t.oneOf;if(Array.isArray(i))return i.some(s=>vs(n,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>vs(n,s));if(typeof t.const=="string")return n===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===n);if(t.type!=="string"||typeof t.minLength=="number"&&n.length<t.minLength||typeof t.maxLength=="number"&&n.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!Ob(t.pattern,"").test(n))return !1}catch{return false}return true}function Nu(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(o=>Nu(n,o));let i=t.oneOf;if(Array.isArray(i))return i.some(o=>Nu(n,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>Nu(n,o));if(t.type!=="array"||typeof t.minItems=="number"&&n.length<t.minItems||typeof t.maxItems=="number"&&n.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(n.length<s.length)return false;for(let o=0;o<s.length;o++)if(!vs(n[o],s[o]))return false;return n.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:n.slice(s.length).every(o=>vs(o,t.items))}function qp(n,e){if(e.type==="regexp")try{let t=Ob(e.source,e.flags);return t.lastIndex=0,t.test(n.join(" "))}catch{return false}return e.type==="literal"?n.join(" ")===e.value:Nu(n,e.schema)}function Fu(n){if(!n||typeof n!="object")return [];let e=n;if(Array.isArray(e.anyOf))return e.anyOf.flatMap(Fu);if(Array.isArray(e.oneOf))return e.oneOf.flatMap(Fu);if(Array.isArray(e.allOf)){let t={};for(let r of e.allOf)r&&typeof r=="object"&&Object.assign(t,r);return Fu(t)}return e.type==="array"&&Array.isArray(e.prefixItems)?[e]:[]}function Sb(n,e){if(n===e)return 1;let t=Math.max(n.length,e.length);return t===0?1:Math.max(0,1-Pb(n,e)/t)}function E1(n,e){if(e&&typeof e=="object"){let t=e;if(typeof t.const=="string")return {weight:2,matched:n===void 0?0:2*Sb(n,t.const)};if(Array.isArray(t.enum))return {weight:2,matched:2*(n===void 0?0:Math.max(0,...t.enum.filter(i=>typeof i=="string").map(i=>Sb(n,i))))}}return {weight:1,matched:n===void 0?0:1}}function D1(n,e){let t=Array.isArray(e.prefixItems)?e.prefixItems:[],r=Math.min(t.length,n.length),i=0,a=0,s=false;for(let o=0;o<r;o++){let u=E1(n[o],t[o]);i+=u.weight,a+=u.matched,u.weight>1&&(s=true);}return {score:i===0?0:a/i,hasDiscriminant:s}}var A1=.8,_b=new Map;function O1(n){let e=JSON.stringify(n),t=_b.get(e);if(t)return t;let r=new Eb.default({strict:false,allErrors:true}).compile(n);return _b.set(e,r),r}function P1(n){if("items"in n)return n;let e=Array.isArray(n.prefixItems)?n.prefixItems.length:0;return {...n,minItems:e,maxItems:e,items:false}}function x1(n,e){let[t]=Ru(n.instancePath);if(t!==void 0&&/^\d+$/.test(t)){let r=Number(t);if(r<e.length)return e[r]}return Gp(n)}function T1(n){return n.keyword==="const"?`must be "${n.params.allowedValue}"`:n.keyword==="enum"?`must be one of ${(n.params.allowedValues??[]).map(t=>`"${t}"`).join(", ")}`:n.message??"invalid value"}function Bp(n){let e=n.split(/\r?\n/),t=[];for(let r=0;r<e.length;r++){let i=e[r];for(let a of i.matchAll(C1)){let s=(a[1]??"").trim();if(!s)continue;let o=Nt.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:r+1,command:s,tokens:o});}}return t}function Gp(n){return n.keyword==="required"&&typeof n.params?.missingProperty=="string"?n.params.missingProperty:n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"?n.params.additionalProperty:n.instancePath.split("/").pop()||"(root)"}function Pb(n,e){let t=n.length+1,r=e.length+1,i=Array.from({length:t},(a,s)=>[s,...Array(r-1).fill(0)]);for(let a=1;a<r;a++)i[0][a]=a;for(let a=1;a<t;a++)for(let s=1;s<r;s++){let o=n[a-1]===e[s-1]?0:1;i[a][s]=Math.min(i[a-1][s]+1,i[a][s-1]+1,i[a-1][s-1]+o);}return i[t-1][r-1]}function N1(n,e){let t,r=1/0;for(let a of e){let s=Pb(n,a);s<r&&(r=s,t=a);}let i=Math.max(1,Math.floor(n.length/3));return r<=i?t:void 0}function F1(n,e){if(n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"){let t=n.params.additionalProperty,r=e&&N1(t,e),i=r?` (did you mean "${r}"?)`:"";return `has an unrecognised property "${t}"${i}`}return n.message??"invalid value"}function Ru(n){return n.split("/").filter(Boolean).map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~"))}function I1(n,e){let t=n,r,i=a=>{a&&typeof a=="object"&&typeof a.$origin=="string"&&(r=a.$origin);};i(t);for(let a of Ru(e)){if(t===null||typeof t!="object")break;t=t[a],i(t);}return r}function k1(n,e){let t=Ru(e);for(let r=t.length;r>=0;r--){let i=t.slice(0,r),a=n;for(let s of i){if(a===null||typeof a!="object"){a=void 0;break}a=a[s];}if(a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.type=="string")return {path:`/${i.map(o=>o.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`,node:a}}}function ku(n,e,t=new Set){if(!n||typeof n!="object")return n;let r=n.$ref;if(typeof r!="string")return n;let i=r.match(/^#\/definitions\/([^/]+)$/);return !i?.[1]||t.has(i[1])||!(i[1]in e)?{}:(t.add(i[1]),ku(e[i[1]],e,t))}function Vu(n,e){let t=ku(n,e);if(!t||typeof t!="object")return;let r=t;if(!(r.anyOf||r.oneOf)){if(Array.isArray(r.allOf)){let i={properties:{},required:[]};for(let a of r.allOf){let s=Vu(a,e);if(!s)return;Object.assign(i.properties,s.properties),i.required.push(...s.required);}return i}return {properties:r.properties??{},required:r.required??[]}}}function wb(n,e){if(!n||typeof n!="object")return true;let t=n;return "const"in t?t.const===e:Array.isArray(t.enum)?t.enum.includes(e):true}function V1(n,e){let t=n.definitions??{},r=[];for(let[i,a]of Object.entries(t)){let s=Vu(a,t);if(!s)continue;let o=s.properties.type;o&&typeof o=="object"&&("const"in o||Array.isArray(o.enum))&&wb(o,e.type)&&wb(s.properties.operationType,e.operationType)&&r.push(i);}return r}function R1(n,e,t){let r=n.definitions??{},i={definitions:r,...r[e]},a=new Mp.default({strict:false,allErrors:true}).compile(i);return a(t)?[]:a.errors??[]}function j1(n,e,t){let r=n.definitions??{},i=ku(r[e],r);for(let a of Ru(t)){let o=Vu(i,r)?.properties[a];if(o===void 0)return [];i=ku(o,r);}return Object.keys(Vu(i,r)?.properties??{})}function Iu(n){let e=n.map(o=>o.instancePath),t=o=>e.some(u=>u!==o&&u.startsWith(`${o}/`)),r=n.filter(o=>!t(o.instancePath)),i=new Map;for(let o of r){let u=i.get(o.instancePath)??[];u.push(o),i.set(o.instancePath,u);}let a=[];for(let o of i.values()){let u=o.filter(l=>l.keyword!=="anyOf"&&l.keyword!=="oneOf");a.push(...u.length>0?u:o);}let s=new Set;return a.filter(o=>{let u=`${Gp(o)}|${o.message}`;return s.has(u)?false:(s.add(u),true)})}function Wp(n,e,t){return n.map(r=>({instancePath:r.instancePath||"(root)",element:Gp(r),message:F1(r,t?.(r)),origin:I1(e,r.instancePath)}))}function $1(n,e,t){let r=n.map(c=>c.instancePath),i=c=>r.some(h=>h!==c&&h.startsWith(`${c}/`)),a=n.filter(c=>!i(c.instancePath)),s=t&&typeof t=="object"?t:void 0,o=new Map,u=[];for(let c of a){let h=s?k1(e,c.instancePath):void 0;if(!h){u.push(c);continue}let p=o.get(h.path);p?p.errors.push(c):o.set(h.path,{node:h.node,errors:[c]});}let l=Wp(Iu(u),e);for(let[c,h]of o){let p=s?V1(s,h.node):[],f=p.length===1?p[0]:void 0;if(!f||!s){l.push(...Wp(Iu(h.errors),e));continue}let m=Iu(R1(s,f,h.node)).map(b=>({...b,instancePath:`${c}${b.instancePath}`}));l.push(...Wp(m,e,b=>j1(s,f,b.instancePath.slice(c.length))));}return l}var Jp;(h=>{function n(p,f={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let g=[];try{return {json:new Db.Compiler(p,{errorHandler:(v,d)=>{let S=v.replace(/^[A-Z]+: line \d+: ?/,""),y=v.match(/line (\d+)/);g.push({message:S,type:d,line:y?Number(y[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:v=>v,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:g}}catch{let b=false,C={...f,textSource:p};return e(g,()=>{b=true;},C),b?n(C.textSource,f):{issues:g}}}h.compile=n;function e(p,f,g){let{functions:m,initialVarsToRemove:b,labelToRemove:C}=g,v=p.find(d=>d.type===Ab.ErrorType.Error);if(v){if(v.message.includes("Divert target not found")){let d=v.message.match(/Divert target not found: '-> (\w+)'/);if(d?.[1]){let S=d[1],y=`
67
+
68
+ === ${S} ===
69
+
70
+ -> DONE`;return g.textSource=g.textSource.concat(y),C.push(S),f()}}if(v.message.includes("Unresolved variable")){let d=v.message.match(/Unresolved variable: (\w+)/);if(d?.[1]){let S=d[1],y=`VAR ${S} = ""
71
+
72
+ `;return g.textSource=y.concat(g.textSource),b.push(S),f()}}if(v.message.includes("Variable could not be found to assign to")){let d=v.message.match(/Variable could not be found to assign to: (\w+)/);if(d?.[1]){let S=d[1],y=`VAR ${S} = ""
73
+
74
+ `;return g.textSource=y.concat(g.textSource),b.push(S),f()}}if(v.message.includes("Variable could not be found to assign to")){let d=v.message.match(/Variable could not be found to assign to: '(\w+)'/);if(d?.[1]){let S=d[1],y=`VAR ${S} = ""
75
+
76
+ `;return g.textSource=y.concat(g.textSource),b.push(S),f()}}if(v.message.includes("Function call target not found")){let d=v.message.match(/Function call target not found: '-> (\w+)'/);if(d?.[1]){let S=d[1],y=`
77
+
78
+ === function ${S}() ===
79
79
 
80
80
  ~ return
81
81
 
82
- `;return g.textSource=g.textSource.concat(y),m.push({name:_,args:0}),b.push(_),p()}}if(v.message.includes(" arguments, but got ")){let d=v.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(d?.[1]){let _=d[1],y=parseInt(d[3]||"0",10),E=y>0?Array.from({length:y},(x,H)=>`arg${H+1}`).join(", "):"",w=`
82
+ `;return g.textSource=g.textSource.concat(y),m.push({name:S,args:0}),C.push(S),f()}}if(v.message.includes(" arguments, but got ")){let d=v.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(d?.[1]){let S=d[1],y=parseInt(d[3]||"0",10),w=y>0?Array.from({length:y},(x,U)=>`arg${U+1}`).join(", "):"",E=`
83
83
 
84
- === function ${_}(${E}) ===
84
+ === function ${S}(${w}) ===
85
85
 
86
86
  ~ return
87
87
 
88
88
  `;g.textSource=g.textSource.replaceAll(`
89
89
 
90
- === function ${_}() ===
90
+ === function ${S}() ===
91
91
 
92
92
  ~ return
93
93
 
94
- `,""),g.textSource=g.textSource.concat(w);let P=m.find(x=>x.name===_);return P?P.args=y:(m.push({name:_,args:y}),b.push(_)),p()}}if(v.message.includes("Could not find target for read count")){let d=v.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(d?.[1]){let _=d[1],[y,E]=_.split("."),w=`
94
+ `,""),g.textSource=g.textSource.concat(E);let O=m.find(x=>x.name===S);return O?O.args=y:(m.push({name:S,args:y}),C.push(S)),f()}}if(v.message.includes("Could not find target for read count")){let d=v.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(d?.[1]){let S=d[1],[y,w]=S.split("."),E=`
95
95
 
96
- LIST ${y} = ${E}
96
+ LIST ${y} = ${w}
97
97
 
98
- `;return g.textSource=g.textSource.concat(w),g.initialVarsToRemove.push(y),g.initialVarsToRemove.push(`${y}.${E}`),p()}}if(v.message.includes("variable for increment could not be found")){let d=v.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(d?.[1]){let _=d[1],y=`VAR ${_} = 0
98
+ `;return g.textSource=g.textSource.concat(E),g.initialVarsToRemove.push(y),g.initialVarsToRemove.push(`${y}.${w}`),f()}}if(v.message.includes("variable for increment could not be found")){let d=v.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(d?.[1]){let S=d[1],y=`VAR ${S} = 0
99
99
 
100
- `;return g.textSource=y.concat(g.textSource),g.initialVarsToRemove.push(_),p()}}return f.forEach(d=>{let _=d.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);_?.[1]&&(d.message=`The function '${_[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:f}}return {issues:f}}h.getErrors=e;function t(f,p){return qf(f).filter(({tokens:g})=>!p.some(({validation:m})=>Lf(g,m)))}h.getUnknownHashtagCommands=t;function r(f,p){let g=p.filter(C=>C.validation.type==="zod");if(g.length===0)return [];let m=[];for(let C of qf(f)){if(p.some(({validation:d})=>Lf(C.tokens,d)))continue;let b;for(let d of g)for(let _ of Tu(d.validation.schema)){let{score:y,hasDiscriminant:E}=E1(C.tokens,_);E&&(!b||y>b.score)&&(b={command:d,branch:_,score:y});}if(!b||b.score<w1)continue;let v=D1(A1(b.branch));if(!v(C.tokens))for(let d of Nu(v.errors??[]))m.push({line:C.line,command:C.command,handlerName:b.command.name,instancePath:d.instancePath||"(root)",element:P1(d,C.tokens),message:O1(d),score:b.score});}return m}h.getLikelyUnknownHashtagCommandSchemaIssues=r;function i(f,p){let g=new Set;for(let d of f.matchAll(C1))d[1]&&g.add(d[1]);let m=new Set(p),C=new Set,b=f.split(/\r?\n/),v=[];for(let d=0;d<b.length;d++){let _=(b[d]??"").replace(/\/\/.*$/,"");for(let y of _.matchAll(/->[ \t]+(\w[\w.]*)/g)){let E=y[1];if(!E)continue;let w=E.split(".")[0]??E;b1.has(w)||g.has(w)||m.has(E)||m.has(E.replaceAll(".",_1))||m.has(w)||C.has(E)||(C.add(E),v.push({line:d+1,target:E}));}}return v}h.getUnknownDivertTargets=i;function a(f){return new Wf.default({strict:false,allErrors:true}).compile(f)}h.getSchemaValidator=a;function s(f,p){let g=typeof p=="function"?p:a(p);return g(f)?[]:R1(g.errors??[],f,g.schema)}h.validateAgainstJsonSchema=s;function o(f,p){let g=new Set,m=[];for(let d of p){let _=u(d);_!==void 0?m.push(_):g.add(String(d));}m.sort((d,_)=>_-d);let C=[],b=f.length;for(let d=f.length-1;d>=0;d--)g.has(f[d])&&(C.push({key:f[d],sectionTokens:f.slice(d+1,b)}),b=d);C.reverse();let v=[];for(let d of m)d<0||d>=b||(v.push({key:d,sectionTokens:f.slice(d,b)}),b=d-1);return v.reverse(),[...v,...C]}h.extractKeyedSections=o;function u(f){return typeof f=="number"?Number.isInteger(f)&&f>=0?f:void 0:/^\d+$/.test(f)?Number(f):void 0}function l(f,p){let g=o(f,Object.keys(p)),m=[];for(let{key:C,sectionTokens:b}of g){let v;try{v=xt.convertListStringToObj(b);}catch(_){m.push({key:C,instancePath:"(root)",element:String(C),message:`could not parse "${C}" section into key/value pairs: ${_ instanceof Error?_.message:String(_)}`});continue}let d=s(v,p[C]);m.push(...d.map(_=>({..._,key:C})));}return m}h.validateKeyedJsonSchemas=l;function c(f,p){let g=[];for(let m of qf(f)){let C=p.find(({validation:v})=>Lf(m.tokens,v));if(!C?.keySchemas)continue;let b=l(m.tokens,C.keySchemas);g.push(...b.map(v=>({...v,line:m.line,command:m.command})));}return g}h.getHashtagKeySchemaIssues=c;})(Gf||={});var Jf=Xr(wr());function P0(n){if(!n||n.length===0)return;let e=new Set;for(let t of n){let r=typeof t=="string"?t:t?.id;typeof r=="string"&&r.length>0&&e.add(r);}return e.size>0?e:void 0}function Vu(n,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:n},{json:r,issues:i}=Gf.compile(n,t);if(i.forEach(({message:s,type:o})=>{o===Jf.ErrorType.Error?U.error(`Ink compilation error: ${s}`):o===Jf.ErrorType.Warning?U.warn(`Ink compilation warning: ${s}`):U.info(`Ink compilation info: ${s}`);}),!r){U.error("No JSON generated from ink file");return}let a;try{a=Qr.parse(r);}catch{U.error("Error parsing ink file");return}return t.enums=a.listDefs||{},nl.inkToJson(a,{...t,characterIds:P0(e.characters)})}var Ge;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Ge||={});var A=class X{static init(e){e.loadAssets&&(X._loadAssets=e.loadAssets),e.soundOperation&&(X._soundOperation=e.soundOperation),e.imageOperation&&(X._imageOperation=e.imageOperation),e.videoOperation&&(X._videoOperation=e.videoOperation),e.imageContainerOperation&&(X._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(X._textOperation=e.textOperation),e.canvasElementOperation&&(X._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(X._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(X._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(X._narrationOperation=e.narrationOperation),e.effectOperation&&(X._effectOperation=e.effectOperation),e.animateOperation&&(X._animateOperation=e.animateOperation),e.canvasOperation&&(X._canvasOperation=e.canvasOperation),e.getLogichValue&&(X._getLogichValue=e.getLogichValue),e.getConditionalStep&&(X._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return X._loadAssets}static _soundOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return X._soundOperation}static _imageOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return X._imageOperation}static _videoOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return X._videoOperation}static _imageContainerOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return X._imageContainerOperation}static _textOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return X._textOperation}static _canvasElementOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return X._canvasElementOperation}static _setStorageValue=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return X._setStorageValue}static _setInitialStorageValue=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return X._setInitialStorageValue}static _narrationOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return X._narrationOperation}static _effectOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return X._effectOperation}static _animateOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return X._animateOperation}static _canvasOperation=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return X._canvasOperation}static _getLogichValue=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return X._getLogichValue}static _getConditionalStep=()=>{throw Ge.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return X._getConditionalStep}};var ys;(n=>{n.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(l,c){e.unshift({fn:l,opts:c});}n.add=t;function r(l){let c=e.findIndex(h=>h.fn===l);c!==-1&&e.splice(c,1);}n.remove=r;function i(){return e.map(l=>l.opts)}n.info=i;function a(l,c){let h=e.filter(f=>(f.opts.type??"after-translation")===c.type);for(let f of h)l=u(l,f.fn,f.opts.validation);return l}n.replace=a;function s(l){let c=e.filter(h=>h.opts.i18nInterpolation);for(let h of c)l=o(l,h.fn,h.opts);return l}n.runI18nPreStep=s;function o(l,c,h){let{validation:f}=h,p=new RegExp(n.options.replaceRegex.source,"g"),g=[...l.matchAll(p)],m=new Set,C=[];for(let b of g)m.has(b[1])||(m.add(b[1]),C.push(b[1]));for(let b of C){if(f==="characterId"){if(!characters.RegisteredCharacters.has(b))continue}else if(f!=="all"){if(f instanceof RegExp){if(!f.test(b))continue}else if(f instanceof zod.ZodType&&!f.safeParse(b).success)continue}c(b)!==void 0&&(l.includes(`{{[${b}]}}`)||(l=l.replaceAll(`[${b}]`,`{{[${b}]}}`)));}return l}function u(l,c,h){let f=new RegExp(n.options.replaceRegex.source,"g"),p=[...l.matchAll(f)],g=new Set,m=[];for(let C of p)g.has(C[1])||(g.add(C[1]),m.push(C[1]));for(let C of m){if(h==="characterId"){if(!characters.RegisteredCharacters.has(C))continue}else if(h!=="all"){if(h instanceof RegExp){if(!h.test(C))continue}else if(h instanceof zod.ZodType&&!h.safeParse(C).success)continue}let b=c(C);b!==void 0&&(l=l.replaceAll(`[${C}]`,b));}return l}})(ys||={});function $1(n,e={}){let t="";return n.values.forEach(r=>{if(typeof r=="string")t+=r;else {let i=A.getLogichValue(r,e);t+=`${i}`;}}),t}var T0;(n=>{let e=u=>u;function t(u){return Array.isArray(u)?u.map(l=>r(`${l}`)):r(`${u}`)}n.t=t;function r(u){let l=u;return n.beforeToTranslate&&(l=(0, n.beforeToTranslate)(l)),l=ys.replace(l,{type:"before-translation"}),l=e(l),n.afterToTranslate&&(l=(0, n.afterToTranslate)(l)),l=ys.replace(l,{type:"after-translation"}),l}n.translate=r;function i(u){e=u;}n.setTranslate=i;function a(u,l,c){let{defaultValue:h="empty_string"}=c;typeof l=="string"&&(l=[l]),Array.isArray(l)&&l.forEach(f=>{let p=f;if(n.beforeToTranslate&&(p=(0, n.beforeToTranslate)(p)),h==="empty_string")u[p]===void 0&&(u[p]="");else if(h==="copy_key"){let g=f;n.beforeToTranslate&&(g=(0, n.beforeToTranslate)(g));let m=ys.runI18nPreStep(g);m=ys.replace(m,{type:"before-translation"}),u[p]=m;}});}function s(u,l=[]){if(typeof u=="object"&&u&&"type"in u)if(u.type==="ifelse")u.then&&s(u.then,l),u.else&&s(u.else,l);else if(u.type==="stepswitch"){if(u.elements)if(Array.isArray(u.elements))u.elements.forEach(c=>{s(c,l);});else if(u.elements.type==="ifelse"){let c=[];s(u.elements,c),c.forEach(h=>{l.push(...h);});}else if(u.elements.type==="stepswitch"){let c=[];s(u.elements,c),c.forEach(h=>{l.push(...h);});}else s(u.elements,l);}else u.type==="resulttocombine"?(u.firstItem&&s(u.firstItem,l),u.secondConditionalItem&&u.secondConditionalItem.forEach(c=>{s(c,l);})):l.push(u);else u&&l.push(u);return l}async function o(u,l={},c={}){let{defaultValue:h="copy_key",operationStringConvert:f}=c,p=u.map(async g=>{if(g.choices){let m=[];Array.isArray(g.choices)?m=[g.choices]:m=s(g.choices),m.forEach(C=>{C.forEach(b=>{if("type"in b){let v=[];b.type==="ifelse"||b.type==="stepswitch"?s(b,v):v=[b],v.map(d=>s(d.text)).forEach(d=>{Array.isArray(d)&&d.forEach(_=>{Array.isArray(_)?_.forEach(y=>{typeof y=="string"?a(l,y,{defaultValue:h}):s(y).forEach(E=>{Array.isArray(E)?E.forEach(w=>{typeof w=="string"&&a(l,w,{defaultValue:h});}):typeof E=="string"&&a(l,E,{defaultValue:h});});}):typeof _=="string"&&a(l,_,{defaultValue:h});});});}});});}if(g.dialogue){let m=[];Array.isArray(g.dialogue)?m=[g.dialogue]:m=s(g.dialogue),m.forEach(C=>{if(typeof C=="string")a(l,C,{defaultValue:h});else if("text"in C){let b=s(C.text);typeof b=="string"&&(b=[b]),b.forEach(v=>{typeof v=="string"?a(l,v,{defaultValue:h}):s(v).forEach(d=>{typeof d=="string"?a(l,d,{defaultValue:h}):Array.isArray(d)&&d.forEach(_=>{typeof _=="string"?a(l,_,{defaultValue:h}):s(_).forEach(y=>{typeof y=="string"&&a(l,y,{defaultValue:h});});});});});}});}if(g.operations)for(let m of g.operations){if(m.type==="operationtoconvert"&&f){let C=$1(m),b=await f(C,g,{});if(!b)return;m=b;}m.type==="text"&&m.operationType==="show"&&a(l,m.text,{defaultValue:h});}g.conditionalStep&&s(g.conditionalStep).forEach(m=>{Array.isArray(m)?o(m,l,c):o([m],l,c);});});return await Promise.all(p),l}n.generateJsonTranslation=o;})(T0||={});var Ct=T0;async function N0(n){let e=A.getLogichValue(n,{});if(e)switch(e.type){case "assets":switch(e.operationType){case "load":await canvas.Assets.load(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoad(e.aliases);break}break;case "bundle":switch(e.operationType){case "load":await canvas.Assets.loadBundle(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoadBundle(e.aliases);break}break}}var Z;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Z||={});async function ju(n,e,t){switch(t.type){case "fade":await canvas.showWithFade(e.alias,n,t.props,t.priority);break;case "dissolve":await canvas.showWithDissolve(e.alias,n,t.props,t.priority);break;case "movein":case "moveout":await canvas.moveIn(e.alias,n,t.props,t.priority);break;case "zoomin":case "zoomout":await canvas.zoomIn(e.alias,n,t.props,t.priority);break;case "pushin":case "pushout":await canvas.pushIn(e.alias,n,t.props,t.priority);break}}function vs(n){if(n.transition)switch(n.transition.type){case "fade":canvas.removeWithFade(n.alias,n.transition.props,n.transition.priority);break;case "dissolve":canvas.removeWithDissolve(n.alias,n.transition.props,n.transition.priority);break;case "movein":case "moveout":canvas.moveOut(n.alias,n.transition.props,n.transition.priority);break;case "zoomin":case "zoomout":canvas.zoomOut(n.alias,n.transition.props,n.transition.priority);break;case "pushin":case "pushout":canvas.pushOut(n.alias,n.transition.props,n.transition.priority);break}else canvas.canvas.remove(n.alias);}async function F0(n){switch(n.operationType){case "show":if(n.transition){let e=new canvas.ImageSprite(n.props,n.url||n.alias);await ju(e,n,n.transition);}else await canvas.showImage(n.alias,n.url,n.props);break;case "edit":{let e=canvas.canvas.find(n.alias);e?n.props&&await e.setMemory({...e.memory,...n.props}):Z.error(`Image with alias ${n.alias} not found.`);break}case "remove":vs(n);break}}async function I0(n){switch(n.operationType){case "show":if(n.transition){let e=new canvas.VideoSprite(n.props,n.url||n.alias);await ju(e,n,n.transition);}else await canvas.showVideo(n.alias,n.url,n.props);break;case "edit":{let e=canvas.canvas.find(n.alias);e?n.props&&await e.setMemory({...e.memory,...n.props}):Z.error(`Video with alias ${n.alias} not found.`);break}case "remove":vs(n);break;case "pause":case "resume":{let e=canvas.canvas.find(n.alias);e?e.paused=n.operationType==="pause":Z.error(`Video with alias ${n.alias} not found.`);break}}}async function k0(n){switch(n.operationType){case "show":if(n.transition){let e=new canvas.ImageContainer(n.props,n.urls);await ju(e,n,n.transition);}else await canvas.showImageContainer(n.alias,n.urls,n.props);break;case "edit":{let e=canvas.canvas.find(n.alias);e?n.props&&await e.setMemory({...e.memory,...n.props}):Z.error(`ImageContainer with alias ${n.alias} not found.`);break}case "remove":vs(n);break}}async function V0(n){switch(n.operationType){case "show":if(n.props=n.props||{},n.props.text=Ct.t(n.text),n.transition){let e=new canvas.Text(n.props);await ju(e,n,n.transition);}else canvas.showText(n.alias,n.text,n.props);break;case "edit":{let e=canvas.canvas.find(n.alias);e?n.props&&await e.setMemory({...e.memory,...n.props}):Z.error(`Text with alias ${n.alias} not found.`);break}case "remove":vs(n);break}}async function R0(n){switch(n.operationType){case "edit":try{let e=canvas.canvas.find(n.alias);e?n.props&&e.setMemory({...e.memory,...n.props}):Z.error(`Canvas Element with alias ${n.alias} not found.`);}catch(e){Z.error(`There was an error while trying to edit the canvas element with alias ${n.alias}.`,e);}break;case "remove":vs(n);break}}function $0(n){n.operationType==="clear"&&canvas.canvas.removeAll();}async function j0(n){n.type==="shake"&&await canvas.shakeEffect(n.alias,n.props,n.priority);}function L0(n){switch(n.type){case "animate":canvas.canvas.animate(n.alias,n.keyframes,n.options,n.priority);break;case "animate-sequence":canvas.canvas.animate(n.alias,n.sequence,n.options,n.priority);break}}function q0(n){switch(n.type){case "input":narration.narration.input.request({type:n.valueType},n.defaultValue);break;case "dialogue":narration.narration.dialogue=void 0;break}}function B0(n){switch(n.operationType){case "play":n.url?sound.sound.play(n.alias,n.url,n.props):sound.sound.play(n.alias,n.props);break;case "stop":switch(n.type){case "sound":sound.sound.stop(n.alias);break;case "all":sound.sound.stopAll();break}break;case "pause":switch(n.type){case "sound":sound.sound.pause(n.alias);break;case "channel":sound.sound.channels.find(n.alias).pauseAll();break;case "all":sound.sound.pauseAll();break}break;case "resume":switch(n.type){case "sound":sound.sound.resume(n.alias);break;case "channel":sound.sound.channels.find(n.alias).resumeAll();break;case "all":sound.sound.resumeAll();break}break;case "edit":Object.entries(n.props).forEach(([e,t])=>{let r=sound.sound.find(n.alias);r&&(e==="volume"?r.volume.value=t:r.paused=t);});break}}var zf="___param___",iN=class Y{static init(e){e.loadAssets&&(Y._loadAssets=e.loadAssets),e.soundOperation&&(Y._soundOperation=e.soundOperation),e.imageOperation&&(Y._imageOperation=e.imageOperation),e.videoOperation&&(Y._videoOperation=e.videoOperation),e.imageContainerOperation&&(Y._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(Y._textOperation=e.textOperation),e.canvasElementOperation&&(Y._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(Y._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(Y._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(Y._narrationOperation=e.narrationOperation),e.effectOperation&&(Y._effectOperation=e.effectOperation),e.animateOperation&&(Y._animateOperation=e.animateOperation),e.canvasOperation&&(Y._canvasOperation=e.canvasOperation),e.getLogichValue&&(Y._getLogichValue=e.getLogichValue),e.getConditionalStep&&(Y._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return Y._loadAssets}static _soundOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return Y._soundOperation}static _imageOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return Y._imageOperation}static _videoOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return Y._videoOperation}static _imageContainerOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return Y._imageContainerOperation}static _textOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return Y._textOperation}static _canvasElementOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return Y._canvasElementOperation}static _setStorageValue=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return Y._setStorageValue}static _setInitialStorageValue=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return Y._setInitialStorageValue}static _narrationOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return Y._narrationOperation}static _effectOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return Y._effectOperation}static _animateOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return Y._animateOperation}static _canvasOperation=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return Y._canvasOperation}static _getLogichValue=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return Y._getLogichValue}static _getConditionalStep=()=>{throw Z.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return Y._getConditionalStep}};function sN(n,e){if(e&&typeof e=="object"&&typeof n.functionName=="string"&&n.functionName in e){let t=e[n.functionName];if(typeof t=="function"){let r=n.args.map(i=>iN.getLogichValue(i,e));return t(...r)}else Z.warn(`getLogichValue function ${n.functionName} not found in props`);}}function W0(n,e){let t=A.getLogichValue(n,e);return t&&typeof t=="object"&&"type"in t?A.getLogichValue(t,e):t}function M0(n,e={}){let t=W0(n.value,e);switch(n.storageType){case "flagStorage":storage.storage.flags.set(n.key,n.value);break;case "storage":storage.storage.set(n.key,t);break;case "tempstorage":storage.storage.temp.set(n.key,t);break;case "params":{let r=storage.storage.get(`${zf}${narration.narration.labels.opened.length-1}`)||[];r.length>n.key&&(r[n.key]=t),storage.storage.temp.set(`${zf}${narration.narration.labels.opened.length-1}`,r);break}}}function G0(n,e={}){let t=W0(n.value,e);switch(n.storageType){case "storage":case "tempstorage":storage.storage.default={[n.key]:t};break}}function J0(n,e={}){let t=z0(n,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return oN(t,e);case "arithmetic":case "arithmeticsingle":return aN(t,e);case "compare":case "union":return uN(t,e);case "function":return sN(t,e)}return t}function aN(n,e){let t=A.getLogichValue(n.leftValue,e);switch(n.type){case "arithmetic":{let r=A.getLogichValue(n.rightValue,e);switch(n.operator){case "*":return t*r;case "/":return t/r;case "+":return typeof t=="string"||typeof r=="string"?`${t}${r}`:Array.isArray(t)&&Array.isArray(r)?[...t,...r]:Array.isArray(t)?[...t,r]:Array.isArray(r)?[t,...r]:t+r;case "-":if(Array.isArray(t)&&Array.isArray(r))return t.filter(i=>!r.includes(i));if(Array.isArray(t))return t.filter(i=>i!==r);if(Array.isArray(r)){Z.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-r;case "%":return t%r;case "POW":return t**r;case "RANDOM":return narration.narration.getRandomNumber(t,r);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(r))return t.filter(i=>r.includes(i));Z.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:Z.warn("getValueFromArithmeticOperations unknown operator",n);return}}case "arithmeticsingle":switch(n.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function oN(n,e){if(n&&typeof n=="object"&&"type"in n&&n.type==="value"&&n.storageOperationType==="get")switch(n.storageType){case "storage":case "tempstorage":return n.key==="_input_value_"?narration.narration.input.value:storage.storage.get(n.key);case "flagStorage":return storage.storage.flags.get(n.key);case "label":return narration.narration.queries.timesLabelOpened(n.label);case "choice":return narration.narration.queries.timesChoiceMade(n.index);case "logic":return A.getLogichValue(n.operation,e);case "params":{let t=storage.storage.get(`${zf}${narration.narration.labels.opened.length-1}`)||[];if(t&&t.length>n.key)return t[n.key];Z.warn("getValue params not found");return}}return n}function uN(n,e){if(!n)return false;if(typeof n!="object"||!("type"in n))return !!n;switch(n.type){case "compare":{let t=A.getLogichValue(n.leftValue,e),r=A.getLogichValue(n.rightValue,e);switch(n.operator){case "==":return Array.isArray(t)&&Array.isArray(r)?t.length===r.length&&t.every(i=>r.includes(i)):t===r;case "!=":return Array.isArray(t)&&Array.isArray(r)?t.length!==r.length||!t.every(i=>r.includes(i)):t!==r;case "<":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)<0:Array.isArray(t)&&Array.isArray(r)?t.length<r.length:t<r;case "<=":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)<=0:Array.isArray(t)&&Array.isArray(r)?t.length<=r.length:t<=r;case ">":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)>0:Array.isArray(t)&&Array.isArray(r)?t.length>r.length:t>r;case ">=":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)>=0:Array.isArray(t)&&Array.isArray(r)?t.length>=r.length:t>=r;case "CONTAINS":return Array.isArray(t)&&Array.isArray(r)?r.every(i=>t.includes(i)):Array.isArray(t)?t.includes(r):t.toString().includes(r.toString())}break}case "value":{let t=A.getLogichValue(n,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return lN(n,e)}return !!n}function lN(n,e){if(n.unionType==="not"){let r=J0(n.condition,e);return Array.isArray(r)?r.length===0:r&&typeof r=="object"?Object.keys(r).length===0:!r}let t=r=>A.getLogichValue(r,e)||false;return n.unionType==="and"?n.conditions.every(t):n.conditions.some(t)}function cN(n,e){return Math.floor(Math.random()*(e-n+1)+n)}function z0(n,e={}){if(Array.isArray(n)||!n)return n;if(n&&typeof n=="object"&&"type"in n)switch(n.type){case "resulttocombine":return hN(n,e);case "ifelse":return A.getLogichValue(n.condition,e)?A.getLogichValue(n.then,e):A.getLogichValue(n.else,e);case "stepswitch":{let t=A.getLogichValue(n.elements,e)||[];if(t.length===0){Z.error("getValueFromConditionalStatements elements.length === 0");return}switch(n.choiceType){case "random":{let r=cN(0,t.length-1);return A.getLogichValue(t[r],e)}case "loop":{let r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(n.nestedId)-1;return r>t.length-1?(r=r%t.length,A.getLogichValue(t[r],e)):A.getLogichValue(t[r],e)}case "sequential":{let r,i=narration.NarrationManagerStatic.getCurrentStepTimesCounter(n.nestedId)-1;return n.end==="lastItem"&&(r=A.getLogichValue(t[t.length-1],e)),i>t.length-1?r:A.getLogichValue(t[i],e)}case "sequentialrandom":{let r=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:n.nestedId,onceOnly:true});if(r===void 0&&n.end==="lastItem"){let i=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(n.nestedId);if(!i?.usedRandomNumbers){Z.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=i.usedRandomNumbers[`0-${t.length-1}`];return A.getLogichValue(t[a[a.length-1]],e)}if(r===void 0){Z.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return A.getLogichValue(t[r],e)}}}}return n}function Lu(n,e={}){if(n.conditionalStep){let t=pixiVn.createExportableElement(A.getLogichValue(n.conditionalStep,e));if(t?.glueEnabled===void 0&&delete t?.glueEnabled,t?.goNextStep===void 0&&delete t?.goNextStep,t?.end===void 0&&delete t?.end,t?.choices===void 0&&delete t?.choices,t?.dialogue===void 0&&delete t?.dialogue,t?.labelToOpen===void 0&&delete t?.labelToOpen,t?.operations===void 0&&delete t?.operations,t){let r={...n,conditionalStep:void 0,...t};return Lu(r,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return n}function hN(n,e){let t=n.firstItem,r=(n.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>A.getLogichValue(s,e)):[A.getLogichValue(a,e)]),i=t?[t,...r]:r;if(i.length===0){Z.warn("combinateResult toCheck.length === 0");return}if(typeof i[0]=="string")return Ct.t(i);if(typeof i[0]=="object"){let a=i,s,o=false,u=a.map((v,d)=>{v=Lu(v,e);let _=A.getLogichValue(v.dialogue,e)||"";return d===0?(s=A.getLogichValue(v.glueEnabled,e)||false,_):(typeof _=="object"&&"text"in _&&(_=`${_.character}: ${_.text}`),s===false&&o&&(_=`
100
+ `;return g.textSource=y.concat(g.textSource),g.initialVarsToRemove.push(S),f()}}return p.forEach(d=>{let S=d.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);S?.[1]&&(d.message=`The function '${S[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:p}}return {issues:p}}h.getErrors=e;function t(p,f){return Bp(p).filter(({tokens:g})=>!f.some(({validation:m})=>qp(g,m)))}h.getUnknownHashtagCommands=t;function r(p,f){let g=f.filter(b=>b.validation.type==="zod");if(g.length===0)return [];let m=[];for(let b of Bp(p)){if(f.some(({validation:d})=>qp(b.tokens,d)))continue;let C;for(let d of g)for(let S of Fu(d.validation.schema)){let{score:y,hasDiscriminant:w}=D1(b.tokens,S);w&&(!C||y>C.score)&&(C={command:d,branch:S,score:y});}if(!C||C.score<A1)continue;let v=O1(P1(C.branch));if(!v(b.tokens))for(let d of Iu(v.errors??[]))m.push({line:b.line,command:b.command,handlerName:C.command.name,instancePath:d.instancePath||"(root)",element:x1(d,b.tokens),message:T1(d),score:C.score});}return m}h.getLikelyUnknownHashtagCommandSchemaIssues=r;function i(p,f){let g=new Set;for(let d of p.matchAll(S1))d[1]&&g.add(d[1]);let m=new Set(f),b=new Set,C=p.split(/\r?\n/),v=[];for(let d=0;d<C.length;d++){let S=(C[d]??"").replace(/\/\/.*$/,"");for(let y of S.matchAll(/->[ \t]+(\w[\w.]*)/g)){let w=y[1];if(!w)continue;let E=w.split(".")[0]??w;_1.has(E)||g.has(E)||m.has(w)||m.has(w.replaceAll(".",w1))||m.has(E)||b.has(w)||(b.add(w),v.push({line:d+1,target:w}));}}return v}h.getUnknownDivertTargets=i;function a(p){return new Mp.default({strict:false,allErrors:true}).compile(p)}h.getSchemaValidator=a;function s(p,f){let g=typeof f=="function"?f:a(f);return g(p)?[]:$1(g.errors??[],p,g.schema)}h.validateAgainstJsonSchema=s;function o(p,f){let g=new Set,m=[];for(let d of f){let S=u(d);S!==void 0?m.push(S):g.add(String(d));}m.sort((d,S)=>S-d);let b=[],C=p.length;for(let d=p.length-1;d>=0;d--)g.has(p[d])&&(b.push({key:p[d],sectionTokens:p.slice(d+1,C)}),C=d);b.reverse();let v=[];for(let d of m)d<0||d>=C||(v.push({key:d,sectionTokens:p.slice(d,C)}),C=d-1);return v.reverse(),[...v,...b]}h.extractKeyedSections=o;function u(p){return typeof p=="number"?Number.isInteger(p)&&p>=0?p:void 0:/^\d+$/.test(p)?Number(p):void 0}function l(p,f){let g=o(p,Object.keys(f)),m=[];for(let{key:b,sectionTokens:C}of g){let v;try{v=Nt.convertListStringToObj(C);}catch(S){m.push({key:b,instancePath:"(root)",element:String(b),message:`could not parse "${b}" section into key/value pairs: ${S instanceof Error?S.message:String(S)}`});continue}let d=s(v,f[b]);m.push(...d.map(S=>({...S,key:b})));}return m}h.validateKeyedJsonSchemas=l;function c(p,f){let g=[];for(let m of Bp(p)){let b=f.find(({validation:v})=>qp(m.tokens,v));if(!b?.keySchemas)continue;let C=l(m.tokens,b.keySchemas);g.push(...C.map(v=>({...v,line:m.line,command:m.command})));}return g}h.getHashtagKeySchemaIssues=c;})(Jp||={});var zp=Zr(Ar());function xb(n){if(!n||n.length===0)return;let e=new Set;for(let t of n){let r=typeof t=="string"?t:t?.id;typeof r=="string"&&r.length>0&&e.add(r);}return e.size>0?e:void 0}function ju(n,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:n},{json:r,issues:i}=Jp.compile(n,t);if(i.forEach(({message:s,type:o})=>{o===zp.ErrorType.Error?K.error(`Ink compilation error: ${s}`):o===zp.ErrorType.Warning?K.warn(`Ink compilation warning: ${s}`):K.info(`Ink compilation info: ${s}`);}),!r){K.error("No JSON generated from ink file");return}let a;try{a=ti.parse(r);}catch{K.error("Error parsing ink file");return}return t.enums=a.listDefs||{},il.inkToJson(a,{...t,characterIds:xb(e.characters)})}var ze;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(ze||={});var A=class Y{static init(e){e.loadAssets&&(Y._loadAssets=e.loadAssets),e.soundOperation&&(Y._soundOperation=e.soundOperation),e.imageOperation&&(Y._imageOperation=e.imageOperation),e.videoOperation&&(Y._videoOperation=e.videoOperation),e.imageContainerOperation&&(Y._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(Y._textOperation=e.textOperation),e.canvasElementOperation&&(Y._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(Y._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(Y._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(Y._narrationOperation=e.narrationOperation),e.effectOperation&&(Y._effectOperation=e.effectOperation),e.animateOperation&&(Y._animateOperation=e.animateOperation),e.canvasOperation&&(Y._canvasOperation=e.canvasOperation),e.getLogichValue&&(Y._getLogichValue=e.getLogichValue),e.getConditionalStep&&(Y._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return Y._loadAssets}static _soundOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return Y._soundOperation}static _imageOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return Y._imageOperation}static _videoOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return Y._videoOperation}static _imageContainerOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return Y._imageContainerOperation}static _textOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return Y._textOperation}static _canvasElementOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return Y._canvasElementOperation}static _setStorageValue=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return Y._setStorageValue}static _setInitialStorageValue=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return Y._setInitialStorageValue}static _narrationOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return Y._narrationOperation}static _effectOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return Y._effectOperation}static _animateOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return Y._animateOperation}static _canvasOperation=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return Y._canvasOperation}static _getLogichValue=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return Y._getLogichValue}static _getConditionalStep=()=>{throw ze.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return Y._getConditionalStep}};var bs;(n=>{n.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(l,c){e.unshift({fn:l,opts:c});}n.add=t;function r(l){let c=e.findIndex(h=>h.fn===l);c!==-1&&e.splice(c,1);}n.remove=r;function i(){return e.map(l=>l.opts)}n.info=i;function a(l,c){let h=e.filter(p=>(p.opts.type??"after-translation")===c.type);for(let p of h)l=u(l,p.fn,p.opts.validation);return l}n.replace=a;function s(l){let c=e.filter(h=>h.opts.i18nInterpolation);for(let h of c)l=o(l,h.fn,h.opts);return l}n.runI18nPreStep=s;function o(l,c,h){let{validation:p}=h,f=new RegExp(n.options.replaceRegex.source,"g"),g=[...l.matchAll(f)],m=new Set,b=[];for(let C of g)m.has(C[1])||(m.add(C[1]),b.push(C[1]));for(let C of b){if(p==="characterId"){if(!characters.RegisteredCharacters.has(C))continue}else if(p!=="all"){if(p instanceof RegExp){if(!p.test(C))continue}else if(p instanceof zod.ZodType&&!p.safeParse(C).success)continue}c(C)!==void 0&&(l.includes(`{{[${C}]}}`)||(l=l.replaceAll(`[${C}]`,`{{[${C}]}}`)));}return l}function u(l,c,h){let p=new RegExp(n.options.replaceRegex.source,"g"),f=[...l.matchAll(p)],g=new Set,m=[];for(let b of f)g.has(b[1])||(g.add(b[1]),m.push(b[1]));for(let b of m){if(h==="characterId"){if(!characters.RegisteredCharacters.has(b))continue}else if(h!=="all"){if(h instanceof RegExp){if(!h.test(b))continue}else if(h instanceof zod.ZodType&&!h.safeParse(b).success)continue}let C=c(b);C!==void 0&&(l=l.replaceAll(`[${b}]`,C));}return l}})(bs||={});function L1(n,e={}){let t="";return n.values.forEach(r=>{if(typeof r=="string")t+=r;else {let i=A.getLogichValue(r,e);t+=`${i}`;}}),t}var Fb;(n=>{let e=u=>u;function t(u){return Array.isArray(u)?u.map(l=>r(`${l}`)):r(`${u}`)}n.t=t;function r(u){let l=u;return n.beforeToTranslate&&(l=(0, n.beforeToTranslate)(l)),l=bs.replace(l,{type:"before-translation"}),l=e(l),n.afterToTranslate&&(l=(0, n.afterToTranslate)(l)),l=bs.replace(l,{type:"after-translation"}),l}n.translate=r;function i(u){e=u;}n.setTranslate=i;function a(u,l,c){let{defaultValue:h="empty_string"}=c;typeof l=="string"&&(l=[l]),Array.isArray(l)&&l.forEach(p=>{let f=p;if(n.beforeToTranslate&&(f=(0, n.beforeToTranslate)(f)),h==="empty_string")u[f]===void 0&&(u[f]="");else if(h==="copy_key"){let g=p;n.beforeToTranslate&&(g=(0, n.beforeToTranslate)(g));let m=bs.runI18nPreStep(g);m=bs.replace(m,{type:"before-translation"}),u[f]=m;}});}function s(u,l=[]){if(typeof u=="object"&&u&&"type"in u)if(u.type==="ifelse")u.then&&s(u.then,l),u.else&&s(u.else,l);else if(u.type==="stepswitch"){if(u.elements)if(Array.isArray(u.elements))u.elements.forEach(c=>{s(c,l);});else if(u.elements.type==="ifelse"){let c=[];s(u.elements,c),c.forEach(h=>{l.push(...h);});}else if(u.elements.type==="stepswitch"){let c=[];s(u.elements,c),c.forEach(h=>{l.push(...h);});}else s(u.elements,l);}else u.type==="resulttocombine"?(u.firstItem&&s(u.firstItem,l),u.secondConditionalItem&&u.secondConditionalItem.forEach(c=>{s(c,l);})):l.push(u);else u&&l.push(u);return l}async function o(u,l={},c={}){let{defaultValue:h="copy_key",operationStringConvert:p}=c,f=u.map(async g=>{if(g.choices){let m=[];Array.isArray(g.choices)?m=[g.choices]:m=s(g.choices),m.forEach(b=>{b.forEach(C=>{if("type"in C){let v=[];C.type==="ifelse"||C.type==="stepswitch"?s(C,v):v=[C],v.map(d=>s(d.text)).forEach(d=>{Array.isArray(d)&&d.forEach(S=>{Array.isArray(S)?S.forEach(y=>{typeof y=="string"?a(l,y,{defaultValue:h}):s(y).forEach(w=>{Array.isArray(w)?w.forEach(E=>{typeof E=="string"&&a(l,E,{defaultValue:h});}):typeof w=="string"&&a(l,w,{defaultValue:h});});}):typeof S=="string"&&a(l,S,{defaultValue:h});});});}});});}if(g.dialogue){let m=[];Array.isArray(g.dialogue)?m=[g.dialogue]:m=s(g.dialogue),m.forEach(b=>{if(typeof b=="string")a(l,b,{defaultValue:h});else if("text"in b){let C=s(b.text);typeof C=="string"&&(C=[C]),C.forEach(v=>{typeof v=="string"?a(l,v,{defaultValue:h}):s(v).forEach(d=>{typeof d=="string"?a(l,d,{defaultValue:h}):Array.isArray(d)&&d.forEach(S=>{typeof S=="string"?a(l,S,{defaultValue:h}):s(S).forEach(y=>{typeof y=="string"&&a(l,y,{defaultValue:h});});});});});}});}if(g.operations)for(let m of g.operations){if(m.type==="operationtoconvert"&&p){let b=L1(m),C=await p(b,g,{});if(!C)return;m=C;}m.type==="text"&&m.operationType==="show"&&a(l,m.text,{defaultValue:h});}g.conditionalStep&&s(g.conditionalStep).forEach(m=>{Array.isArray(m)?o(m,l,c):o([m],l,c);});});return await Promise.all(f),l}n.generateJsonTranslation=o;})(Fb||={});var St=Fb;async function Ib(n){let e=A.getLogichValue(n,{});if(e)switch(e.type){case "assets":switch(e.operationType){case "load":await canvas.Assets.load(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoad(e.aliases);break}break;case "bundle":switch(e.operationType){case "load":await canvas.Assets.loadBundle(e.aliases);break;case "lazyload":canvas.Assets.backgroundLoadBundle(e.aliases);break}break}}var Q;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Q||={});async function qu(n,e,t){let{alias:r}=e,{props:i,priority:a}=t;switch(t.type){case "fade":await canvas.transitions.showWithFade(r,n,i,a);break;case "dissolve":await canvas.transitions.showWithDissolve(r,n,i,a);break;case "movein":case "moveout":await canvas.transitions.moveIn(r,n,i,a);break;case "zoomin":case "zoomout":await canvas.transitions.zoomIn(r,n,i,a);break;case "pushin":case "pushout":await canvas.transitions.pushIn(r,n,i,a);break;case "wipein":case "wipeout":await canvas.transitions.wipeIn(r,n,i,a);break;case "irisin":case "irisout":await canvas.transitions.irisIn(r,n,i,a);break;case "splitin":case "splitout":await canvas.transitions.splitIn(r,n,i,a);break;case "blurin":case "blurout":await canvas.transitions.blurIn(r,n,i,a);break;case "pixelatein":case "pixelateout":await canvas.transitions.pixelateIn(r,n,i,a);break;case "flashin":case "flashout":await canvas.transitions.flashIn(r,n,i,a);break;case "glitchin":case "glitchout":await canvas.transitions.glitchIn(r,n,i,a);break;case "twistin":case "twistout":await canvas.transitions.twistIn(r,n,i,a);break;case "warpin":case "warpout":await canvas.transitions.warpIn(r,n,i,a);break;case "ripplein":case "rippleout":await canvas.transitions.rippleIn(r,n,i,a);break;case "noisedissolvein":case "noisedissolveout":await canvas.transitions.noiseDissolveIn(r,n,i,a);break;case "tvin":case "tvout":await canvas.transitions.tvIn(r,n,i,a);break;case "pinchin":case "pinchout":await canvas.transitions.pinchIn(r,n,i,a);break}}function Cs(n){let{transition:e,alias:t}=n;if(!e){canvas.canvas.remove(t);return}let{props:r,priority:i}=e;switch(e.type){case "fade":canvas.transitions.removeWithFade(t,r,i);break;case "dissolve":canvas.transitions.removeWithDissolve(t,r,i);break;case "movein":case "moveout":canvas.transitions.moveOut(t,r,i);break;case "zoomin":case "zoomout":canvas.transitions.zoomOut(t,r,i);break;case "pushin":case "pushout":canvas.transitions.pushOut(t,r,i);break;case "wipein":case "wipeout":canvas.transitions.wipeOut(t,r,i);break;case "irisin":case "irisout":canvas.transitions.irisOut(t,r,i);break;case "splitin":case "splitout":canvas.transitions.splitOut(t,r,i);break;case "blurin":case "blurout":canvas.transitions.blurOut(t,r,i);break;case "pixelatein":case "pixelateout":canvas.transitions.pixelateOut(t,r,i);break;case "flashin":case "flashout":canvas.transitions.flashOut(t,r,i);break;case "glitchin":case "glitchout":canvas.transitions.glitchOut(t,r,i);break;case "twistin":case "twistout":canvas.transitions.twistOut(t,r,i);break;case "warpin":case "warpout":canvas.transitions.warpOut(t,r,i);break;case "ripplein":case "rippleout":canvas.transitions.rippleOut(t,r,i);break;case "noisedissolvein":case "noisedissolveout":canvas.transitions.noiseDissolveOut(t,r,i);break;case "tvin":case "tvout":canvas.transitions.tvOut(t,r,i);break;case "pinchin":case "pinchout":canvas.transitions.pinchOut(t,r,i);break}}async function kb(n){switch(n.operationType){case "show":if(n.transition){let e=new canvas.ImageSprite(n.props,n.url||n.alias);await qu(e,n,n.transition);}else await canvas.showImage(n.alias,n.url,n.props);break;case "edit":{let e=canvas.canvas.find(n.alias);e?n.props&&await e.setMemory({...e.memory,...n.props}):Q.error(`Image with alias ${n.alias} not found.`);break}case "remove":Cs(n);break}}async function Vb(n){switch(n.operationType){case "show":if(n.transition){let e=new canvas.VideoSprite(n.props,n.url||n.alias);await qu(e,n,n.transition);}else await canvas.showVideo(n.alias,n.url,n.props);break;case "edit":{let e=canvas.canvas.find(n.alias);e?n.props&&await e.setMemory({...e.memory,...n.props}):Q.error(`Video with alias ${n.alias} not found.`);break}case "remove":Cs(n);break;case "pause":case "resume":{let e=canvas.canvas.find(n.alias);e?e.paused=n.operationType==="pause":Q.error(`Video with alias ${n.alias} not found.`);break}}}async function Rb(n){switch(n.operationType){case "show":if(n.transition){let e=new canvas.ImageContainer(n.props,n.urls);await qu(e,n,n.transition);}else await canvas.showImageContainer(n.alias,n.urls,n.props);break;case "edit":{let e=canvas.canvas.find(n.alias);e?n.props&&await e.setMemory({...e.memory,...n.props}):Q.error(`ImageContainer with alias ${n.alias} not found.`);break}case "remove":Cs(n);break}}async function jb(n){switch(n.operationType){case "show":if(n.props=n.props||{},n.props.text=St.t(n.text),n.transition){let e=new canvas.Text(n.props);await qu(e,n,n.transition);}else canvas.showText(n.alias,n.text,n.props);break;case "edit":{let e=canvas.canvas.find(n.alias);e?n.props&&await e.setMemory({...e.memory,...n.props}):Q.error(`Text with alias ${n.alias} not found.`);break}case "remove":Cs(n);break}}async function $b(n){switch(n.operationType){case "edit":try{let e=canvas.canvas.find(n.alias);e?n.props&&e.setMemory({...e.memory,...n.props}):Q.error(`Canvas Element with alias ${n.alias} not found.`);}catch(e){Q.error(`There was an error while trying to edit the canvas element with alias ${n.alias}.`,e);}break;case "remove":Cs(n);break}}function Lb(n){n.operationType==="clear"&&canvas.canvas.removeAll();}async function qb(n){switch(n.type){case "shake":await canvas.effects.shakeEffect(n.alias,n.props,n.priority);break;case "bounce":await canvas.effects.bounceEffect(n.alias,n.props,n.priority);break;case "pulse":await canvas.effects.pulseEffect(n.alias,n.props,n.priority);break;case "hop":await canvas.effects.hopEffect(n.alias,n.props,n.priority);break;case "wiggle":await canvas.effects.wiggleEffect(n.alias,n.props,n.priority);break;case "nod":await canvas.effects.nodEffect(n.alias,n.props,n.priority);break;case "sway":await canvas.effects.swayEffect(n.alias,n.props,n.priority);break;case "punch":await canvas.effects.punchEffect(n.alias,n.props,n.priority);break;case "glitch":await canvas.effects.glitchEffect(n.alias,n.props,n.priority);break;case "chromatic-aberration":await canvas.effects.chromaticAberrationEffect(n.alias,n.props,n.priority);break;case "shockwave":await canvas.effects.shockwaveEffect(n.alias,n.props,n.priority);break;case "radial-blur":await canvas.effects.radialBlurEffect(n.alias,n.props,n.priority);break;case "blur-pulse":await canvas.effects.blurPulseEffect(n.alias,n.props,n.priority);break;case "vignette-pulse":await canvas.effects.vignettePulseEffect(n.alias,n.props,n.priority);break;case "desaturate":await canvas.effects.desaturateEffect(n.alias,n.props,n.priority);break;case "glow-pulse":await canvas.effects.glowPulseEffect(n.alias,n.props,n.priority);break}}function Bb(n){switch(n.type){case "animate":canvas.canvas.animate(n.alias,n.keyframes,n.options,n.priority);break;case "animate-sequence":canvas.canvas.animate(n.alias,n.sequence,n.options,n.priority);break}}function Wb(n){switch(n.type){case "input":narration.narration.input.request({type:n.valueType},n.defaultValue);break;case "dialogue":narration.narration.dialogue=void 0;break}}function Mb(n){switch(n.operationType){case "play":n.url?sound.sound.play(n.alias,n.url,n.props):sound.sound.play(n.alias,n.props);break;case "stop":switch(n.type){case "sound":sound.sound.stop(n.alias);break;case "all":sound.sound.stopAll();break}break;case "pause":switch(n.type){case "sound":sound.sound.pause(n.alias);break;case "channel":sound.sound.channels.find(n.alias).pauseAll();break;case "all":sound.sound.pauseAll();break}break;case "resume":switch(n.type){case "sound":sound.sound.resume(n.alias);break;case "channel":sound.sound.channels.find(n.alias).resumeAll();break;case "all":sound.sound.resumeAll();break}break;case "edit":{let e=sound.sound.find(n.alias);if(!e)break;for(let[t,r]of Object.entries(n.props))switch(t){case "volume":e.volume.value=r;break;case "playbackRate":e.playbackRate=r;break;case "mute":e.mute=r;break;case "loop":e.loop=r;break;case "paused":e.paused=r;break}break}}}var Hp="___param___",K1=class Z{static init(e){e.loadAssets&&(Z._loadAssets=e.loadAssets),e.soundOperation&&(Z._soundOperation=e.soundOperation),e.imageOperation&&(Z._imageOperation=e.imageOperation),e.videoOperation&&(Z._videoOperation=e.videoOperation),e.imageContainerOperation&&(Z._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(Z._textOperation=e.textOperation),e.canvasElementOperation&&(Z._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(Z._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(Z._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(Z._narrationOperation=e.narrationOperation),e.effectOperation&&(Z._effectOperation=e.effectOperation),e.animateOperation&&(Z._animateOperation=e.animateOperation),e.canvasOperation&&(Z._canvasOperation=e.canvasOperation),e.getLogichValue&&(Z._getLogichValue=e.getLogichValue),e.getConditionalStep&&(Z._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return Z._loadAssets}static _soundOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return Z._soundOperation}static _imageOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return Z._imageOperation}static _videoOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return Z._videoOperation}static _imageContainerOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return Z._imageContainerOperation}static _textOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return Z._textOperation}static _canvasElementOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return Z._canvasElementOperation}static _setStorageValue=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return Z._setStorageValue}static _setInitialStorageValue=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return Z._setInitialStorageValue}static _narrationOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return Z._narrationOperation}static _effectOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return Z._effectOperation}static _animateOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return Z._animateOperation}static _canvasOperation=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return Z._canvasOperation}static _getLogichValue=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return Z._getLogichValue}static _getConditionalStep=()=>{throw Q.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return Z._getConditionalStep}};function X1(n,e){if(e&&typeof e=="object"&&typeof n.functionName=="string"&&n.functionName in e){let t=e[n.functionName];if(typeof t=="function"){let r=n.args.map(i=>K1.getLogichValue(i,e));return t(...r)}else Q.warn(`getLogichValue function ${n.functionName} not found in props`);}}function Gb(n,e){let t=A.getLogichValue(n,e);return t&&typeof t=="object"&&"type"in t?A.getLogichValue(t,e):t}function Jb(n,e={}){let t=Gb(n.value,e);switch(n.storageType){case "flagStorage":storage.storage.flags.set(n.key,n.value);break;case "storage":storage.storage.set(n.key,t);break;case "tempstorage":storage.storage.temp.set(n.key,t);break;case "params":{let r=storage.storage.get(`${Hp}${narration.narration.labels.opened.length-1}`)||[];r.length>n.key&&(r[n.key]=t),storage.storage.temp.set(`${Hp}${narration.narration.labels.opened.length-1}`,r);break}}}function zb(n,e={}){let t=Gb(n.value,e);switch(n.storageType){case "storage":case "tempstorage":storage.storage.default={[n.key]:t};break}}function Hb(n,e={}){let t=Ub(n,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return Z1(t,e);case "arithmetic":case "arithmeticsingle":return Y1(t,e);case "compare":case "union":return Q1(t,e);case "function":return X1(t,e)}return t}function Y1(n,e){let t=A.getLogichValue(n.leftValue,e);switch(n.type){case "arithmetic":{let r=A.getLogichValue(n.rightValue,e);switch(n.operator){case "*":return t*r;case "/":return t/r;case "+":return typeof t=="string"||typeof r=="string"?`${t}${r}`:Array.isArray(t)&&Array.isArray(r)?[...t,...r]:Array.isArray(t)?[...t,r]:Array.isArray(r)?[t,...r]:t+r;case "-":if(Array.isArray(t)&&Array.isArray(r))return t.filter(i=>!r.includes(i));if(Array.isArray(t))return t.filter(i=>i!==r);if(Array.isArray(r)){Q.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-r;case "%":return t%r;case "POW":return t**r;case "RANDOM":return narration.narration.getRandomNumber(t,r);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(r))return t.filter(i=>r.includes(i));Q.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:Q.warn("getValueFromArithmeticOperations unknown operator",n);return}}case "arithmeticsingle":switch(n.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function Z1(n,e){if(n&&typeof n=="object"&&"type"in n&&n.type==="value"&&n.storageOperationType==="get")switch(n.storageType){case "storage":case "tempstorage":return n.key==="_input_value_"?narration.narration.input.value:storage.storage.get(n.key);case "flagStorage":return storage.storage.flags.get(n.key);case "label":return narration.narration.queries.timesLabelOpened(n.label);case "choice":return narration.narration.queries.timesChoiceMade(n.index);case "logic":return A.getLogichValue(n.operation,e);case "params":{let t=storage.storage.get(`${Hp}${narration.narration.labels.opened.length-1}`)||[];if(t&&t.length>n.key)return t[n.key];Q.warn("getValue params not found");return}}return n}function Q1(n,e){if(!n)return false;if(typeof n!="object"||!("type"in n))return !!n;switch(n.type){case "compare":{let t=A.getLogichValue(n.leftValue,e),r=A.getLogichValue(n.rightValue,e);switch(n.operator){case "==":return Array.isArray(t)&&Array.isArray(r)?t.length===r.length&&t.every(i=>r.includes(i)):t===r;case "!=":return Array.isArray(t)&&Array.isArray(r)?t.length!==r.length||!t.every(i=>r.includes(i)):t!==r;case "<":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)<0:Array.isArray(t)&&Array.isArray(r)?t.length<r.length:t<r;case "<=":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)<=0:Array.isArray(t)&&Array.isArray(r)?t.length<=r.length:t<=r;case ">":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)>0:Array.isArray(t)&&Array.isArray(r)?t.length>r.length:t>r;case ">=":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)>=0:Array.isArray(t)&&Array.isArray(r)?t.length>=r.length:t>=r;case "CONTAINS":return Array.isArray(t)&&Array.isArray(r)?r.every(i=>t.includes(i)):Array.isArray(t)?t.includes(r):t.toString().includes(r.toString())}break}case "value":{let t=A.getLogichValue(n,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return eN(n,e)}return !!n}function eN(n,e){if(n.unionType==="not"){let r=Hb(n.condition,e);return Array.isArray(r)?r.length===0:r&&typeof r=="object"?Object.keys(r).length===0:!r}let t=r=>A.getLogichValue(r,e)||false;return n.unionType==="and"?n.conditions.every(t):n.conditions.some(t)}function tN(n,e){return Math.floor(Math.random()*(e-n+1)+n)}function Ub(n,e={}){if(Array.isArray(n)||!n)return n;if(n&&typeof n=="object"&&"type"in n)switch(n.type){case "resulttocombine":return nN(n,e);case "ifelse":return A.getLogichValue(n.condition,e)?A.getLogichValue(n.then,e):A.getLogichValue(n.else,e);case "stepswitch":{let t=A.getLogichValue(n.elements,e)||[];if(t.length===0){Q.error("getValueFromConditionalStatements elements.length === 0");return}switch(n.choiceType){case "random":{let r=tN(0,t.length-1);return A.getLogichValue(t[r],e)}case "loop":{let r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(n.nestedId)-1;return r>t.length-1?(r=r%t.length,A.getLogichValue(t[r],e)):A.getLogichValue(t[r],e)}case "sequential":{let r,i=narration.NarrationManagerStatic.getCurrentStepTimesCounter(n.nestedId)-1;return n.end==="lastItem"&&(r=A.getLogichValue(t[t.length-1],e)),i>t.length-1?r:A.getLogichValue(t[i],e)}case "sequentialrandom":{let r=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:n.nestedId,onceOnly:true});if(r===void 0&&n.end==="lastItem"){let i=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(n.nestedId);if(!i?.usedRandomNumbers){Q.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=i.usedRandomNumbers[`0-${t.length-1}`];return A.getLogichValue(t[a[a.length-1]],e)}if(r===void 0){Q.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return A.getLogichValue(t[r],e)}}}}return n}function Bu(n,e={}){if(n.conditionalStep){let t=pixiVn.createExportableElement(A.getLogichValue(n.conditionalStep,e));if(t?.glueEnabled===void 0&&delete t?.glueEnabled,t?.goNextStep===void 0&&delete t?.goNextStep,t?.end===void 0&&delete t?.end,t?.choices===void 0&&delete t?.choices,t?.dialogue===void 0&&delete t?.dialogue,t?.labelToOpen===void 0&&delete t?.labelToOpen,t?.operations===void 0&&delete t?.operations,t){let r={...n,conditionalStep:void 0,...t};return Bu(r,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return n}function nN(n,e){let t=n.firstItem,r=(n.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>A.getLogichValue(s,e)):[A.getLogichValue(a,e)]),i=t?[t,...r]:r;if(i.length===0){Q.warn("combinateResult toCheck.length === 0");return}if(typeof i[0]=="string")return St.t(i);if(typeof i[0]=="object"){let a=i,s,o=false,u=a.map((v,d)=>{v=Bu(v,e);let S=A.getLogichValue(v.dialogue,e)||"";return d===0?(s=A.getLogichValue(v.glueEnabled,e)||false,S):(typeof S=="object"&&"text"in S&&(S=`${S.character}: ${S.text}`),s===false&&o&&(S=`
101
101
 
102
- ${_}`),_&&(o=true),s=A.getLogichValue(v.glueEnabled,e)||false,_)}),l=A.getLogichValue(u[0],e),c=typeof l=="object"&&"character"in l?l.character:void 0,h=u.flatMap(v=>{let d;v&&typeof v=="object"&&"text"in v?d=v.text:d=v;let _;return Array.isArray(d)?_=d.map(y=>{let E=A.getLogichValue(y,e);return Ct.t(`${E}`)}):_=A.getLogichValue(d,e)||"",Ct.t(_)}),f=a.find(v=>v.end),p=a.find(v=>v.choices),g=false,m=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),g=a[a.length-1].glueEnabled,m=a.reverse().find(v=>!(v.operations&&(!v.dialogue||!v.choices)))?.goNextStep);let C=a.find(v=>v.labelToOpen),b=[];return a.forEach(v=>{v.operations&&(b=[...b,...v.operations]);}),{dialogue:c?{character:c,text:h}:h,end:f?.end,choices:p?.choices,glueEnabled:g,goNextStep:m,labelToOpen:C?.labelToOpen,operations:b}}}var qu;(n=>{let e=new Set;function t(a){e.add(a);}n.add=t;function r(){e.clear();}n.clear=r;function i(a,s={}){let o=c=>J0(c,s)??void 0,u=z0(a,s);if(e.size===0)return o(u);let l=o;for(let c of e){let h=l;l=f=>c(f,h)??void 0;}return l(u)}n.getLogichValue=i;})(qu||={});var mN=Object.create,Y0=Object.defineProperty,gN=Object.getOwnPropertyDescriptor,yN=Object.getOwnPropertyNames,vN=Object.getPrototypeOf,CN=Object.prototype.hasOwnProperty,U0=(n=>typeof Dn<"u"?Dn:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof Dn<"u"?Dn:e)[t]}):n)(function(n){if(typeof Dn<"u")return Dn.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),Z0=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),bN=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of yN(e))!CN.call(n,i)&&i!==t&&Y0(n,i,{get:()=>e[i],enumerable:!(r=gN(e,i))||r.enumerable});return n},_N=(n,e,t)=>(t=n!=null?mN(vN(n)):{},bN(Y0(t,"default",{value:n,enumerable:true}),n)),SN=Z0((n,e)=>{(function(t,r){typeof n=="object"?e.exports=n=r():typeof define=="function"&&define.amd?define([],r):t.CryptoJS=r();})(n,function(){var t=t||(function(r,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 U0=="function")try{a=U0("crypto");}catch{}var s=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||(function(){function v(){}return function(d){var _;return v.prototype=d,_=new v,v.prototype=null,_}})(),u={},l=u.lib={},c=l.Base=(function(){return {extend:function(v){var d=o(this);return v&&d.mixIn(v),(!d.hasOwnProperty("init")||this.init===d.init)&&(d.init=function(){d.$super.init.apply(this,arguments);}),d.init.prototype=d,d.$super=this,d},create:function(){var v=this.extend();return v.init.apply(v,arguments),v},init:function(){},mixIn:function(v){for(var d in v)v.hasOwnProperty(d)&&(this[d]=v[d]);v.hasOwnProperty("toString")&&(this.toString=v.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),h=l.WordArray=c.extend({init:function(v,d){v=this.words=v||[],d!=i?this.sigBytes=d:this.sigBytes=v.length*4;},toString:function(v){return (v||p).stringify(this)},concat:function(v){var d=this.words,_=v.words,y=this.sigBytes,E=v.sigBytes;if(this.clamp(),y%4)for(var w=0;w<E;w++){var P=_[w>>>2]>>>24-w%4*8&255;d[y+w>>>2]|=P<<24-(y+w)%4*8;}else for(var x=0;x<E;x+=4)d[y+x>>>2]=_[x>>>2];return this.sigBytes+=E,this},clamp:function(){var v=this.words,d=this.sigBytes;v[d>>>2]&=4294967295<<32-d%4*8,v.length=r.ceil(d/4);},clone:function(){var v=c.clone.call(this);return v.words=this.words.slice(0),v},random:function(v){for(var d=[],_=0;_<v;_+=4)d.push(s());return new h.init(d,v)}}),f=u.enc={},p=f.Hex={stringify:function(v){for(var d=v.words,_=v.sigBytes,y=[],E=0;E<_;E++){var w=d[E>>>2]>>>24-E%4*8&255;y.push((w>>>4).toString(16)),y.push((w&15).toString(16));}return y.join("")},parse:function(v){for(var d=v.length,_=[],y=0;y<d;y+=2)_[y>>>3]|=parseInt(v.substr(y,2),16)<<24-y%8*4;return new h.init(_,d/2)}},g=f.Latin1={stringify:function(v){for(var d=v.words,_=v.sigBytes,y=[],E=0;E<_;E++){var w=d[E>>>2]>>>24-E%4*8&255;y.push(String.fromCharCode(w));}return y.join("")},parse:function(v){for(var d=v.length,_=[],y=0;y<d;y++)_[y>>>2]|=(v.charCodeAt(y)&255)<<24-y%4*8;return new h.init(_,d)}},m=f.Utf8={stringify:function(v){try{return decodeURIComponent(escape(g.stringify(v)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(v){return g.parse(unescape(encodeURIComponent(v)))}},C=l.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new h.init,this._nDataBytes=0;},_append:function(v){typeof v=="string"&&(v=m.parse(v)),this._data.concat(v),this._nDataBytes+=v.sigBytes;},_process:function(v){var d,_=this._data,y=_.words,E=_.sigBytes,w=this.blockSize,P=w*4,x=E/P;v?x=r.ceil(x):x=r.max((x|0)-this._minBufferSize,0);var H=x*w,be=r.min(H*4,E);if(H){for(var Jt=0;Jt<H;Jt+=w)this._doProcessBlock(y,Jt);d=y.splice(0,H),_.sigBytes-=be;}return new h.init(d,be)},clone:function(){var v=c.clone.call(this);return v._data=this._data.clone(),v},_minBufferSize:0});l.Hasher=C.extend({cfg:c.extend(),init:function(v){this.cfg=this.cfg.extend(v),this.reset();},reset:function(){C.reset.call(this),this._doReset();},update:function(v){return this._append(v),this._process(),this},finalize:function(v){v&&this._append(v);var d=this._doFinalize();return d},blockSize:16,_createHelper:function(v){return function(d,_){return new v.init(_).finalize(d)}},_createHmacHelper:function(v){return function(d,_){return new b.HMAC.init(v,_).finalize(d)}}});var b=u.algo={};return u})(Math);return t});}),EN=Z0((n,e)=>{(function(t,r){typeof n=="object"?e.exports=n=r(SN()):typeof define=="function"&&define.amd?define(["./core"],r):r(t.CryptoJS);})(n,function(t){return (function(){var r=t,i=r.lib,a=i.WordArray,s=i.Hasher,o=r.algo,u=[],l=o.SHA1=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(c,h){for(var f=this._hash.words,p=f[0],g=f[1],m=f[2],C=f[3],b=f[4],v=0;v<80;v++){if(v<16)u[v]=c[h+v]|0;else {var d=u[v-3]^u[v-8]^u[v-14]^u[v-16];u[v]=d<<1|d>>>31;}var _=(p<<5|p>>>27)+b+u[v];v<20?_+=(g&m|~g&C)+1518500249:v<40?_+=(g^m^C)+1859775393:v<60?_+=(g&m|g&C|m&C)-1894007588:_+=(g^m^C)-899497514,b=C,C=m,m=g<<30|g>>>2,g=p,p=_;}f[0]=f[0]+p|0,f[1]=f[1]+g|0,f[2]=f[2]+m|0,f[3]=f[3]+C|0,f[4]=f[4]+b|0;},_doFinalize:function(){var c=this._data,h=c.words,f=this._nDataBytes*8,p=c.sigBytes*8;return h[p>>>5]|=128<<24-p%32,h[(p+64>>>9<<4)+14]=Math.floor(f/4294967296),h[(p+64>>>9<<4)+15]=f,c.sigBytes=h.length*4,this._process(),this._hash},clone:function(){var c=s.clone.call(this);return c._hash=this._hash.clone(),c}});r.SHA1=s._createHelper(l),r.HmacSHA1=s._createHmacHelper(l);})(),t.SHA1});}),K0="___param___",Ce;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Ce||={});var wN=class Q{static init(e){e.loadAssets&&(Q._loadAssets=e.loadAssets),e.soundOperation&&(Q._soundOperation=e.soundOperation),e.imageOperation&&(Q._imageOperation=e.imageOperation),e.videoOperation&&(Q._videoOperation=e.videoOperation),e.imageContainerOperation&&(Q._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(Q._textOperation=e.textOperation),e.canvasElementOperation&&(Q._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(Q._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(Q._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(Q._narrationOperation=e.narrationOperation),e.effectOperation&&(Q._effectOperation=e.effectOperation),e.animateOperation&&(Q._animateOperation=e.animateOperation),e.canvasOperation&&(Q._canvasOperation=e.canvasOperation),e.getLogichValue&&(Q._getLogichValue=e.getLogichValue),e.getConditionalStep&&(Q._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return Q._loadAssets}static _soundOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return Q._soundOperation}static _imageOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return Q._imageOperation}static _videoOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return Q._videoOperation}static _imageContainerOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return Q._imageContainerOperation}static _textOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return Q._textOperation}static _canvasElementOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return Q._canvasElementOperation}static _setStorageValue=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return Q._setStorageValue}static _setInitialStorageValue=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return Q._setInitialStorageValue}static _narrationOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return Q._narrationOperation}static _effectOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return Q._effectOperation}static _animateOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return Q._animateOperation}static _canvasOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return Q._canvasOperation}static _getLogichValue=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return Q._getLogichValue}static _getConditionalStep=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return Q._getConditionalStep}};function DN(n,e){if(e&&typeof e=="object"&&typeof n.functionName=="string"&&n.functionName in e){let t=e[n.functionName];if(typeof t=="function"){let r=n.args.map(i=>wN.getLogichValue(i,e));return t(...r)}else Ce.warn(`getLogichValue function ${n.functionName} not found in props`);}}function AN(n,e={}){let t="";return n.values.forEach(r=>{if(typeof r=="string")t+=r;else {let i=A.getLogichValue(r,e);t+=`${i}`;}}),t}async function Q0(n,e,t){let r=A.getLogichValue(n,e);if(r)switch(r.type){case "sound":A.soundOperation(r);break;case "assets":case "bundle":await A.loadAssets(r);break;case "image":await A.imageOperation(r);break;case "video":await A.videoOperation(r);break;case "imagecontainer":await A.imageContainerOperation(r);break;case "text":await A.textOperation(r);break;case "canvaselement":await A.canvasElementOperation(r);break;case "canvas":A.canvasOperation(r);break;case "value":A.setStorageValue(r,e);break;case "operationtoconvert":if(t){let i=AN(r,e),a=await t(i);a&&await Q0(a,e,t);}break;case "input":case "dialogue":A.narrationOperation(r);break;case "shake":await A.effectOperation(r);break;case "animate":case "animate-sequence":A.animateOperation(r);break;case "function":await DN(r,e);break}}function X0(n){let e=A.getLogichValue(n,{});e&&e.type==="value"&&e.storageOperationType==="set"&&(e.storageType==="storage"||e.storageType==="tempstorage")&&A.setInitialStorageValue(e);}var PN=_N(EN()),ON=class extends narration.LabelAbstract{constructor(n,e,t,r={}){t||(t={}),t.onLoadingLabel=async()=>{for(let i of e){let a;if(typeof i=="function"?a=i():a=i,a=A.getConditionalStep(a),a.operations)try{let s=a.operations.map(o=>A.loadAssets(o));await Promise.all(s);}catch(s){Ce.error("The operation in the onLoadingLabel function of the label has an error:",s);}}},super(n,t),this._steps=e,this.operationStringConvert=r.operationStringConvert,this.skipEmptyDialogs=r.skipEmptyDialogs||false;}_steps;get steps(){return this._steps.map(n=>this.stepConverter(n))}get stepCount(){return this._steps.length}getStepById(n){if(n<0||n>=this._steps.length)return;let e=this._steps[n];return this.stepConverter(e)}operationStringConvert;skipEmptyDialogs=false;getStepSha(n){if(n<0||n>=this.steps.length)return;let e=this._steps[n];return (0, PN.default)(e.toString().toLocaleLowerCase()).toString()}getDialogueText(n,e){let t="";if(Array.isArray(n)){let r=[];n.forEach(i=>{if(typeof i=="string")r.push(i);else if(i&&typeof i=="object"){let a=A.getLogichValue(i,e);a?(a&&!Array.isArray(a)&&typeof a=="object"&&(a=A.getLogichValue(a,e)||""),Array.isArray(a)?r=r.map(s=>`${s}`).concat(a):r.push(`${a}`)):r.push(`${i}`);}else r.push(`${i}`);}),t=r;}else {let r=A.getLogichValue(n,e);r&&!Array.isArray(r)&&typeof r=="object"&&(r=A.getLogichValue(r,e)),r&&Array.isArray(r)?t=r.map(i=>`${i}`):t=`${r}`;}return t}getDialogue(n,e){if(n==null)return;let t=A.getLogichValue(n,e);return t==null?`${t}`:typeof t=="object"&&"character"in t&&"text"in t?{character:t.character,text:Ct.t(this.getDialogueText(t.text,e))}:Ct.t(this.getDialogueText(t,e))}getChoices(n,e){return A.getLogichValue(n,e)?.map(t=>A.getLogichValue(t,e)).filter(t=>t!==void 0)}stepConverter(n){return async e=>{let t=typeof n=="function"?n():n;t=pixiVn.createExportableElement(t),t=A.getConditionalStep(t,e);let r=this.operationStringConvert?f=>this.operationStringConvert(f,t,e):void 0,{operations:i=[]}=t;for(let f of i)await Q0(f,e,r);let{labelToOpen:a=[]}=t,s=this.getChoices(t.choices,e),o=A.getLogichValue(t.glueEnabled,e),u=this.getDialogue(t.dialogue,e),l=[];Array.isArray(a)||(a=[a]),a.forEach(f=>{let p=A.getLogichValue(f,e);p&&l.push(p);});let c=A.getLogichValue(t.goNextStep,e),h=A.getLogichValue(t.end,e);if(s){let f=s.map(p=>{let g="";if(Array.isArray(p.text)){let m=[];p.text.forEach(C=>{if(typeof C=="string")m.push(Ct.t(C));else if(C&&typeof C=="object"){let b=A.getLogichValue(C,e);b&&!Array.isArray(b)&&typeof b=="object"&&(b=A.getLogichValue(b,e)||""),b&&(Array.isArray(b)?m=m.concat(Ct.t(b)):m.push(Ct.t(b)));}}),g=m;}else typeof p.text=="string"&&(g=Ct.t(p.text));return {label:p.label,text:g,props:p.props,type:p.type,oneTime:p.oneTime,onlyHaveNoChoice:p.onlyHaveNoChoice,autoSelect:p.autoSelect}});narration.narration.choices=f;}else narration.narration.choices=void 0;u!==void 0&&(narration.narration.dialogue=u,this.skipEmptyDialogs&&typeof u=="string"&&(u===""||RegExp(/^\s+$/).test(u))&&(c=true)),o?narration.narration.dialogGlue=true:o===false&&(narration.narration.dialogGlue=false);for(let f of l){let p=f.label;typeof p=="object"&&(p=A.getLogichValue(p,e)||"");let g=f.params?.map(m=>A.getLogichValue(m,e));e={...e,...f.props},f.type==="jump"?(narration.narration.labels.opened.length>0&&narration.narration.labels.closeCurrent(),storage.storage.temp.set(`${K0}${narration.narration.labels.opened.length}`,g),await narration.narration.call(p,e)):(storage.storage.temp.set(`${K0}${narration.narration.labels.opened.length}`,g),await narration.narration.call(p,e));}h==="game_end"?(narration.narration.labels.closeAll(),await narration.narration.continue(e,{runNow:true})):h==="label_end"&&narration.narration.labels.closeCurrent(),c&&await narration.narration.continue(e,{runNow:true});}}};async function Hf(n,e={}){if(!Array.isArray(n))if(typeof n=="object"||typeof n=="string")n=[n];else {Ce.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let t=n.map(a=>{if(typeof a=="string")try{return JSON.parse(a)}catch(s){return Ce.error("Error parsing imported Pixi'VN JSON",s),{}}return a}),r=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)s.type==="value"&&(typeof s.value!="object"||!s.value||!("type"in s.value))&&X0(s);return Promise.resolve()});await Promise.all(r);let i=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)(s.type!=="value"||s.type==="value"&&typeof s.value=="object"&&s.value&&"type"in s.value)&&X0(s);if(a.labels){let s=a.labels;for(let o in s)try{let u=s[o],l=new ON(o,u,void 0,e);narration.RegisteredLabels.add(l);}catch(u){Ce.error(`Error creating JSON label ${o}`,u);}}return Promise.resolve()});await Promise.all(i);}function Uf(){A.init({animateOperation:L0,canvasElementOperation:R0,canvasOperation:$0,effectOperation:j0,imageContainerOperation:k0,imageOperation:F0,textOperation:V0,narrationOperation:q0,loadAssets:N0,soundOperation:B0,videoOperation:I0,setStorageValue:M0,setInitialStorageValue:G0,getLogichValue:qu.getLogichValue,getConditionalStep:Lu});}async function eC(n,e={}){Array.isArray(n)||(n=[n]),Uf();let t={functions:[],enums:{},characters:e.characters},r=n.map(async i=>{let a=Vu(i,t);return a&&await Hf(a,{operationStringConvert:xt.run,skipEmptyDialogs:true}),i});return await Promise.all(r)}async function Kf(n){return Uf(),await Hf(n,{operationStringConvert:xt.run,skipEmptyDialogs:true})}async function TN(n,e,t={}){let r={importJson:async s=>{await Kf(s);},importInkText:s=>eC(s,{characters:t.characters})},i=n&&typeof n=="object"&&"inkJson"in n?n.inkJson:void 0;if(i&&i.length>0){await r.importJson(i);return}let a=n&&typeof n=="object"&&"inkText"in n?n.inkText:typeof n=="string"?n:void 0;typeof a=="string"&&await r.importInkText(a);}async function NN(n={}){virtual_pixiVnInk.inkJsons&&virtual_pixiVnInk.inkJsons.length>0&&await Kf(virtual_pixiVnInk.inkJsons),undefined&&(undefined.on("ink-updated",async e=>{await TN(e,void 0,n);}),undefined.on("ink-error-cleared",()=>{document.querySelectorAll("vite-error-overlay").forEach(e=>{e.close();});}));}exports.setupInkHmrListener=NN;
102
+ ${S}`),S&&(o=true),s=A.getLogichValue(v.glueEnabled,e)||false,S)}),l=A.getLogichValue(u[0],e),c=typeof l=="object"&&"character"in l?l.character:void 0,h=u.flatMap(v=>{let d;v&&typeof v=="object"&&"text"in v?d=v.text:d=v;let S;return Array.isArray(d)?S=d.map(y=>{let w=A.getLogichValue(y,e);return St.t(`${w}`)}):S=A.getLogichValue(d,e)||"",St.t(S)}),p=a.find(v=>v.end),f=a.find(v=>v.choices),g=false,m=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),g=a[a.length-1].glueEnabled,m=a.reverse().find(v=>!(v.operations&&(!v.dialogue||!v.choices)))?.goNextStep);let b=a.find(v=>v.labelToOpen),C=[];return a.forEach(v=>{v.operations&&(C=[...C,...v.operations]);}),{dialogue:c?{character:c,text:h}:h,end:p?.end,choices:f?.choices,glueEnabled:g,goNextStep:m,labelToOpen:b?.labelToOpen,operations:C}}}var Wu;(n=>{let e=new Set;function t(a){e.add(a);}n.add=t;function r(){e.clear();}n.clear=r;function i(a,s={}){let o=c=>Hb(c,s)??void 0,u=Ub(a,s);if(e.size===0)return o(u);let l=o;for(let c of e){let h=l;l=p=>c(p,h)??void 0;}return l(u)}n.getLogichValue=i;})(Wu||={});var aN=Object.create,Qb=Object.defineProperty,oN=Object.getOwnPropertyDescriptor,uN=Object.getOwnPropertyNames,lN=Object.getPrototypeOf,cN=Object.prototype.hasOwnProperty,Xb=(n=>typeof On<"u"?On:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof On<"u"?On:e)[t]}):n)(function(n){if(typeof On<"u")return On.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),e0=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),hN=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of uN(e))!cN.call(n,i)&&i!==t&&Qb(n,i,{get:()=>e[i],enumerable:!(r=oN(e,i))||r.enumerable});return n},dN=(n,e,t)=>(t=n!=null?aN(lN(n)):{},hN(Qb(t,"default",{value:n,enumerable:true}),n)),pN=e0((n,e)=>{(function(t,r){typeof n=="object"?e.exports=n=r():typeof define=="function"&&define.amd?define([],r):t.CryptoJS=r();})(n,function(){var t=t||(function(r,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 Xb=="function")try{a=Xb("crypto");}catch{}var s=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||(function(){function v(){}return function(d){var S;return v.prototype=d,S=new v,v.prototype=null,S}})(),u={},l=u.lib={},c=l.Base=(function(){return {extend:function(v){var d=o(this);return v&&d.mixIn(v),(!d.hasOwnProperty("init")||this.init===d.init)&&(d.init=function(){d.$super.init.apply(this,arguments);}),d.init.prototype=d,d.$super=this,d},create:function(){var v=this.extend();return v.init.apply(v,arguments),v},init:function(){},mixIn:function(v){for(var d in v)v.hasOwnProperty(d)&&(this[d]=v[d]);v.hasOwnProperty("toString")&&(this.toString=v.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),h=l.WordArray=c.extend({init:function(v,d){v=this.words=v||[],d!=i?this.sigBytes=d:this.sigBytes=v.length*4;},toString:function(v){return (v||f).stringify(this)},concat:function(v){var d=this.words,S=v.words,y=this.sigBytes,w=v.sigBytes;if(this.clamp(),y%4)for(var E=0;E<w;E++){var O=S[E>>>2]>>>24-E%4*8&255;d[y+E>>>2]|=O<<24-(y+E)%4*8;}else for(var x=0;x<w;x+=4)d[y+x>>>2]=S[x>>>2];return this.sigBytes+=w,this},clamp:function(){var v=this.words,d=this.sigBytes;v[d>>>2]&=4294967295<<32-d%4*8,v.length=r.ceil(d/4);},clone:function(){var v=c.clone.call(this);return v.words=this.words.slice(0),v},random:function(v){for(var d=[],S=0;S<v;S+=4)d.push(s());return new h.init(d,v)}}),p=u.enc={},f=p.Hex={stringify:function(v){for(var d=v.words,S=v.sigBytes,y=[],w=0;w<S;w++){var E=d[w>>>2]>>>24-w%4*8&255;y.push((E>>>4).toString(16)),y.push((E&15).toString(16));}return y.join("")},parse:function(v){for(var d=v.length,S=[],y=0;y<d;y+=2)S[y>>>3]|=parseInt(v.substr(y,2),16)<<24-y%8*4;return new h.init(S,d/2)}},g=p.Latin1={stringify:function(v){for(var d=v.words,S=v.sigBytes,y=[],w=0;w<S;w++){var E=d[w>>>2]>>>24-w%4*8&255;y.push(String.fromCharCode(E));}return y.join("")},parse:function(v){for(var d=v.length,S=[],y=0;y<d;y++)S[y>>>2]|=(v.charCodeAt(y)&255)<<24-y%4*8;return new h.init(S,d)}},m=p.Utf8={stringify:function(v){try{return decodeURIComponent(escape(g.stringify(v)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(v){return g.parse(unescape(encodeURIComponent(v)))}},b=l.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new h.init,this._nDataBytes=0;},_append:function(v){typeof v=="string"&&(v=m.parse(v)),this._data.concat(v),this._nDataBytes+=v.sigBytes;},_process:function(v){var d,S=this._data,y=S.words,w=S.sigBytes,E=this.blockSize,O=E*4,x=w/O;v?x=r.ceil(x):x=r.max((x|0)-this._minBufferSize,0);var U=x*E,Se=r.min(U*4,w);if(U){for(var Ht=0;Ht<U;Ht+=E)this._doProcessBlock(y,Ht);d=y.splice(0,U),S.sigBytes-=Se;}return new h.init(d,Se)},clone:function(){var v=c.clone.call(this);return v._data=this._data.clone(),v},_minBufferSize:0});l.Hasher=b.extend({cfg:c.extend(),init:function(v){this.cfg=this.cfg.extend(v),this.reset();},reset:function(){b.reset.call(this),this._doReset();},update:function(v){return this._append(v),this._process(),this},finalize:function(v){v&&this._append(v);var d=this._doFinalize();return d},blockSize:16,_createHelper:function(v){return function(d,S){return new v.init(S).finalize(d)}},_createHmacHelper:function(v){return function(d,S){return new C.HMAC.init(v,S).finalize(d)}}});var C=u.algo={};return u})(Math);return t});}),fN=e0((n,e)=>{(function(t,r){typeof n=="object"?e.exports=n=r(pN()):typeof define=="function"&&define.amd?define(["./core"],r):r(t.CryptoJS);})(n,function(t){return (function(){var r=t,i=r.lib,a=i.WordArray,s=i.Hasher,o=r.algo,u=[],l=o.SHA1=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(c,h){for(var p=this._hash.words,f=p[0],g=p[1],m=p[2],b=p[3],C=p[4],v=0;v<80;v++){if(v<16)u[v]=c[h+v]|0;else {var d=u[v-3]^u[v-8]^u[v-14]^u[v-16];u[v]=d<<1|d>>>31;}var S=(f<<5|f>>>27)+C+u[v];v<20?S+=(g&m|~g&b)+1518500249:v<40?S+=(g^m^b)+1859775393:v<60?S+=(g&m|g&b|m&b)-1894007588:S+=(g^m^b)-899497514,C=b,b=m,m=g<<30|g>>>2,g=f,f=S;}p[0]=p[0]+f|0,p[1]=p[1]+g|0,p[2]=p[2]+m|0,p[3]=p[3]+b|0,p[4]=p[4]+C|0;},_doFinalize:function(){var c=this._data,h=c.words,p=this._nDataBytes*8,f=c.sigBytes*8;return h[f>>>5]|=128<<24-f%32,h[(f+64>>>9<<4)+14]=Math.floor(p/4294967296),h[(f+64>>>9<<4)+15]=p,c.sigBytes=h.length*4,this._process(),this._hash},clone:function(){var c=s.clone.call(this);return c._hash=this._hash.clone(),c}});r.SHA1=s._createHelper(l),r.HmacSHA1=s._createHmacHelper(l);})(),t.SHA1});}),Yb="___param___",Ce;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Ce||={});var mN=class ee{static init(e){e.loadAssets&&(ee._loadAssets=e.loadAssets),e.soundOperation&&(ee._soundOperation=e.soundOperation),e.imageOperation&&(ee._imageOperation=e.imageOperation),e.videoOperation&&(ee._videoOperation=e.videoOperation),e.imageContainerOperation&&(ee._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(ee._textOperation=e.textOperation),e.canvasElementOperation&&(ee._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(ee._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(ee._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(ee._narrationOperation=e.narrationOperation),e.effectOperation&&(ee._effectOperation=e.effectOperation),e.animateOperation&&(ee._animateOperation=e.animateOperation),e.canvasOperation&&(ee._canvasOperation=e.canvasOperation),e.getLogichValue&&(ee._getLogichValue=e.getLogichValue),e.getConditionalStep&&(ee._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return ee._loadAssets}static _soundOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return ee._soundOperation}static _imageOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return ee._imageOperation}static _videoOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return ee._videoOperation}static _imageContainerOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return ee._imageContainerOperation}static _textOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return ee._textOperation}static _canvasElementOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return ee._canvasElementOperation}static _setStorageValue=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return ee._setStorageValue}static _setInitialStorageValue=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return ee._setInitialStorageValue}static _narrationOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return ee._narrationOperation}static _effectOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return ee._effectOperation}static _animateOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return ee._animateOperation}static _canvasOperation=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return ee._canvasOperation}static _getLogichValue=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return ee._getLogichValue}static _getConditionalStep=()=>{throw Ce.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return ee._getConditionalStep}};function gN(n,e){if(e&&typeof e=="object"&&typeof n.functionName=="string"&&n.functionName in e){let t=e[n.functionName];if(typeof t=="function"){let r=n.args.map(i=>mN.getLogichValue(i,e));return t(...r)}else Ce.warn(`getLogichValue function ${n.functionName} not found in props`);}}function yN(n,e={}){let t="";return n.values.forEach(r=>{if(typeof r=="string")t+=r;else {let i=A.getLogichValue(r,e);t+=`${i}`;}}),t}async function t0(n,e,t){let r=A.getLogichValue(n,e);if(r)switch(r.type){case "sound":A.soundOperation(r);break;case "assets":case "bundle":await A.loadAssets(r);break;case "image":await A.imageOperation(r);break;case "video":await A.videoOperation(r);break;case "imagecontainer":await A.imageContainerOperation(r);break;case "text":await A.textOperation(r);break;case "canvaselement":await A.canvasElementOperation(r);break;case "canvas":A.canvasOperation(r);break;case "value":A.setStorageValue(r,e);break;case "operationtoconvert":if(t){let i=yN(r,e),a=await t(i);a&&await t0(a,e,t);}break;case "input":case "dialogue":A.narrationOperation(r);break;case "shake":await A.effectOperation(r);break;case "animate":case "animate-sequence":A.animateOperation(r);break;case "function":await gN(r,e);break}}function Zb(n){let e=A.getLogichValue(n,{});e&&e.type==="value"&&e.storageOperationType==="set"&&(e.storageType==="storage"||e.storageType==="tempstorage")&&A.setInitialStorageValue(e);}var vN=dN(fN()),bN=class extends narration.LabelAbstract{constructor(n,e,t,r={}){t||(t={}),t.onLoadingLabel=async()=>{for(let i of e){let a;if(typeof i=="function"?a=i():a=i,a=A.getConditionalStep(a),a.operations)try{let s=a.operations.map(o=>A.loadAssets(o));await Promise.all(s);}catch(s){Ce.error("The operation in the onLoadingLabel function of the label has an error:",s);}}},super(n,t),this._steps=e,this.operationStringConvert=r.operationStringConvert,this.skipEmptyDialogs=r.skipEmptyDialogs||false;}_steps;get steps(){return this._steps.map(n=>this.stepConverter(n))}get stepCount(){return this._steps.length}getStepById(n){if(n<0||n>=this._steps.length)return;let e=this._steps[n];return this.stepConverter(e)}operationStringConvert;skipEmptyDialogs=false;getStepSha(n){if(n<0||n>=this.steps.length)return;let e=this._steps[n];return (0, vN.default)(e.toString().toLocaleLowerCase()).toString()}getDialogueText(n,e){let t="";if(Array.isArray(n)){let r=[];n.forEach(i=>{if(typeof i=="string")r.push(i);else if(i&&typeof i=="object"){let a=A.getLogichValue(i,e);a?(a&&!Array.isArray(a)&&typeof a=="object"&&(a=A.getLogichValue(a,e)||""),Array.isArray(a)?r=r.map(s=>`${s}`).concat(a):r.push(`${a}`)):r.push(`${i}`);}else r.push(`${i}`);}),t=r;}else {let r=A.getLogichValue(n,e);r&&!Array.isArray(r)&&typeof r=="object"&&(r=A.getLogichValue(r,e)),r&&Array.isArray(r)?t=r.map(i=>`${i}`):t=`${r}`;}return t}getDialogue(n,e){if(n==null)return;let t=A.getLogichValue(n,e);return t==null?`${t}`:typeof t=="object"&&"character"in t&&"text"in t?{character:t.character,text:St.t(this.getDialogueText(t.text,e))}:St.t(this.getDialogueText(t,e))}getChoices(n,e){return A.getLogichValue(n,e)?.map(t=>A.getLogichValue(t,e)).filter(t=>t!==void 0)}stepConverter(n){return async e=>{let t=typeof n=="function"?n():n;t=pixiVn.createExportableElement(t),t=A.getConditionalStep(t,e);let r=this.operationStringConvert?p=>this.operationStringConvert(p,t,e):void 0,{operations:i=[]}=t;for(let p of i)await t0(p,e,r);let{labelToOpen:a=[]}=t,s=this.getChoices(t.choices,e),o=A.getLogichValue(t.glueEnabled,e),u=this.getDialogue(t.dialogue,e),l=[];Array.isArray(a)||(a=[a]),a.forEach(p=>{let f=A.getLogichValue(p,e);f&&l.push(f);});let c=A.getLogichValue(t.goNextStep,e),h=A.getLogichValue(t.end,e);if(s){let p=s.map(f=>{let g="";if(Array.isArray(f.text)){let m=[];f.text.forEach(b=>{if(typeof b=="string")m.push(St.t(b));else if(b&&typeof b=="object"){let C=A.getLogichValue(b,e);C&&!Array.isArray(C)&&typeof C=="object"&&(C=A.getLogichValue(C,e)||""),C&&(Array.isArray(C)?m=m.concat(St.t(C)):m.push(St.t(C)));}}),g=m;}else typeof f.text=="string"&&(g=St.t(f.text));return {label:f.label,text:g,props:f.props,type:f.type,oneTime:f.oneTime,onlyHaveNoChoice:f.onlyHaveNoChoice,autoSelect:f.autoSelect}});narration.narration.choices=p;}else narration.narration.choices=void 0;u!==void 0&&(narration.narration.dialogue=u,this.skipEmptyDialogs&&typeof u=="string"&&(u===""||RegExp(/^\s+$/).test(u))&&(c=true)),o?narration.narration.dialogGlue=true:o===false&&(narration.narration.dialogGlue=false);for(let p of l){let f=p.label;typeof f=="object"&&(f=A.getLogichValue(f,e)||"");let g=p.params?.map(m=>A.getLogichValue(m,e));e={...e,...p.props},p.type==="jump"?(narration.narration.labels.opened.length>0&&narration.narration.labels.closeCurrent(),storage.storage.temp.set(`${Yb}${narration.narration.labels.opened.length}`,g),await narration.narration.call(f,e)):(storage.storage.temp.set(`${Yb}${narration.narration.labels.opened.length}`,g),await narration.narration.call(f,e));}h==="game_end"?(narration.narration.labels.closeAll(),await narration.narration.continue(e,{runNow:true})):h==="label_end"&&narration.narration.labels.closeCurrent(),c&&await narration.narration.continue(e,{runNow:true});}}};async function Up(n,e={}){if(!Array.isArray(n))if(typeof n=="object"||typeof n=="string")n=[n];else {Ce.error("Error parsing imported Pixi'VN JSON: data is not an object");return}let t=n.map(a=>{if(typeof a=="string")try{return JSON.parse(a)}catch(s){return Ce.error("Error parsing imported Pixi'VN JSON",s),{}}return a}),r=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)s.type==="value"&&(typeof s.value!="object"||!s.value||!("type"in s.value))&&Zb(s);return Promise.resolve()});await Promise.all(r);let i=t.map(async a=>{if(a.initialOperations)for(let s of a.initialOperations)(s.type!=="value"||s.type==="value"&&typeof s.value=="object"&&s.value&&"type"in s.value)&&Zb(s);if(a.labels){let s=a.labels;for(let o in s)try{let u=s[o],l=new bN(o,u,void 0,e);narration.RegisteredLabels.add(l);}catch(u){Ce.error(`Error creating JSON label ${o}`,u);}}return Promise.resolve()});await Promise.all(i);}function Kp(){A.init({animateOperation:Bb,canvasElementOperation:$b,canvasOperation:Lb,effectOperation:qb,imageContainerOperation:Rb,imageOperation:kb,textOperation:jb,narrationOperation:Wb,loadAssets:Ib,soundOperation:Mb,videoOperation:Vb,setStorageValue:Jb,setInitialStorageValue:zb,getLogichValue:Wu.getLogichValue,getConditionalStep:Bu});}async function n0(n,e={}){Array.isArray(n)||(n=[n]),Kp();let t={functions:[],enums:{},characters:e.characters},r=n.map(async i=>{let a=ju(i,t);return a&&await Up(a,{operationStringConvert:Nt.run,skipEmptyDialogs:true}),i});return await Promise.all(r)}async function Xp(n){return Kp(),await Up(n,{operationStringConvert:Nt.run,skipEmptyDialogs:true})}async function SN(n,e,t={}){let r={importJson:async s=>{await Xp(s);},importInkText:s=>n0(s,{characters:t.characters})},i=n&&typeof n=="object"&&"inkJson"in n?n.inkJson:void 0;if(i&&i.length>0){await r.importJson(i);return}let a=n&&typeof n=="object"&&"inkText"in n?n.inkText:typeof n=="string"?n:void 0;typeof a=="string"&&await r.importInkText(a);}async function _N(n={}){virtual_pixiVnInk.inkJsons&&virtual_pixiVnInk.inkJsons.length>0&&await Xp(virtual_pixiVnInk.inkJsons),undefined&&(undefined.on("ink-updated",async e=>{await SN(e,void 0,n);}),undefined.on("ink-error-cleared",()=>{document.querySelectorAll("vite-error-overlay").forEach(e=>{e.close();});}));}exports.setupInkHmrListener=_N;