route-engine-js 0.1.33 → 0.1.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RouteEngine.js +1 -1
- package/package.json +10 -2
package/dist/RouteEngine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ot=Object.defineProperty;var kt=(e,t)=>{for(var n in t)Ot(e,n,{get:t[n],enumerable:!0})};var Ue=Symbol.for("immer-nothing"),De=Symbol.for("immer-draftable"),k=Symbol.for("immer-state");function N(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var U=Object.getPrototypeOf;function W(e){return!!e&&!!e[k]}function B(e){return e?We(e)||Array.isArray(e)||!!e[De]||!!e.constructor?.[De]||ie(e)||se(e):!1}var Rt=Object.prototype.constructor.toString();function We(e){if(!e||typeof e!="object")return!1;let t=U(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===Rt}function te(e,t){oe(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function oe(e){let t=e[k];return t?t.type_:Array.isArray(e)?1:ie(e)?2:se(e)?3:0}function he(e,t){return oe(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ze(e,t,n){let r=oe(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Pt(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ie(e){return e instanceof Map}function se(e){return e instanceof Set}function M(e){return e.copy_||e.base_}function ge(e,t){if(ie(e))return new Map(e);if(se(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=We(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[k];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let a=o[i],u=r[a];u.writable===!1&&(u.writable=!0,u.configurable=!0),(u.get||u.set)&&(r[a]={configurable:!0,writable:!0,enumerable:u.enumerable,value:e[a]})}return Object.create(U(e),r)}else{let r=U(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function we(e,t=!1){return ae(e)||W(e)||!B(e)||(oe(e)>1&&(e.set=e.add=e.clear=e.delete=Tt),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>we(r,!0))),e}function Tt(){N(2)}function ae(e){return Object.isFrozen(e)}var Nt={};function F(e){let t=Nt[e];return t||N(0,e),t}var q;function Ye(){return q}function Vt(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Me(e,t){t&&(F("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ye(e){me(e),e.drafts_.forEach(Dt),e.drafts_=null}function me(e){e===q&&(q=e.parent_)}function Be(e){return q=Vt(q,e)}function Dt(e){let t=e[k];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Fe(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[k].modified_&&(ye(t),N(4)),B(e)&&(e=ne(t,e),t.parent_||re(t,e)),t.patches_&&F("Patches").generateReplacementPatches_(n[k].base_,e,t.patches_,t.inversePatches_)):e=ne(t,n,[]),ye(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ue?e:void 0}function ne(e,t,n){if(ae(t))return t;let r=t[k];if(!r)return te(t,(o,i)=>je(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return re(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,a=!1;r.type_===3&&(i=new Set(o),o.clear(),a=!0),te(i,(u,l)=>je(e,r,o,u,l,n,a)),re(e,o,!1),n&&e.patches_&&F("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function je(e,t,n,r,o,i,a){if(W(o)){let u=i&&t&&t.type_!==3&&!he(t.assigned_,r)?i.concat(r):void 0,l=ne(e,o,u);if(ze(n,r,l),W(l))e.canAutoFreeze_=!1;else return}else a&&n.add(o);if(B(o)&&!ae(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;ne(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&re(e,o)}}function re(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&we(t,n)}function Mt(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Ye(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=_e;n&&(o=[r],i=X);let{revoke:a,proxy:u}=Proxy.revocable(o,i);return r.draft_=u,r.revoke_=a,u}var _e={get(e,t){if(t===k)return e;let n=M(e);if(!he(n,t))return Bt(e,n,t);let r=n[t];return e.finalized_||!B(r)?r:r===de(e.base_,t)?(pe(e),e.copy_[t]=Ie(r,e)):r},has(e,t){return t in M(e)},ownKeys(e){return Reflect.ownKeys(M(e))},set(e,t,n){let r=He(M(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=de(M(e),t),i=o?.[k];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Pt(n,o)&&(n!==void 0||he(e.base_,t)))return!0;pe(e),be(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return de(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,pe(e),be(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=M(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){N(11)},getPrototypeOf(e){return U(e.base_)},setPrototypeOf(){N(12)}},X={};te(_e,(e,t)=>{X[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});X.deleteProperty=function(e,t){return X.set.call(this,e,t,void 0)};X.set=function(e,t,n){return _e.set.call(this,e[0],t,n,e[0])};function de(e,t){let n=e[k];return(n?M(n):e)[t]}function Bt(e,t,n){let r=He(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function He(e,t){if(!(t in e))return;let n=U(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=U(n)}}function be(e){e.modified_||(e.modified_=!0,e.parent_&&be(e.parent_))}function pe(e){e.copy_||(e.copy_=ge(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ft=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let a=this;return function(l=i,...s){return a.produce(l,f=>n.call(this,f,...s))}}typeof n!="function"&&N(6),r!==void 0&&typeof r!="function"&&N(7);let o;if(B(t)){let i=Be(this),a=Ie(t,void 0),u=!0;try{o=n(a),u=!1}finally{u?ye(i):me(i)}return Me(i,r),Fe(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Ue&&(o=void 0),this.autoFreeze_&&we(o,!0),r){let i=[],a=[];F("Patches").generateReplacementPatches_(t,o,i,a),r(i,a)}return o}else N(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(a,...u)=>this.produceWithPatches(a,l=>t(l,...u));let r,o;return[this.produce(t,n,(a,u)=>{r=a,o=u}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){B(e)||N(8),W(e)&&(e=jt(e));let t=Be(this),n=Ie(e,void 0);return n[k].isManual_=!0,me(t),n}finishDraft(e,t){let n=e&&e[k];(!n||!n.isManual_)&&N(9);let{scope_:r}=n;return Me(r,t),Fe(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=F("Patches").applyPatches_;return W(e)?r(e,t):this.produce(e,o=>r(o,t))}};function Ie(e,t){let n=ie(e)?F("MapSet").proxyMap_(e,t):se(e)?F("MapSet").proxySet_(e,t):Mt(e,t);return(t?t.scope_:Ye()).drafts_.push(n),n}function jt(e){return W(e)||N(10,e),Ke(e)}function Ke(e){if(!B(e)||ae(e))return e;let t=e[k],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=ge(e,t.scope_.immer_.useStrictShallowCopy_)}else n=ge(e,!0);return te(n,(r,o)=>{ze(n,r,Ke(o))}),t&&(t.finalized_=!1),n}var R=new Ft,ve=R.produce,Kr=R.produceWithPatches.bind(R),Jr=R.setAutoFreeze.bind(R),qr=R.setUseStrictShallowCopy.bind(R),Xr=R.applyPatches.bind(R),Gr=R.createDraft.bind(R),Qr=R.finishDraft.bind(R);var Je=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:a=l=>l,transformActionFirstArgument:u=l=>l}=n;for(let[l,s]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?o[l]=(...f)=>s(a(r),...f):i[l]=(...f)=>{r=ve(r,d=>s(u(d),...f))});return{...o,...i}},le=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return ve(r,i=>{o.forEach(a=>{t.forEach(u=>{u(i,a)})})})};var Ut=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},qe=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=Ut(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},Xe=(e,t)=>{let n=["context","global-device","global-account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},Ge=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},xe=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}},Ee=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),Qe=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=o=>String(o).padStart(2,"0");return t.replace("DD",r(n.getDate())).replace("MM",r(n.getMonth()+1)).replace("YYYY",n.getFullYear()).replace("YY",String(n.getFullYear()).slice(-2)).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},Wt=(e,t)=>{let n=e?.gui,r=t?.gui;return JSON.stringify(n)===JSON.stringify(r)?null:n&&!r?{changeType:"delete",data:e}:r&&!e?{changeType:"add",data:t}:r&&e?{changeType:"update",data:t}:null},Ae=(e={},t={})=>{let n={},r=["sfx","voice"],o=a=>{let u=e[a],l=t[a];l&&!u?n[a]={changeType:"add",data:l}:u&&!l?r.includes(a)||(n[a]={changeType:"delete",data:u}):u&&l&&JSON.stringify(u)!==JSON.stringify(l)&&(n[a]={changeType:"update",data:l})};o("background"),o("base"),o("bgm"),o("voice");let i=Wt(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("keyboard"),o("character"),o("visual"),o("sfx"),n};var ce=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},Ze=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},zt=()=>({}),Yt=(e,t)=>{t.base&&(e.base={...t.base})},Ht=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=ce(t.background,o=>!!o.resourceId);if(n){e.background=r;return}if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},Kt=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.characterId=void 0);return}if(e.dialogue||(e.dialogue={}),t.dialogue.gui){let{animationsOnly:n,state:r}=ce(t.dialogue.gui,o=>!!o.resourceId);n?e.dialogue.gui={...e.dialogue.gui,...r}:e.dialogue.gui={...t.dialogue.gui}}else e.dialogue?.gui?.animations&&(e.dialogue.gui.animations={});if(t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content),delete e.dialogue.characterId,t.dialogue.characterId&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character&&(e.dialogue.character={...t.dialogue.character}),t.dialogue.clear){delete e.dialogue;return}t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),t.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&e.dialogue.lines.push({content:t.dialogue.content,characterId:t.dialogue.characterId||null})},Jt=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},qt=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},Xt=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=Ze(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Gt=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=Ze(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},Qt=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Zt=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=ce(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},en=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=ce(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},tn=(e,t)=>{t.keyboard&&(e.keyboard=t.keyboard)},nn=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},rn=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},G=e=>le(zt,[rn,Yt,Ht,Jt,qt,Xt,Kt,Gt,Qt,Zt,en,tn,nn])(e);var p={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},E={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Q={NOT:0};var w=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},S=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Le=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new w(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},et=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var tt=(e,t,n=!1)=>{if(t===null)return new S(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new S(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new S(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new S(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},nt=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new S(`Unknown function '${e}' (${n})`)};var on=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let a=x(e,{functions:r,partials:o},t,{});return a===void 0?{}:a},x=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return A(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return A(e.path,n,r);if(e.type===p.INTERPOLATION)return an(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return ot(e,t,n,r);case p.BINARY:return it(e,t,n,r);case p.UNARY:return st(e,t,n,r);case p.CONDITIONAL:return cn(e,t,n,r);case p.LOOP:return hn(e,t,n,r);case p.OBJECT:return yn(e,t,n,r);case p.ARRAY:return mn(e,t,n,r);case p.PARTIAL:return bn(e,t,n,r);case p.PATH_REFERENCE:return In(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},rt=new Map,sn=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let a=n.trim();if(/^\d+$/.test(a))t.push({type:"index",value:parseInt(a,10)});else if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'")){let u=a.slice(1,-1);t.push({type:"property",value:u})}else t.push({type:"property",value:a});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},A=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=rt.get(e);if(!r){let i=[],a="",u=0;for(let l=0;l<e.length;l++){let s=e[l];s==="["?(u++,a+=s):s==="]"?(u--,a+=s):s==="."&&u===0?a&&(i.push(a),a=""):a+=s}a&&i.push(a),r=[];for(let l of i){let s=sn(l.trim());r.push(...s)}rt.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let a=r[i];if(a.type==="property"&&a.value in n){o=n[a.value];continue}if(o==null)return;(a.type==="property"||a.type==="index")&&(o=o[a.value])}return o},an=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let a=x(i,t,n,r);o.push(a!=null?String(a):"")}return o.join("")},ot=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw nt(e.name,o);let a=e.args.map(u=>x(u,t,n,r));return i(...a)},z=(e,t,n,r)=>{if(e.var&&!e.type)return A(e.var,n,r);switch(e.type){case p.VARIABLE:return A(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return it(e,t,n,r);case p.UNARY:return st(e,t,n,r);case p.FUNCTION:return ot(e,t,n,r);default:return x(e,t,n,r)}},it=(e,t,n,r)=>{if(e.op===E.AND||e.op===E.OR){let a=z(e.left,t,n,r),u=z(e.right,t,n,r);switch(e.op){case E.AND:return a&&u;case E.OR:return a||u}}let o=x(e.left,t,n,r),i=x(e.right,t,n,r);switch(e.op){case E.EQ:return o==i;case E.NEQ:return o!=i;case E.GT:return o>i;case E.LT:return o<i;case E.GTE:return o>=i;case E.LTE:return o<=i;case E.IN:return Array.isArray(i)?i.includes(o):!1;case E.ADD:if(typeof o!="number"||typeof i!="number")throw new S(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case E.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new S(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},st=(e,t,n,r)=>{let o=e.op===Q.NOT?z(e.operand,t,n,r):x(e.operand,t,n,r);if(e.op===Q.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},ln=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(A(o.path,n,r)){let a=e.bodies[0];if(a.type===p.OBJECT&&a.properties.length<=5){let u={};for(let l of a.properties){let s=l.parsedKey?x(l.parsedKey,t,n,r):l.key,f=l.value;if(f.type===p.LITERAL)u[s]=f.value;else if(f.type===p.VARIABLE)u[s]=A(f.path,n,r);else if(f.type===p.INTERPOLATION){let c=[];for(let d of f.parts)if(typeof d=="string")c.push(d);else if(d.type===p.VARIABLE){let h=A(d.path,n,r);c.push(h!=null?String(h):"")}else{let h=x(d,t,n,r);c.push(h!=null?String(h):"")}u[s]=c.join("")}else u[s]=x(f,t,n,r)}return u}}else{let a=e.bodies[1];if(a.type===p.OBJECT&&a.properties.length<=5){let u={};for(let l of a.properties){let s=l.parsedKey?x(l.parsedKey,t,n,r):l.key,f=l.value;if(f.type===p.LITERAL)u[s]=f.value;else if(f.type===p.VARIABLE)u[s]=A(f.path,n,r);else if(f.type===p.INTERPOLATION){let c=[];for(let d of f.parts)if(typeof d=="string")c.push(d);else if(d.type===p.VARIABLE){let h=A(d.path,n,r);c.push(h!=null?String(h):"")}else{let h=x(d,t,n,r);c.push(h!=null?String(h):"")}u[s]=c.join("")}else u[s]=x(f,t,n,r)}return u}}}return null},cn=(e,t,n,r)=>{let o=ln(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let a=e.conditions[i];if(a===null||z(a,t,n,r))return x(e.bodies[i],t,n,r)}return at},un=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let a=o.substring(r.length+1);if(i.type===p.OBJECT&&i.properties.length<=5){for(let l of i.properties)if(l.parsedKey)return null;let u=[];for(let l=0;l<t.length;l++){let s=t[l];if(s[a]){let f={};for(let c of i.properties){let d=c.key,h=c.value;if(h.type===p.LITERAL)f[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)f[d]=s;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);f[d]=s[y]}else return null}else if(h.type===p.INTERPOLATION){let g=[],y=!0;for(let m of h.parts)if(typeof m=="string")g.push(m);else if(m.type===p.VARIABLE){let b=m.path;if(b===r)g.push(s!=null?String(s):"");else if(b.startsWith(r+".")){let I=b.substring(r.length+1),_=s[I];g.push(_!=null?String(_):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;f[d]=g.join("")}else return null}u.push(f)}}return u}}}return null},fn=(e,t)=>{let n=e.body,r=e.itemVar,o=un(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let u of n.properties)if(u.parsedKey)return null;let i=[],a=!0;for(let u of n.properties){let l=u.key,s=u.value;if(s.type===p.LITERAL)i.push({key:l,type:"literal",value:s.value});else if(s.type===p.VARIABLE){let f=s.path;if(f===r)i.push({key:l,type:"item"});else if(f.startsWith(r+".")){let c=f.substring(r.length+1);if(!c.includes(".")&&!c.includes("["))i.push({key:l,type:"prop",prop:c});else{a=!1;break}}else{a=!1;break}}else if(s.type===p.INTERPOLATION&&s.parts.length===1){let f=s.parts[0];if(f.type===p.VARIABLE){let c=f.path;if(c===r)i.push({key:l,type:"item_string"});else if(c.startsWith(r+".")){let d=c.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:l,type:"prop_string",prop:d});else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}if(a){let u=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let l=0;l<t.length;l++){let s=t[l];u[l]={id:s.id,title:s.title!=null?String(s.title):"",completed:s.completed}}else for(let l=0;l<t.length;l++){let s=t[l],f={};for(let c of i)if(c.type==="literal")f[c.key]=c.value;else if(c.type==="item")f[c.key]=s;else if(c.type==="prop")f[c.key]=s[c.prop];else if(c.type==="item_string")f[c.key]=s!=null?String(s):"";else if(c.type==="prop_string"){let d=s[c.prop];f[c.key]=d!=null?String(d):""}u[l]=f}return u}}return null},dn=(e,t,n,r,o)=>{let i=[],a=e.body;if(a.type===p.OBJECT&&a.fast!==!1){let u=e.itemVar,l=e.indexVar;for(let s=0;s<o.length;s++){let f=o[s],c={},d={...r,[u]:f,...l&&{[l]:s}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let g=h.split("."),y=g[0];y in r.__paths__&&(h=r.__paths__[y],g.length>1&&(h+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[u]:`${h}[${s}]`,...l&&{[l]:s}};for(let g of a.properties){let y=g.parsedKey?x(g.parsedKey,t,n,d):g.key,m=g.value;if(m.type===p.LITERAL)c[y]=m.value;else if(m.type===p.VARIABLE){let b=m.path;if(b===u)c[y]=f;else if(b===l)c[y]=s;else if(b.startsWith(u+".")){let I=b.substring(u.length+1);!I.includes(".")&&!I.includes("[")?c[y]=f[I]:c[y]=A(b,n,{...r,[u]:f,...l&&{[l]:s}})}else c[y]=A(b,n,{...r,[u]:f,...l&&{[l]:s}})}else if(m.type===p.INTERPOLATION){let b=[];for(let I of m.parts)if(typeof I=="string")b.push(I);else if(I.type===p.VARIABLE){let _=I.path,v;if(_===u)v=f;else if(_===l)v=s;else if(_.startsWith(u+".")){let L=_.substring(u.length+1);!L.includes(".")&&!L.includes("[")?v=f[L]:v=A(_,n,{...r,[u]:f,...l&&{[l]:s}})}else v=A(_,n,{...r,[u]:f,...l&&{[l]:s}});b.push(v!=null?String(v):"")}else{let _={...r,[u]:f,...l&&{[l]:s}},v=x(I,t,n,_);b.push(v!=null?String(v):"")}c[y]=b.join("")}else{let b={...r,[u]:f,...l&&{[l]:s}};c[y]=x(m,t,n,b)}}i.push(c)}return i}return null},pn=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let a=i.bodies[0];if(a.type===p.OBJECT&&a.properties.length===2){let u=a.properties[0],l=a.properties[1];if(u.key==="id"&&u.value.type===p.VARIABLE&&u.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===p.CONDITIONAL){let s=[];for(let f=0;f<t.length;f++){let c=t[f];if(c.visible){let d={id:c.id};c.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${c.name}`):(d.highlight=!1,d.message=c.name),s.push(d)}}return s}}}}return null},hn=(e,t,n,r)=>{let o=x(e.iterable,t,n,r);if(!Array.isArray(o)){let s,f=!1;if(e.iterable.type===p.FUNCTION){f=!0;let d=e.iterable.args.map(h=>h.type===p.LITERAL?typeof h.value=="string"?`'${h.value}'`:String(h.value):h.type===p.VARIABLE?h.path:h.type===p.FUNCTION?`${h.name}(...)`:"?").join(", ");s=`${e.iterable.name}(${d})`}else s=e.iterable.path||"undefined";let c=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${s}`;throw tt(c,o,f)}if(!e.indexVar){let s=pn(e,o,e.itemVar);if(s!==null)return s}if(!e.indexVar){let s=fn(e,o);if(s!==null)return s}let i=dn(e,t,n,r,o);if(i!==null)return i;let a=[],u=e.iterable.path||"";if(r&&r.__paths__&&u){let s=u.split("."),f=s[0];f in r.__paths__&&(u=r.__paths__[f],s.length>1&&(u+="."+s.slice(1).join(".")))}let l=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(s=>s.type===p.OBJECT&&s.properties.some(f=>f.key.startsWith("$if ")||f.key.startsWith("$when "))));for(let s=0;s<o.length;s++){let f=e.indexVar?{...r,[e.itemVar]:o[s],[e.indexVar]:s}:{...r,[e.itemVar]:o[s]};f.__paths__||(f.__paths__=r.__paths__||{}),f.__paths__={...f.__paths__,[e.itemVar]:`${u}[${s}]`},e.indexVar&&(f.__paths__[e.indexVar]=s);let c=x(e.body,t,n,f);if(Array.isArray(c)&&c.length===1&&!l){let d=c[0];a.push(d===void 0?{}:d)}else a.push(c===void 0?{}:c)}return a},gn=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?x(o.parsedKey,t,n,r):o.key,a=o.value;if(a.type===p.OBJECT&&a.properties.length<=10&&!a.whenCondition){let u={},l={},s=!0;for(let f of a.properties){let c=f.parsedKey?x(f.parsedKey,t,n,r):f.key,d=f.value;if(d.type===p.LITERAL)l[c]=d.value;else if(d.type===p.VARIABLE)l[c]=A(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=A(g.path,n,r);h.push(y!=null?String(y):"")}else{s=!1;break}if(!s)break;l[c]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,m=g.value;if(m.type===p.LITERAL)h[y]=m.value;else if(m.type===p.VARIABLE)h[y]=A(m.path,n,r);else if(m.type===p.INTERPOLATION){let b=[];for(let I of m.parts)if(typeof I=="string")b.push(I);else if(I.type===p.VARIABLE){let _=A(I.path,n,r);b.push(_!=null?String(_):"")}else{s=!1;break}if(!s)break;h[y]=b.join("")}else{s=!1;break}}if(!s)break;l[c]=h}else{s=!1;break}}if(s)return u[i]=l,u}}return null},yn=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!z(e.whenCondition,o,n,r))return;let i=gn(e,t,n,r);if(i!==null)return i;if(e.fast){let s={};for(let f of e.properties){let c=f.parsedKey?x(f.parsedKey,t,n,r):f.key,d=f.value;if(d.type===p.LITERAL)s[c]=d.value;else if(d.type===p.VARIABLE)s[c]=A(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let y=A(g.path,n,r);h.push(y!=null?String(y):"")}else{let y=x(g,t,n,r);h.push(y!=null?String(y):"")}s[c]=h.join("")}else s[c]=x(d,t,n,r)}return s}let a={},u=null,l=!1;for(let s of e.properties)if(!s.key.startsWith("$if ")&&!s.key.match(/^\$if\s+\w+.*:?$/)&&!s.key.startsWith("$elif")&&!s.key.startsWith("$else")&&!s.key.startsWith("$for ")){l=!0;break}for(let s of e.properties)if(s.key.startsWith("$if ")||s.key.match(/^\$if\s+\w+.*:?$/)){let f=x(s.value,t,n,r);if(!l&&f!==null&&f!==void 0)return Array.isArray(f)&&f.length===1?f[0]:f;typeof f=="object"&&f!==null&&!Array.isArray(f)&&Object.assign(a,f)}else if(s.key.startsWith("$for ")){if(e.properties.length===1)return x(s.value,t,n,r)}else{let f=s.value;if(f&&f.type===p.OBJECT&&f.properties){let c=f.properties.find(d=>d.key.startsWith("$for "));if(c){let d=x(c.value,t,n,r);d!==void 0&&(a[s.key]=d)}else{let d=x(s.value,t,n,r);d!==void 0&&(a[s.key]=d)}}else{let c=s.parsedKey?x(s.parsedKey,t,n,r):s.key,d=x(s.value,t,n,r);d!==void 0&&(a[c]=d)}}return a},at={},mn=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let a=x(i,t,n,r);Array.isArray(a)&&i.flatten!==!1?o.push(...a):o.push(a)}else{let a=x(i,t,n,r);a!==at&&a!==void 0&&o.push(a)}return o},bn=(e,t,n,r)=>{let{name:o,data:i,whenCondition:a}=e,u=t.partials||{},l=t.functions||t;if(a&&!z(a,l,n,r))return;if(!u[o])throw new S(`Partial '${o}' is not defined`);let s=r._partialStack||[];if(s.includes(o))throw new S(`Circular partial reference detected: ${o}`);let f=u[o],c=n,d={...r,_partialStack:[...s,o]};if(r){c={...n};for(let h of Object.keys(r))h.startsWith("_")||(c[h]=r[h])}if(i){let h=x(i,t,n,r);c={...c,...h}}return x(f,t,c,d)},In=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),a=i[0],u=i.slice(1);if(!r||!(a in r))throw new S(`Path reference '#{${o}}' refers to '${a}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(a in r.__paths__))throw new S(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let l=r.__paths__[a];if(typeof l=="number"){if(u.length>0)throw new S(`Path reference '#{${o}}' - cannot access properties on index variable '${a}'`);return String(l)}return u.length>0&&(l+="."+u.join(".")),l},$e=on;var wn=/\$\{([^}]*)\}/g,_n=/#\{([^}]*)\}/g,ct=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=vn(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},vn=(e,t={})=>e.trim()?xn(e).map(r=>En(r.trim(),t)):[],xn=e=>{let t=[],n="",r=0,o=!1,i="";for(let a=0;a<e.length;a++){let u=e[a],l=a>0?e[a-1]:"";!o&&(u==='"'||u==="'")?(o=!0,i=u,n+=u):o&&u===i&&l!=="\\"?(o=!1,i="",n+=u):!o&&u==="("?(r++,n+=u):!o&&u===")"?(r--,n+=u):!o&&u===","&&r===0?(t.push(n),n=""):n+=u}return n&&t.push(n),t},En=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:p.LITERAL,value:parseFloat(e)};if(e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};let n=ct(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,a=null;for(let{op:u,type:l}of o){let s=0;for(;s<r.length;){let f=j(r.substring(s),u);if(f===-1)break;let c=s+f;c>i&&(i=c,a={op:u,type:l}),s=c+u.length}}if(i!==-1)try{return $(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},ut=/^\w+\(.*\)$/,An=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Ln=e=>{if(!(!e||e.trim()===""||ut.test(e))&&An.test(e))throw e.includes("?")&&e.includes(":")?new w(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},lt=e=>{let t=e.trim();if(ut.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new w(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:p.PATH_REFERENCE,path:t}},Z=(e,t={})=>{let n=e.trim();Ln(n);let r=ct(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:p.VARIABLE,path:n}},Ce=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(s,f)=>{let c=`__ESCAPED_${r.length}__`;return r.push(f),c}),n=n.replace(/\\(#\{[^}]*\})/g,(s,f)=>{let c=`__ESCAPED_${r.length}__`;return r.push(f),c}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(wn)],i=[...n.matchAll(_n)],a=[...o.map(s=>({match:s,type:"variable"})),...i.map(s=>({match:s,type:"pathref"}))].sort((s,f)=>s.match.index-f.match.index);if(a.length===0){let s=n;for(let f=0;f<r.length;f++)s=s.replace(`__ESCAPED_${f}__`,r[f]);return{type:p.LITERAL,value:s}}if(a.length===1&&a[0].match[0]===n&&r.length===0){let{match:s,type:f}=a[0];try{return f==="variable"?Z(s[1],t):lt(s[1])}catch(c){if(c.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw c}}let u=[],l=0;for(let{match:s,type:f}of a){let[c,d]=s,h=s.index;if(h>l){let g=n.substring(l,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&u.push(g)}try{let g;f==="variable"?g=Z(d.trim(),t):g=lt(d.trim()),u.push(g)}catch(g){if(g.message==="Invalid array index syntax")u.push(c);else throw g}l=h+c.length}if(l<n.length){let s=n.substring(l);for(let f=0;f<r.length;f++)s=s.replace(`__ESCAPED_${f}__`,r[f]);s&&u.push(s)}return{type:p.INTERPOLATION,parts:u}};var D=(e,t)=>typeof e=="string"?Ce(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Cn(e,t):Sn(e,t):{type:p.LITERAL,value:e},$n=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new w("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new w("Empty $each body not allowed");if(n.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},Cn=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let l=$n(i),s=Object.keys(l);if(s.length===1&&/^\$for(?::\w+)?\s/.test(s[0])){let f=ft(s[0],l[s[0]],t,!0);n.push(f),r=!0;continue}}catch(l){throw l instanceof w?l:new w(l.message)}let u=Object.keys(i);if(u.length===1&&/^\$for(?::\w+)?\s/.test(u[0])){let l=ft(u[0],i[u[0]],t);n.push(l),r=!0;continue}}let a=D(i,t);n.push(a),(a.type===p.FUNCTION||a.type===p.CONDITIONAL||a.type===p.LOOP||a.type===p.PARTIAL||a.type===p.OBJECT&&!a.fast||a.type===p.ARRAY&&!a.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},Sn=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),a=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],s=[];for(let[b]of i)for(let I of l)if(b===I||b.startsWith(I+" ")||b.startsWith(I+"#")){s.push(I);break}if(s.length>0)throw new w(`Cannot use $partial with ${s.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:f,$when:c,...d}=e,h={},g=!1;for(let[b,I]of Object.entries(d)){let _=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(_=b.slice(1)),h[_]=I,g=!0}let y=null;if(g&&(y=D(h,t),y.type===p.OBJECT)){let b=!1;for(let I of y.properties)if(I.value.type===p.VARIABLE||I.value.type===p.INTERPOLATION||I.value.type===p.FUNCTION||I.value.type===p.CONDITIONAL||I.value.type===p.OBJECT&&!I.value.fast||I.value.type===p.ARRAY&&!I.value.fast){b=!0;break}b&&(y.fast=!1)}let m={type:p.PARTIAL,name:f,data:y};if(c!==void 0){let b;if(typeof c=="string"){if(c.trim()==="")throw new w("Empty condition expression after '$when'");b=$(c,t)}else b={type:p.LITERAL,value:c};m.whenCondition=b}return m}for(let[l,s]of i)if(l==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(s==null)throw new w("Missing condition expression after '$when'");let f=typeof s=="string"?s:JSON.stringify(s);if(f.trim()==="")throw new w("Empty condition expression after '$when'");o=$(f,t),r=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;a<i.length;){let[l,s]=i[a];if(l==="$when"){a++;continue}if(l==="$each")throw new w("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let f=On(i,a,t);n.push({key:l,value:f.node}),r=!0,a=f.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let f=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",c=f?`:${f}`:"";throw new w(`$for loops must be inside arrays - use '- $for${c} item in items:' instead of '$for${c} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(l.startsWith("$elif ")||l.startsWith("$else"))throw new w(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new w("Missing condition expression after '$if'");{let f=D(s,t);(f.type===p.FUNCTION||f.type===p.CONDITIONAL||f.type===p.PARTIAL||f.type===p.OBJECT&&!f.fast||f.type===p.ARRAY&&!f.fast)&&(r=!0);let c=Ce(l,t),d={key:l,value:f};(c.type!==p.LITERAL||c.value!==l)&&(d.parsedKey=c),n.push(d),a++}}}let u={type:p.OBJECT,properties:n,fast:!r};return o&&(u.whenCondition=o),u},On=(e,t,n={})=>{let r=[],o=[],i=t,[a,u]=e[i],l=null,s;if(a.startsWith("$if#")){let c=a.match(/^\$if#(\w+)\s+(.+)$/);if(c)l=c[1],s=c[2];else throw new w(`Invalid conditional syntax: ${a}`)}else s=a.substring(4),s.endsWith(":")&&(s=s.slice(0,-1).trim());Le(s);let f=$(s,n);for(r.push(f),o.push(D(u,n)),i++;i<e.length;){let[c,d]=e[i],h=!1,g;if(l?c.startsWith(`$elif#${l} `)?(g=c.substring(`$elif#${l} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(c===`$else#${l}`||c===`$else#${l}:`)&&(h=!0,g=null):c.startsWith("$elif ")?(g=c.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(c==="$else"||c==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{Le(g);let y=$(g,n);r.push(y)}if(o.push(D(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:l},nextIndex:i}},$=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let s=e.slice(1,-1),f=0,c=!0;for(let d=0;d<s.length;d++)if(s[d]==="("?f++:s[d]===")"&&f--,f<0){c=!1;break}if(c&&f===0)return $(s,t)}let n=j(e,"||");if(n!==-1)return{type:p.BINARY,op:E.OR,left:$(e.substring(0,n).trim(),t),right:$(e.substring(n+2).trim(),t)};let r=j(e,"&&");if(r!==-1)return{type:p.BINARY,op:E.AND,left:$(e.substring(0,r).trim(),t),right:$(e.substring(r+2).trim(),t)};let o=[{op:">=",type:E.GTE},{op:"<=",type:E.LTE},{op:"==",type:E.EQ},{op:"!=",type:E.NEQ},{op:">",type:E.GT},{op:"<",type:E.LT},{op:" in ",type:E.IN}];for(let{op:s,type:f}of o){let c=j(e,s);if(c!==-1)return{type:p.BINARY,op:f,left:$(e.substring(0,c).trim(),t),right:$(e.substring(c+s.length).trim(),t)}}let i=-1,a=null,u=[{op:" + ",type:E.ADD},{op:" - ",type:E.SUBTRACT}];for(let{op:s,type:f}of u){let c=0;for(;c<e.length;){let d=j(e.substring(c),s);if(d===-1)break;let h=c+d;h>i&&(i=h,a={op:s,type:f}),c=h+s.length}}if(i!==-1&&a)return{type:p.BINARY,op:a.type,left:$(e.substring(0,i).trim(),t),right:$(e.substring(i+a.op.length).trim(),t)};let l=[" * "," / "," % "];for(let s of l)if(j(e,s)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${s}"`);return e.startsWith("!")?{type:p.UNARY,op:Q.NOT,operand:$(e.substring(1).trim(),t)}:dt(e,t)},j=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},kn=e=>{if(e=e.trim(),e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:p.LITERAL,value:""};if(e==="{}")return{type:p.LITERAL,value:{}};if(e==="[]")return{type:p.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:p.LITERAL,value:t}:{type:p.VARIABLE,path:e}},dt=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return Z(n,t);let o=kn(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return Z(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},Rn=(e,t=!1)=>{let n=t?"$each":"$for";try{et(e)}catch(r){if(r instanceof w&&t){let o=r.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw r}},ft=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let m=r?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",m)}')`)}let a=i[1],u=i[2].trim();Rn(u,r);let l=u.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let m=r?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${m} ${u}')`)}let s=l[1].trim(),f=l[2].trim(),c,d=null;if(s.includes(",")){let m=s.split(",").map(b=>b.trim());if(m.length!==2)throw new w(`Invalid loop variables: ${s}. Expected format: "item" or "item, index"`);c=m[0],d=m[1]}else c=s;let h=["this","undefined","null","true","false"];if(h.includes(c))throw new w(`Reserved variable name: ${c}`);if(d&&h.includes(d))throw new w(`Reserved variable name: ${d}`);let g=dt(f,n),y=D(t,n);return{type:p.LOOP,itemVar:c,indexVar:d,iterable:g,body:y,flatten:a!=="nested"}};var Pn=(e,t={})=>{let{functions:n={}}=t;return D(e,n)},ue=Pn;var Se={};kt(Se,{now:()=>Tn});var Tn=()=>Date.now();var Nn=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Se,...r},a=ue(e,{functions:i}),u={};for(let[l,s]of Object.entries(o))u[l]=ue(s,{functions:i});return $e(a,t,{functions:i,partials:u})},P=Nn;var Y={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:Qe},pt=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=P(e,t);return n&&typeof n=="object"?e:n},H=({animations:e,animationsDef:t,resources:n,previousResourceId:r,currentResourceId:o,idPrefix:i,targetId:a,outTargetId:u})=>{if(t){if(t.in){let l=t.in.resourceId||t.in,s=n?.tweens?.[l];s&&!r&&e.push({id:`${i}-animation-in`,type:"tween",targetId:a,properties:structuredClone(s.properties)})}if(t.out){let l=t.out.resourceId||t.out,s=n?.tweens?.[l];s&&r&&r!==o&&e.push({id:`${i}-animation-out`,type:"tween",targetId:u||a,properties:structuredClone(s.properties)})}if(t.update){let l=t.update.resourceId||t.update,s=n?.tweens?.[l];s&&r&&r===o&&e.push({id:`${i}-animation-update`,type:"tween",targetId:a,properties:structuredClone(s.properties)})}}},Vn=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Dn=(e,{presentationState:t,resources:n,variables:r})=>{let{elements:o}=e;if(t.base){let i=o.find(a=>a.id==="story");if(!i)return e;if(t.base.resourceId){let a=n?.layouts[t.base.resourceId];if(a){let u={id:"base",type:"container",children:a.elements},l=P(u,{variables:r},{functions:Y});i.children.unshift(l)}}}return e},Mn=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,variables:a})=>{let{elements:u,animations:l}=e;if(t.background){let s=u.find(f=>f.id==="story");if(!s)return e;if(t.background.resourceId){let{images:f={},videos:c={}}=r,d=f[t.background.resourceId]||c[t.background.resourceId];if(d){let h=c[t.background.resourceId]!==void 0,g={id:`bg-cg-${t.background.resourceId}`,type:h?"video":"sprite",x:0,y:0,src:d.fileId,width:d.width,height:d.height};h&&(g.loop=t.background.loop??!1,g.volume=d.volume??500),s.children.push(g)}}if(t.background.resourceId){let{layouts:f={}}=r,c=f[t.background.resourceId];if(c){let d={id:`bg-cg-${t.background.resourceId}`,type:"container",children:c.elements},h=P(d,{variables:a},{functions:Y});s.children.push(h)}}if(t.background.animations&&!o&&!i){let f=n?.background?.resourceId,c=t.background.resourceId;H({animations:l,animationsDef:t.background.animations,resources:r,previousResourceId:f,currentResourceId:c,idPrefix:"bg-cg",targetId:`bg-cg-${c}`,outTargetId:`bg-cg-${f}`})}}return e},Bn=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i})=>{let{elements:a,animations:u}=e;if(t.character&&r){let l=a.find(c=>c.id==="story");if(!l)return e;let s=t.character.items||[],f=n?.character?.items||[];for(let c=0;c<s.length;c++){let d=s[c],{transformId:h,sprites:g}=d,y=f.find(C=>C.id===d.id),m=y?.sprites&&y.sprites.length>0,b=g&&g.length>0;if(d.animations&&d.animations.out&&!g&&!h){if(!o&&m){let C=d.animations.out.resourceId,T=r?.tweens?.[C];if(T){let V={id:"character-animation-out",type:"tween",targetId:`character-container-${d.id}`,properties:T.properties};u.push(V)}}continue}if(!g||g.length===0||!h){console.warn("Character item missing sprites or transformId:",d);continue}let I=g.map(({resourceId:C})=>C),_=`character-container-${d.id}-${c}-${I.join("-")}`,v=r.transforms[h];if(!v){console.warn("Transform not found:",h);continue}let L={type:"container",id:_,x:d.x??v.x,y:d.y??v.y,anchorX:v.anchorX,anchorY:v.anchorY,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY,children:[]};for(let C of g){let T=r.images[C.resourceId];if(!T){console.warn(`Image resource not found: ${C.resourceId}`);continue}L.children.push({type:"sprite",id:`${_}-${C.id}`,src:T.fileId,width:T.width,height:T.height,x:0,y:0})}l.children.push(L),d.animations&&!o&&!i&&H({animations:u,animationsDef:d.animations,resources:r,previousResourceId:m,currentResourceId:b,idPrefix:"character",targetId:_})}}return e},Fn=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:a})=>{let{elements:u,animations:l}=e;if(t.visual&&r){let s=u.find(c=>c.id==="story");if(!s)return e;let f=t.visual.items;for(let c of f){if(c.resourceId){let{images:d={},videos:h={},spritesheets:g={}}=r,y=g[c.resourceId];if(y){let m=r.transforms?.[c.transformId]||{},b=c.animationName;if(b){let I=y.animations?.[b];if(!I)throw new Error(`Animation '${b}' not found in spritesheet resource '${c.resourceId}'`);let _={id:`visual-${c.id}`,type:"animated-sprite",x:c.x??m.x??0,y:c.y??m.y??0,width:c.width??y.width,height:c.height??y.height,alpha:c.alpha??1,anchorX:m.anchorX,anchorY:m.anchorY,rotation:m.rotation,scaleX:m.scaleX,scaleY:m.scaleY,spritesheetSrc:y.fileId,spritesheetData:y.jsonData,animation:{frames:I.frames,animationSpeed:c.animationSpeed??I.animationSpeed??.5,loop:c.loop??I.loop??!0}};s.children.push(structuredClone(_))}}else{let m=d[c.resourceId]||h[c.resourceId];if(m){let b=h[c.resourceId]!==void 0,I=r.transforms[c.transformId],_={id:`visual-${c.id}`,type:b?"video":"sprite",src:m.fileId,width:m.width,height:m.height,x:I.x,y:I.y,anchorX:I.anchorX,anchorY:I.anchorY,rotation:I.rotation,scaleX:I.scaleX,scaleY:I.scaleY};b&&(_.loop=m.loop??!1,_.volume=m.volume??500),s.children.push(_)}}}if(c.resourceId){let{layouts:d={}}=r,h=d[c.resourceId];if(h){let g=r.transforms[c.transformId],y={id:`visual-${c.id}`,type:"container",children:structuredClone(h.elements),x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY},m=P(y,{variables:a},{functions:Y});s.children.push(m)}}if(c.animations&&!o&&!i){let h=(n?.visual?.items||[]).find(g=>g.id===c.id);H({animations:l,animationsDef:c.animations,resources:r,previousResourceId:h?.resourceId,currentResourceId:c.resourceId,idPrefix:c.id,targetId:`visual-${c.id}`})}}}return e},jn=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:a,canRollback:u,skipOnlyViewedLines:l,isLineCompleted:s,skipTransitionsAndAnimations:f,l10n:c,variables:d,saveSlots:h=[]})=>{let{elements:g,animations:y}=e;if(!t.dialogue||o)return e;let m=g.find(b=>b.id==="story");if(!m)return e;if(t.dialogue.gui&&t.dialogue.gui.resourceId){let{layouts:b={}}=r,I=b[t.dialogue.gui.resourceId];if(I){let _;t.dialogue.characterId&&(_=r.characters[t.dialogue.characterId]),t.dialogue.character&&(_={..._,name:t.dialogue.character.name});let v={elements:I.elements},L={variables:d,autoMode:i,skipMode:a,canRollback:u,skipOnlyViewedLines:l,isLineCompleted:s,saveSlots:h,effectiveSoundVolume:d?._muteAll?0:d?._soundVolume??500,textSpeed:d?._textSpeed??50,dialogue:{character:{name:_?.name||""},content:(t.dialogue?.content||[{text:""}]).map(V=>({...V,text:pt(V.text,{variables:d,l10n:c})})),lines:(t.dialogue?.lines||[]).map(V=>({content:V.content?.map(Ve=>({...Ve,text:pt(Ve.text,{variables:d,l10n:c})})),characterName:V.characterId&&r.characters?.[V.characterId]?.name||""}))},l10n:c},C=P(v,L,{functions:Y});C=P(C,{l10n:c});let T=C?.elements;if(Array.isArray(T))for(let V of T)m.children.push(structuredClone(V));else T&&m.children.push(structuredClone(T))}}return t.dialogue.gui?.animations&&!s&&!f&&H({animations:y,animationsDef:t.dialogue.gui.animations,resources:r,previousResourceId:n?.dialogue?.gui?.resourceId,currentResourceId:t.dialogue.gui?.resourceId,idPrefix:"dialogue-gui",targetId:"dialogue-container"}),e},Un=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,screen:a})=>{let{elements:u,animations:l}=e;if(t.choice&&r){let s=u.find(c=>c.id==="story");if(!s)return e;s.children.push({id:"choice-blocker",type:"rect",fill:"transparent",width:a.width,height:a.height,x:0,y:0,click:{actionPayload:{actions:{}}}});let f=r?.layouts[t.choice.resourceId];if(f&&f.elements){let c={elements:f.elements},h=P(c,{choice:{items:t.choice?.items??[]}})?.elements;if(Array.isArray(h))for(let g of h)s.children.push(structuredClone(g));else h&&s.children.push(structuredClone(h))}t.choice.animations&&!o&&!i&&H({animations:l,animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,idPrefix:"choice",targetId:"choice-container"})}return e},Wn=(e,{presentationState:t,resources:n})=>{if(t.keyboard?.resourceId){let r=n?.keyboards?.[t.keyboard.resourceId];r&&(e.global.keyboard=r)}return e},zn=(e,{presentationState:t,resources:n,variables:r})=>{let{elements:o,audio:i}=e;if(t.bgm&&n){if(!o.find(s=>s.id==="story"))return e;let u=n.sounds[t.bgm.resourceId];if(!u)return e;let l=r?._muteAll?0:r?._musicVolume??500;i.push({id:"bgm",type:"sound",src:u.fileId,loop:t.bgm.loop??!0,volume:l,delay:t.bgm.delay??null})}return e},Yn=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let a=n.sounds?.[i.resourceId];a&&r.push({id:i.id,type:"sound",src:a.fileId,loop:i.loop??a.loop??!0,volume:i.volume??a.volume??500,delay:i.delay??a.delay??null})}}return e},Hn=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:o,volume:i,loop:a}=t.voice;return r.push({id:`voice-${o}`,type:"sound",src:o,volume:i??500,loop:a??!1}),e},Kn=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:a,canRollback:u,currentLocalizationPackageId:l,saveSlots:s=[],isLineCompleted:f,skipTransitionsAndAnimations:c})=>{let{elements:d,animations:h}=e;if(t.layout){let g=d.find(v=>v.id==="story");if(!g)return e;let y=r.layouts[t.layout.resourceId];if(!y)return e;Array.isArray(y.transitions)&&!f&&!c&&y.transitions.forEach(v=>{h.push(v)});let m={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:y.elements||[]},b={variables:o,saveSlots:s,autoMode:i,skipMode:a,canRollback:u,currentLocalizationPackageId:l,effectiveSoundVolume:o?._muteAll?0:o?._soundVolume??500,textSpeed:o?._textSpeed??50},I=P(m,b,{functions:Y});I=P(I,{i18n:{}});let _=v=>{let L={...v};return v.src&&v.src.startsWith("file:")&&(L.src=v.src),v.children&&Array.isArray(v.children)&&(L.children=v.children.map(_)),L};g.children.push(_(I))}if(t.layout?.animations&&!f&&!c){let g=n?.layout?.resourceId,y=t.layout?.resourceId;H({animations:h,animationsDef:t.layout.animations,resources:r,previousResourceId:g,currentResourceId:y,idPrefix:"layout",targetId:`layout-${y}`,outTargetId:`layout-${g}`})}return e},Jn=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,canRollback:i,currentLocalizationPackageId:a,layeredViews:u=[],dialogueHistory:l=[],saveSlots:s=[],l10n:f,screen:c})=>{let{elements:d,animations:h}=e;return u&&u.length>0&&u.forEach((g,y)=>{let m=t.layouts[g.resourceId];if(!m){console.warn(`LayeredView layout not found: ${g.resourceId}`);return}Array.isArray(m.transitions)&&m.transitions.forEach(L=>{h.push(L)});let b={id:`layeredView-${y}`,type:"container",x:0,y:0,children:[{id:`layeredView-${y}-blocker`,type:"rect",fill:"transparent",width:c.width,height:c.height,x:0,y:0,click:{actionPayload:{actions:{}}}},...m.elements||[]]},I=l.map(L=>{let C=t.characters?.[L.characterId];return{...L,characterName:C?.name||""}}),_={variables:n,autoMode:r,skipMode:o,canRollback:i,currentLocalizationPackageId:a,saveSlots:s,effectiveSoundVolume:n?._muteAll?0:n?._soundVolume??500,textSpeed:n?._textSpeed??50,historyDialogue:I,characters:t.characters||{}},v=P(b,_,{functions:Y});v=P(v,{i18n:{},l10n:f}),d.push(v)}),e},ht=e=>le(Vn,[Dn,Mn,Bn,Fn,jn,Un,Wn,Kn,zn,Yn,Hn,Jn])(e);var qn=e=>{let{global:{currentLocalizationPackageId:t,saveSlots:n={},variables:r={}},projectData:o}=e,i=o.story.initialSceneId,a=o.story.scenes[i],u=a.initialSectionId,l=a.sections[u],s={sceneId:i,sectionId:u,lineId:l.initialLineId??l.lines[0].id},{contextVariableDefaultValues:f,globalVariablesDefaultValues:c}=qe(o),d={...c,...r};return{projectData:o,global:{isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isDialogueHistoryShowing:!1,currentLocalizationPackageId:t,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1}},saveSlots:n,layeredViews:[],variables:d},contexts:[{currentPointerMode:"read",pointers:{read:s,history:{sectionId:void 0,lineId:void 0,historySequenceIndex:void 0}},historySequence:[{sectionId:s.sectionId,initialState:{...f},lines:[{id:s.lineId}]}],configuration:{},views:[],bgm:{resourceId:void 0},variables:f}]}},Xn=({state:e})=>e.global.layeredViews||[],Gn=({state:e})=>e.global.pendingEffects,gt=({state:e})=>e.global.skipMode,Qn=({state:e})=>e.global.autoMode,yt=({state:e})=>e.global.dialogueUIHidden,ke=({state:e})=>{let t=e.contexts[e.contexts.length-1];if(!t)return[];let{sectionId:n,lineId:r}=t.pointers.read,o=O({state:e},{sectionId:n});if(!o?.lines||!Array.isArray(o.lines))return[];let i=o.lines.findIndex(l=>l.id===r);return o.lines.slice(0,i+1).filter(l=>l.actions?.dialogue).map(l=>{let s=l.actions.dialogue,f="";return s.characterId&&(f=e.projectData.resources?.characters?.[s.characterId]?.name||""),{content:s.content,characterId:s.characterId,characterName:f}})},Zn=({state:e})=>e.global.currentLocalizationPackageId,Re=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(l=>l.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=O({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return!1;let a=i.lines.findIndex(l=>l.id===o.lastLineId),u=i.lines.findIndex(l=>l.id===r);return a===-1||u===-1?o.lastLineId===r:u<a},er=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},tr=({state:e})=>e.global.nextLineConfig,nr=({state:e})=>e.global.saveSlots,rr=({state:e},t)=>{let{slotKey:n}=t;return e.global.saveSlots[n]},J=({state:e})=>{let t=e.contexts[e.contexts.length-1];if(!t)return;let n=t.pointers?.[t.currentPointerMode];return{currentPointerMode:t.currentPointerMode,pointer:n}},O=({state:e},t)=>{let{sectionId:n}=t,r=e.projectData?.story?.scenes||{};for(let o in r){let i=r[o];if(i.sections&&i.sections[n])return i.sections[n]}},mt=({state:e})=>{let t=J({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=O({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},bt=({state:e})=>{let{sectionId:t,lineId:n}=J({state:e}).pointer,o=O({state:e},{sectionId:t})?.lines||[],i=o.findIndex(s=>s.id===n),u=o.slice(0,i+1).map(s=>{let f=s.actions||{},c={};return Object.keys(f).forEach(d=>{c[d]=f[d]}),c});return G(u)},or=({state:e})=>{let t=It({state:e}),r=mt({state:e})?.actions??{},o=G([t??{},r]);return Ae(t??{},o??{})},ir=({state:e},{sectionId:t})=>{let n=O({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let a=i.actions||{},u=G([o,a]),l=Ae(o,u);r.push({id:i.id,changes:l}),o=u}return{lines:r}},It=({state:e})=>{let{sectionId:t,lineId:n}=J({state:e}).pointer,o=O({state:e},{sectionId:t})?.lines||[],i=o.findIndex(l=>l.id===n);if(i<=0)return null;let u=o.slice(0,i).map(l=>{let s=l.actions||{},f={};return Object.keys(s).forEach(c=>{f[c]=s[c]}),f});return G(u)},wt=({state:e},{slotsPerPage:t=6}={})=>{let o=(({...e.global.variables,...e.contexts[e.contexts.length-1].variables}.loadPage??1)-1)*t+1,i=[];for(let a=0;a<t;a++){let u=o+a,l=e.global.saveSlots&&e.global.saveSlots[u]||{};i.push({slotNumber:u,...l})}return{saveSlots:i}},sr=({state:e})=>{let t=bt({state:e}),n=It({state:e}),r={...e.global.variables,...e.contexts[e.contexts.length-1].variables},{saveSlots:o}=wt({state:e});return ht({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,screen:e.projectData.screen,l10n:e.projectData.l10n.packages[e.global.currentLocalizationPackageId],currentLocalizationPackageId:e.global.currentLocalizationPackageId,dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,canRollback:$t({state:e}),skipOnlyViewedLines:!r._skipUnseenText,isLineCompleted:e.global.isLineCompleted,skipTransitionsAndAnimations:!!r._skipTransitionsAndAnimations,layeredViews:e.global.layeredViews,dialogueHistory:ke({state:e}),saveSlots:o,variables:r})},ar=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),e),lr=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),e),cr=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),e),ur=({state:e})=>(e.global.layeredViews=[],e.global.pendingEffects.push({name:"render"}),e),_t=({state:e})=>{if(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted){let t=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:t}})}return e.global.pendingEffects.push({name:"render"}),e},fe=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),fr=({state:e})=>(e.global.autoMode?fe({state:e}):_t({state:e}),e),vt=({state:e})=>(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),K=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),dr=({state:e})=>(gt({state:e})?K({state:e}):vt({state:e}),e),xt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),e),Et=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),e),pr=({state:e})=>(yt({state:e})?xt({state:e}):Et({state:e}),e),hr=({state:e})=>{let t=ke({state:e});return e.global.isDialogueHistoryShowing=!0,e.global.pendingEffects.push({name:"render"}),e},gr=({state:e})=>(e.global.isDialogueHistoryShowing=!1,e.global.pendingEffects.push({name:"render"}),e),yr=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},mr=({state:e})=>(e.global.pendingEffects=[],e),br=({state:e},t)=>(e.global.pendingEffects.push(t),e),At=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(i=>i.sectionId===n);if(o){let i=O({state:e},{sectionId:n});if(i?.lines&&o.lastLineId!==void 0){let a=i.lines.findIndex(l=>l.id===o.lastLineId),u=i.lines.findIndex(l=>l.id===r);(a===-1||u>a)&&(o.lastLineId=r)}else o.lastLineId=r}else e.global.viewedRegistry.sections.push({sectionId:n,lastLineId:r});return e.global.pendingEffects.push({name:"render"}),e},Ir=({state:e},t)=>{let{resourceId:n}=t;return e.global.viewedRegistry.resources.find(o=>o.resourceId===n)||e.global.viewedRegistry.resources.push({resourceId:n}),e.global.pendingEffects.push({name:"render"}),e},wr=({state:e},t)=>{let{manual:n,auto:r}=t,o=e.global.nextLineConfig.auto?.enabled,i=r?.enabled;return n&&r?e.global.nextLineConfig={manual:n,auto:r}:(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r)),i===!0&&!o?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):i===!1&&o&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),e},_r=({state:e},t)=>{let{slot:n,thumbnailImage:r}=t,o=String(n),i={contexts:[...e.contexts],viewedRegistry:e.global.viewedRegistry},a={slotKey:o,date:Date.now(),image:r,state:i};return e.global.saveSlots[o]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},vr=({state:e},t)=>{let{slot:n}=t,r=String(n),o=e.global.saveSlots[r];return o&&(e.global.viewedRegistry=o.state.viewedRegistry,e.contexts=o.state.contexts,e.global.pendingEffects.push({name:"render"})),e},xr=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},Er=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!O({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let a=O({state:e},{sectionId:i});return!a?.lines||!Array.isArray(a.lines)?(console.warn(`Section ${i} has no lines`),e):a.lines.find(l=>l.id===r)?(o.pointers.read={sectionId:i,lineId:r},e.global.isLineCompleted=!1,ee({state:e},{lineId:r}),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},Lt=({state:e},t)=>{let{item:n}=t,r=e.contexts[e.contexts.length-1];if(r&&r.historySequence){let o={...r.variables};r.historySequence.push({sectionId:n.sectionId,initialState:o,lines:[]})}return e.global.pendingEffects.push({name:"render"}),e},ee=({state:e},t)=>{let{lineId:n}=t,r=e.contexts[e.contexts.length-1];if(!r?.historySequence)return e;let o=r.historySequence;if(o.length===0)return e;let i=o[o.length-1];return i.lines||(i.lines=[]),i.lines.push({id:n}),e},Ar=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(!e.global.isLineCompleted){if(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode){let l=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:l}})}let u=e.global.nextLineConfig;return u?.auto?.enabled&&u.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:u.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let t=J({state:e})?.pointer,n=t?.sectionId,o=O({state:e},{sectionId:n})?.lines||[],a=o.findIndex(u=>u.id===t?.lineId)+1;if(a<o.length){let u=o[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!Re({state:e},{sectionId:n,lineId:u.id}))return K({state:e}),e;let s=e.contexts[e.contexts.length-1];if(s){let f=s.pointers.read.lineId;f&&n&&At({state:e},{sectionId:n,lineId:f}),s.pointers.read={sectionId:n,lineId:u.id}}e.global.isLineCompleted=!1,ee({state:e},{lineId:u.id}),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}else e.global.autoMode&&fe({state:e}),e.global.skipMode&&K({state:e});return e},Lr=({state:e})=>{if(e.global.isLineCompleted)return e;if(e.global.isLineCompleted=!0,e.global.autoMode){let n=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:n}})}let t=e.global.nextLineConfig;return t?.auto?.enabled&&t.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:t.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},$r=({state:e},t)=>{let{sectionId:n}=t,r=O({state:e},{sectionId:n});if(!r||!r.lines||r.lines.length===0)return e;let o=r.lines,i=e.contexts[e.contexts.length-1];if(!i||!i.pointers)return e;let a=i.pointers.history||i.pointers.read;if(i.currentPointerMode!=="history"||!i.pointers.history){if(!a)return e;i.currentPointerMode="history",i.pointers.history={sectionId:n,lineId:a?.lineId};let f=o.findIndex(c=>c.id===a.lineId)-1;if(f>=0&&f<o.length){let c=o[f];i.pointers.history={sectionId:n,lineId:c.id}}return e.global.pendingEffects.push({name:"render"}),e}let l=o.findIndex(s=>s.id===i.pointers.history.lineId)-1;if(l>=0&&l<o.length){let s=o[l];i.pointers.history={sectionId:n,lineId:s.id},e.global.pendingEffects.push({name:"render"})}return e},Cr=({state:e},t)=>{let{sectionId:n}=t,r=O({state:e},{sectionId:n});if(!r)return console.warn(`Section not found: ${n}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${n} has no lines`),e;e.global.autoMode&&fe({state:e}),e.global.skipMode&&K({state:e});let i=e.contexts[e.contexts.length-1];return i&&(i.pointers.read={sectionId:n,lineId:o.id},Lt({state:e},{item:{sectionId:n}}),ee({state:e},{lineId:o.id})),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},Sr=({state:e})=>{let t=J({state:e})?.pointer,n=t?.sectionId,o=O({state:e},{sectionId:n})?.lines||[],a=o.findIndex(u=>u.id===t?.lineId)+1;if(a<o.length){let u=o[a],l=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&l&&!Re({state:e},{sectionId:n,lineId:u.id}))return K({state:e}),e;let s=e.contexts[e.contexts.length-1];s&&(s.pointers.read={sectionId:n,lineId:u.id}),e.global.isLineCompleted=!1,ee({state:e},{lineId:u.id}),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e.global.nextLineConfig.auto?.enabled&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Or=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1],i=!1,a=!1,u=!1;if(r.forEach(({variableId:l,op:s,value:f})=>{let c=e.projectData.resources?.variables?.[l],d=c?.scope,h=c?.type;Xe(d,l),Ge(h,s,l);let g=d==="context"?o.variables:e.global.variables;d==="context"?i=!0:d==="global-device"?a=!0:d==="global-account"&&(u=!0),g[l]=xe(g[l],s,f)}),i){let l=o.historySequence;if(l&&l.length>0){let s=l[l.length-1];if(s.lines&&s.lines.length>0){let f=s.lines[s.lines.length-1];f.updateVariableIds||(f.updateVariableIds=[]),f.updateVariableIds.push(n)}}}if(a){let l=Ee(e.global.variables,e.projectData.resources?.variables,"global-device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:l}})}if(u){let l=Ee(e.global.variables,e.projectData.resources?.variables,"global-account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:l}})}return e.global.pendingEffects.push({name:"render"}),e},Oe=(e,t,n="")=>{if(e!=null){if(n==="updateVariable"&&typeof e=="object"&&e.id===t&&Array.isArray(e.operations))return e;if(Array.isArray(e)){for(let r of e){let o=Oe(r,t,n);if(o)return o}return}if(typeof e=="object")for(let r of Object.keys(e)){let o=Oe(e[r],t,r);if(o)return o}}},Pe=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.pointers.read?.sectionId,i=r.pointers.read?.lineId;if(!o||!i)return null;let u=r.historySequence?.find(c=>c.sectionId===o);if(!u?.lines||u.lines.length===0)return null;let l=u.lines.findLastIndex(c=>c.id===i);if(l===-1)return null;let s=l+n;if(s<0||s>=u.lines.length)return null;let f=u.lines[s];return{sectionId:o,lineId:f.id}},$t=({state:e})=>Pe({state:e},{offset:-1})!==null,kr=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=Pe({state:e},{offset:n});return r?Ct({state:e},{sectionId:r.sectionId,lineId:r.lineId}):e},Ct=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let a=o.historySequence?.find(s=>s.sectionId===n);if(!a?.lines)throw new Error(`Section ${n} not found in history or has no lines`);let u=a.lines.findIndex(s=>s.id===r);if(u===-1)throw new Error(`Line ${r} not found in section ${n} history`);let l=a.initialState||{};o.variables={...l};for(let s=0;s<u;s++){let c=a.lines[s].updateVariableIds||[];for(let d of c){let h=Oe(e.projectData,d);if(!h)throw new Error(`Action definition not found for ID: ${d}`);let g=h.operations||[];for(let{variableId:y,op:m,value:b}of g)e.projectData.resources?.variables?.[y]?.scope==="context"&&(o.variables[y]=xe(o.variables[y],m,b))}}return a.lines=a.lines.slice(0,u),a.lines.push({id:r}),o.pointers.read={sectionId:n,lineId:r},o.currentPointerMode="read",o.pointers.history={sectionId:null,lineId:null,historySequenceIndex:null},e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},St=e=>{let t=qn(e);return Je(t,{selectPendingEffects:Gn,selectSkipMode:gt,selectAutoMode:Qn,selectDialogueUIHidden:yt,selectDialogueHistory:ke,selectCurrentLocalizationPackageId:Zn,selectIsLineViewed:Re,selectIsResourceViewed:er,selectNextLineConfig:tr,selectSaveSlots:nr,selectSaveSlot:rr,selectCurrentPointer:J,selectSection:O,selectCurrentLine:mt,selectPresentationState:bt,selectPresentationChanges:or,selectSectionLineChanges:ir,selectCurrentPageSlots:wt,selectRenderState:sr,selectLayeredViews:Xn,selectLineIdByOffset:Pe,selectCanRollback:$t,startAutoMode:_t,stopAutoMode:fe,toggleAutoMode:fr,startSkipMode:vt,stopSkipMode:K,toggleSkipMode:dr,showDialogueUI:xt,hideDialogueUI:Et,toggleDialogueUI:pr,showDialogueHistory:hr,hideDialogueHistory:gr,setCurrentLocalizationPackageId:yr,clearPendingEffects:mr,appendPendingEffect:br,addViewedLine:At,addViewedResource:Ir,setNextLineConfig:wr,saveSaveSlot:_r,loadSaveSlot:vr,updateProjectData:xr,sectionTransition:Cr,jumpToLine:Er,addToHistorySequence:Lt,addLineToHistory:ee,nextLine:Ar,markLineCompleted:Lr,prevLine:$r,rollbackToLine:Ct,rollbackByOffset:kr,pushLayeredView:ar,popLayeredView:lr,replaceLastLayeredView:cr,clearLayeredViews:ur,updateVariable:Or,nextLineFromSystem:Sr},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Te(e){let t,{handlePendingEffects:n}=e,r=()=>{for(;t.selectPendingEffects().length>0;){let y=[...t.selectPendingEffects()];t.clearPendingEffects(),n(y)}},o=({initialState:y})=>{t=St(y),t.appendPendingEffect({name:"render"}),g(),r()},i=()=>t.selectPresentationState(),a=()=>t.selectPresentationChanges(),u=y=>t.selectSectionLineChanges(y),l=()=>t.selectRenderState(),s=()=>t.selectSaveSlots(),f=()=>t.selectSkipMode(),c=()=>t.selectAutoMode(),d=(y,m)=>{t[y]&&(t[y](m),r())},h=y=>{Object.entries(y).forEach(([m,b])=>{d(m,b)})},g=()=>{let y=t.selectCurrentLine();y?.actions&&h(y.actions)};return{init:o,handleAction:d,handleActions:h,selectRenderState:l,selectPresentationState:i,selectPresentationChanges:a,selectSectionLineChanges:u,selectSaveSlots:s,handleLineActions:g}}var Ne=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Rr=({engine:e,routeGraphics:t},n)=>{let r=e.selectRenderState();t.render(r)},Pr=({engine:e},t)=>{e.handleLineActions()},Tr=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=a=>{n.addElapsed(a.deltaMS);let u=r.delay??1e3;n.getElapsed()>=u&&(t.remove(i),n.setCallback(null),n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Nr=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Vr=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=a=>{n.addElapsed(a.deltaMS),n.getElapsed()>=30&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Dr=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Mr=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=a=>{n.addElapsed(a.deltaMS);let u=r.delay??1e3;n.getElapsed()>=u&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Br=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Fr=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},jr=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Ur=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},Wr={render:Rr,saveSlots:Fr,saveGlobalDeviceVariables:jr,saveGlobalAccountVariables:Ur,handleLineActions:Pr,startAutoNextTimer:Tr,clearAutoNextTimer:Nr,startSkipNextTimer:Vr,clearSkipNextTimer:Dr,nextLineConfigTimer:Mr,clearNextLineConfigTimer:Br},zr=({getEngine:e,routeGraphics:t,ticker:n})=>{let r=Ne(),o=Ne(),i=Ne();return async a=>{let u=e(),l=a.reduce((c,d)=>(c[d.name]=d,c),{}),s=Object.values(l),f={engine:u,routeGraphics:t,ticker:n,autoTimer:r,skipTimer:o,nextLineConfigTimerState:i};for(let c of s){let d=Wr[c.name];d&&d(f,c.payload)}}},Yr=zr;var Fo=Te;export{Yr as createEffectsHandler,Fo as default};
|
|
1
|
+
var Nt=Object.defineProperty;var Pt=(e,t)=>{for(var n in t)Nt(e,n,{get:t[n],enumerable:!0})};var ze=Symbol.for("immer-nothing"),Be=Symbol.for("immer-draftable"),R=Symbol.for("immer-state");function P(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var W=Object.getPrototypeOf;function z(e){return!!e&&!!e[R]}function B(e){return e?Ye(e)||Array.isArray(e)||!!e[Be]||!!e.constructor?.[Be]||se(e)||le(e):!1}var Vt=Object.prototype.constructor.toString();function Ye(e){if(!e||typeof e!="object")return!1;let t=W(e);if(t===null)return!0;let n=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return n===Object?!0:typeof n=="function"&&Function.toString.call(n)===Vt}function ne(e,t){ie(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function ie(e){let t=e[R];return t?t.type_:Array.isArray(e)?1:se(e)?2:le(e)?3:0}function ge(e,t){return ie(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function He(e,t,n){let r=ie(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Dt(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function se(e){return e instanceof Map}function le(e){return e instanceof Set}function M(e){return e.copy_||e.base_}function ye(e,t){if(se(e))return new Map(e);if(le(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Ye(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[R];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let l=o[i],c=r[l];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(r[l]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[l]})}return Object.create(W(e),r)}else{let r=W(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function _e(e,t=!1){return ae(e)||z(e)||!B(e)||(ie(e)>1&&(e.set=e.add=e.clear=e.delete=Mt),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>_e(r,!0))),e}function Mt(){P(2)}function ae(e){return Object.isFrozen(e)}var Bt={};function F(e){let t=Bt[e];return t||P(0,e),t}var X;function qe(){return X}function Ft(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Fe(e,t){t&&(F("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function me(e){be(e),e.drafts_.forEach(jt),e.drafts_=null}function be(e){e===X&&(X=e.parent_)}function je(e){return X=Ft(X,e)}function jt(e){let t=e[R];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Ue(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[R].modified_&&(me(t),P(4)),B(e)&&(e=re(t,e),t.parent_||oe(t,e)),t.patches_&&F("Patches").generateReplacementPatches_(n[R].base_,e,t.patches_,t.inversePatches_)):e=re(t,n,[]),me(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==ze?e:void 0}function re(e,t,n){if(ae(t))return t;let r=t[R];if(!r)return ne(t,(o,i)=>We(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return oe(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,l=!1;r.type_===3&&(i=new Set(o),o.clear(),l=!0),ne(i,(c,a)=>We(e,r,o,c,a,n,l)),oe(e,o,!1),n&&e.patches_&&F("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function We(e,t,n,r,o,i,l){if(z(o)){let c=i&&t&&t.type_!==3&&!ge(t.assigned_,r)?i.concat(r):void 0,a=re(e,o,c);if(He(n,r,a),z(a))e.canAutoFreeze_=!1;else return}else l&&n.add(o);if(B(o)&&!ae(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;re(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&oe(e,o)}}function oe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&_e(t,n)}function Ut(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:qe(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=xe;n&&(o=[r],i=G);let{revoke:l,proxy:c}=Proxy.revocable(o,i);return r.draft_=c,r.revoke_=l,c}var xe={get(e,t){if(t===R)return e;let n=M(e);if(!ge(n,t))return Wt(e,n,t);let r=n[t];return e.finalized_||!B(r)?r:r===pe(e.base_,t)?(he(e),e.copy_[t]=we(r,e)):r},has(e,t){return t in M(e)},ownKeys(e){return Reflect.ownKeys(M(e))},set(e,t,n){let r=Ke(M(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=pe(M(e),t),i=o?.[R];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Dt(n,o)&&(n!==void 0||ge(e.base_,t)))return!0;he(e),Ie(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return pe(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,he(e),Ie(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=M(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){P(11)},getPrototypeOf(e){return W(e.base_)},setPrototypeOf(){P(12)}},G={};ne(xe,(e,t)=>{G[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});G.deleteProperty=function(e,t){return G.set.call(this,e,t,void 0)};G.set=function(e,t,n){return xe.set.call(this,e[0],t,n,e[0])};function pe(e,t){let n=e[R];return(n?M(n):e)[t]}function Wt(e,t,n){let r=Ke(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Ke(e,t){if(!(t in e))return;let n=W(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=W(n)}}function Ie(e){e.modified_||(e.modified_=!0,e.parent_&&Ie(e.parent_))}function he(e){e.copy_||(e.copy_=ye(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var zt=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let i=n;n=t;let l=this;return function(a=i,...s){return l.produce(a,f=>n.call(this,f,...s))}}typeof n!="function"&&P(6),r!==void 0&&typeof r!="function"&&P(7);let o;if(B(t)){let i=je(this),l=we(t,void 0),c=!0;try{o=n(l),c=!1}finally{c?me(i):be(i)}return Fe(i,r),Ue(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===ze&&(o=void 0),this.autoFreeze_&&_e(o,!0),r){let i=[],l=[];F("Patches").generateReplacementPatches_(t,o,i,l),r(i,l)}return o}else P(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(l,...c)=>this.produceWithPatches(l,a=>t(a,...c));let r,o;return[this.produce(t,n,(l,c)=>{r=l,o=c}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){B(e)||P(8),z(e)&&(e=Yt(e));let t=je(this),n=we(e,void 0);return n[R].isManual_=!0,be(t),n}finishDraft(e,t){let n=e&&e[R];(!n||!n.isManual_)&&P(9);let{scope_:r}=n;return Fe(r,t),Ue(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));let r=F("Patches").applyPatches_;return z(e)?r(e,t):this.produce(e,o=>r(o,t))}};function we(e,t){let n=se(e)?F("MapSet").proxyMap_(e,t):le(e)?F("MapSet").proxySet_(e,t):Ut(e,t);return(t?t.scope_:qe()).drafts_.push(n),n}function Yt(e){return z(e)||P(10,e),Je(e)}function Je(e){if(!B(e)||ae(e))return e;let t=e[R],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=ye(e,t.scope_.immer_.useStrictShallowCopy_)}else n=ye(e,!0);return ne(n,(r,o)=>{He(n,r,Je(o))}),t&&(t.finalized_=!1),n}var T=new zt,ve=T.produce,eo=T.produceWithPatches.bind(T),to=T.setAutoFreeze.bind(T),no=T.setUseStrictShallowCopy.bind(T),ro=T.applyPatches.bind(T),oo=T.createDraft.bind(T),io=T.finishDraft.bind(T);var p={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},E={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},Q={NOT:0};var w=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},S=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var Ee=e=>{if(!e||e.trim()==="")throw new w("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new w(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${n}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let n of t)if(e.trim().endsWith(n))throw new w(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Xe=e=>{if(e.trim().endsWith(" in"))throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new w(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new w(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(o=>o.trim()):[t.trim()];for(let o of r){if(!o)throw new w(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new w(`Invalid loop syntax (got: '$for ${e}')`)}};var Ge=(e,t,n=!1)=>{if(t===null)return new S(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new S(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new S(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new S(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Qe=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new S(`Unknown function '${e}' (${n})`)};var Ht=(e,t,n={})=>{let r={},o={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},o=n.partials||{}):typeof n=="object"&&(r=n));let l=v(e,{functions:r,partials:o},t,{});return l===void 0?{}:l},v=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return L(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return L(e.path,n,r);if(e.type===p.INTERPOLATION)return Kt(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return et(e,t,n,r);case p.BINARY:return tt(e,t,n,r);case p.UNARY:return nt(e,t,n,r);case p.CONDITIONAL:return Xt(e,t,n,r);case p.LOOP:return tn(e,t,n,r);case p.OBJECT:return rn(e,t,n,r);case p.ARRAY:return on(e,t,n,r);case p.PARTIAL:return sn(e,t,n,r);case p.PATH_REFERENCE:return ln(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Ze=new Map,qt=e=>{let t=[],n="",r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(i==="]"){if(r&&n){let l=n.trim();if(/^\d+$/.test(l))t.push({type:"index",value:parseInt(l,10)});else if(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'")){let c=l.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:l});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},L=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Ze.get(e);if(!r){let i=[],l="",c=0;for(let a=0;a<e.length;a++){let s=e[a];s==="["?(c++,l+=s):s==="]"?(c--,l+=s):s==="."&&c===0?l&&(i.push(l),l=""):l+=s}l&&i.push(l),r=[];for(let a of i){let s=qt(a.trim());r.push(...s)}Ze.set(e,r)}let o=t;for(let i=0;i<r.length;i++){let l=r[i];if(l.type==="property"&&l.value in n){o=n[l.value];continue}if(o==null)return;(l.type==="property"||l.type==="index")&&(o=o[l.value])}return o},Kt=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let l=v(i,t,n,r);o.push(l!=null?String(l):"")}return o.join("")},et=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw Qe(e.name,o);let l=e.args.map(c=>v(c,t,n,r));return i(...l)},Y=(e,t,n,r)=>{if(e.var&&!e.type)return L(e.var,n,r);switch(e.type){case p.VARIABLE:return L(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return tt(e,t,n,r);case p.UNARY:return nt(e,t,n,r);case p.FUNCTION:return et(e,t,n,r);default:return v(e,t,n,r)}},tt=(e,t,n,r)=>{if(e.op===E.AND||e.op===E.OR){let l=Y(e.left,t,n,r),c=Y(e.right,t,n,r);switch(e.op){case E.AND:return l&&c;case E.OR:return l||c}}let o=v(e.left,t,n,r),i=v(e.right,t,n,r);switch(e.op){case E.EQ:return o==i;case E.NEQ:return o!=i;case E.GT:return o>i;case E.LT:return o<i;case E.GTE:return o>=i;case E.LTE:return o<=i;case E.IN:return Array.isArray(i)?i.includes(o):!1;case E.ADD:if(typeof o!="number"||typeof i!="number")throw new S(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case E.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new S(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},nt=(e,t,n,r)=>{let o=e.op===Q.NOT?Y(e.operand,t,n,r):v(e.operand,t,n,r);if(e.op===Q.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Jt=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(L(o.path,n,r)){let l=e.bodies[0];if(l.type===p.OBJECT&&l.properties.length<=5){let c={};for(let a of l.properties){let s=a.parsedKey?v(a.parsedKey,t,n,r):a.key,f=a.value;if(f.type===p.LITERAL)c[s]=f.value;else if(f.type===p.VARIABLE)c[s]=L(f.path,n,r);else if(f.type===p.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===p.VARIABLE){let h=L(d.path,n,r);u.push(h!=null?String(h):"")}else{let h=v(d,t,n,r);u.push(h!=null?String(h):"")}c[s]=u.join("")}else c[s]=v(f,t,n,r)}return c}}else{let l=e.bodies[1];if(l.type===p.OBJECT&&l.properties.length<=5){let c={};for(let a of l.properties){let s=a.parsedKey?v(a.parsedKey,t,n,r):a.key,f=a.value;if(f.type===p.LITERAL)c[s]=f.value;else if(f.type===p.VARIABLE)c[s]=L(f.path,n,r);else if(f.type===p.INTERPOLATION){let u=[];for(let d of f.parts)if(typeof d=="string")u.push(d);else if(d.type===p.VARIABLE){let h=L(d.path,n,r);u.push(h!=null?String(h):"")}else{let h=v(d,t,n,r);u.push(h!=null?String(h):"")}c[s]=u.join("")}else c[s]=v(f,t,n,r)}return c}}}return null},Xt=(e,t,n,r)=>{let o=Jt(e,t,n,r);if(o!==null)return o;for(let i=0;i<e.conditions.length;i++){let l=e.conditions[i];if(l===null||Y(l,t,n,r))return v(e.bodies[i],t,n,r)}return rt},Gt=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===p.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===p.VARIABLE){let o=n.conditions[0].path,i=n.bodies[0];if(o.startsWith(r+".")){let l=o.substring(r.length+1);if(i.type===p.OBJECT&&i.properties.length<=5){for(let a of i.properties)if(a.parsedKey)return null;let c=[];for(let a=0;a<t.length;a++){let s=t[a];if(s[l]){let f={};for(let u of i.properties){let d=u.key,h=u.value;if(h.type===p.LITERAL)f[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)f[d]=s;else if(g.startsWith(r+".")){let m=g.substring(r.length+1);f[d]=s[m]}else return null}else if(h.type===p.INTERPOLATION){let g=[],m=!0;for(let y of h.parts)if(typeof y=="string")g.push(y);else if(y.type===p.VARIABLE){let b=y.path;if(b===r)g.push(s!=null?String(s):"");else if(b.startsWith(r+".")){let I=b.substring(r.length+1),_=s[I];g.push(_!=null?String(_):"")}else{m=!1;break}}else{m=!1;break}if(!m)return null;f[d]=g.join("")}else return null}c.push(f)}}return c}}}return null},Qt=(e,t)=>{let n=e.body,r=e.itemVar,o=Gt(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let c of n.properties)if(c.parsedKey)return null;let i=[],l=!0;for(let c of n.properties){let a=c.key,s=c.value;if(s.type===p.LITERAL)i.push({key:a,type:"literal",value:s.value});else if(s.type===p.VARIABLE){let f=s.path;if(f===r)i.push({key:a,type:"item"});else if(f.startsWith(r+".")){let u=f.substring(r.length+1);if(!u.includes(".")&&!u.includes("["))i.push({key:a,type:"prop",prop:u});else{l=!1;break}}else{l=!1;break}}else if(s.type===p.INTERPOLATION&&s.parts.length===1){let f=s.parts[0];if(f.type===p.VARIABLE){let u=f.path;if(u===r)i.push({key:a,type:"item_string"});else if(u.startsWith(r+".")){let d=u.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:a,type:"prop_string",prop:d});else{l=!1;break}}else{l=!1;break}}else{l=!1;break}}else{l=!1;break}}if(l){let c=new Array(t.length);if(i.length===3&&i[0].type==="prop"&&i[0].key==="id"&&i[1].type==="prop_string"&&i[1].key==="title"&&i[2].type==="prop"&&i[2].key==="completed")for(let a=0;a<t.length;a++){let s=t[a];c[a]={id:s.id,title:s.title!=null?String(s.title):"",completed:s.completed}}else for(let a=0;a<t.length;a++){let s=t[a],f={};for(let u of i)if(u.type==="literal")f[u.key]=u.value;else if(u.type==="item")f[u.key]=s;else if(u.type==="prop")f[u.key]=s[u.prop];else if(u.type==="item_string")f[u.key]=s!=null?String(s):"";else if(u.type==="prop_string"){let d=s[u.prop];f[u.key]=d!=null?String(d):""}c[a]=f}return c}}return null},Zt=(e,t,n,r,o)=>{let i=[],l=e.body;if(l.type===p.OBJECT&&l.fast!==!1){let c=e.itemVar,a=e.indexVar;for(let s=0;s<o.length;s++){let f=o[s],u={},d={...r,[c]:f,...a&&{[a]:s}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let g=h.split("."),m=g[0];m in r.__paths__&&(h=r.__paths__[m],g.length>1&&(h+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${h}[${s}]`,...a&&{[a]:s}};for(let g of l.properties){let m=g.parsedKey?v(g.parsedKey,t,n,d):g.key,y=g.value;if(y.type===p.LITERAL)u[m]=y.value;else if(y.type===p.VARIABLE){let b=y.path;if(b===c)u[m]=f;else if(b===a)u[m]=s;else if(b.startsWith(c+".")){let I=b.substring(c.length+1);!I.includes(".")&&!I.includes("[")?u[m]=f[I]:u[m]=L(b,n,{...r,[c]:f,...a&&{[a]:s}})}else u[m]=L(b,n,{...r,[c]:f,...a&&{[a]:s}})}else if(y.type===p.INTERPOLATION){let b=[];for(let I of y.parts)if(typeof I=="string")b.push(I);else if(I.type===p.VARIABLE){let _=I.path,x;if(_===c)x=f;else if(_===a)x=s;else if(_.startsWith(c+".")){let A=_.substring(c.length+1);!A.includes(".")&&!A.includes("[")?x=f[A]:x=L(_,n,{...r,[c]:f,...a&&{[a]:s}})}else x=L(_,n,{...r,[c]:f,...a&&{[a]:s}});b.push(x!=null?String(x):"")}else{let _={...r,[c]:f,...a&&{[a]:s}},x=v(I,t,n,_);b.push(x!=null?String(x):"")}u[m]=b.join("")}else{let b={...r,[c]:f,...a&&{[a]:s}};u[m]=v(y,t,n,b)}}i.push(u)}return i}return null},en=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let i=r.properties[0].value;if(i.type===p.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===p.VARIABLE&&i.conditions[0].path==="item.visible"){let l=i.bodies[0];if(l.type===p.OBJECT&&l.properties.length===2){let c=l.properties[0],a=l.properties[1];if(c.key==="id"&&c.value.type===p.VARIABLE&&c.value.path==="item.id"&&a.key==="$if item.highlighted"&&a.value.type===p.CONDITIONAL){let s=[];for(let f=0;f<t.length;f++){let u=t[f];if(u.visible){let d={id:u.id};u.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${u.name}`):(d.highlight=!1,d.message=u.name),s.push(d)}}return s}}}}return null},tn=(e,t,n,r)=>{let o=v(e.iterable,t,n,r);if(!Array.isArray(o)){let s,f=!1;if(e.iterable.type===p.FUNCTION){f=!0;let d=e.iterable.args.map(h=>h.type===p.LITERAL?typeof h.value=="string"?`'${h.value}'`:String(h.value):h.type===p.VARIABLE?h.path:h.type===p.FUNCTION?`${h.name}(...)`:"?").join(", ");s=`${e.iterable.name}(${d})`}else s=e.iterable.path||"undefined";let u=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${s}`;throw Ge(u,o,f)}if(!e.indexVar){let s=en(e,o,e.itemVar);if(s!==null)return s}if(!e.indexVar){let s=Qt(e,o);if(s!==null)return s}let i=Zt(e,t,n,r,o);if(i!==null)return i;let l=[],c=e.iterable.path||"";if(r&&r.__paths__&&c){let s=c.split("."),f=s[0];f in r.__paths__&&(c=r.__paths__[f],s.length>1&&(c+="."+s.slice(1).join(".")))}let a=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?a=!1:a=e.body._shouldPreserveArray??=e.body.items.some(s=>s.type===p.OBJECT&&s.properties.some(f=>f.key.startsWith("$if ")||f.key.startsWith("$when "))));for(let s=0;s<o.length;s++){let f=e.indexVar?{...r,[e.itemVar]:o[s],[e.indexVar]:s}:{...r,[e.itemVar]:o[s]};f.__paths__||(f.__paths__=r.__paths__||{}),f.__paths__={...f.__paths__,[e.itemVar]:`${c}[${s}]`},e.indexVar&&(f.__paths__[e.indexVar]=s);let u=v(e.body,t,n,f);if(Array.isArray(u)&&u.length===1&&!a){let d=u[0];l.push(d===void 0?{}:d)}else l.push(u===void 0?{}:u)}return l},nn=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?v(o.parsedKey,t,n,r):o.key,l=o.value;if(l.type===p.OBJECT&&l.properties.length<=10&&!l.whenCondition){let c={},a={},s=!0;for(let f of l.properties){let u=f.parsedKey?v(f.parsedKey,t,n,r):f.key,d=f.value;if(d.type===p.LITERAL)a[u]=d.value;else if(d.type===p.VARIABLE)a[u]=L(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let m=L(g.path,n,r);h.push(m!=null?String(m):"")}else{s=!1;break}if(!s)break;a[u]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let m=g.key,y=g.value;if(y.type===p.LITERAL)h[m]=y.value;else if(y.type===p.VARIABLE)h[m]=L(y.path,n,r);else if(y.type===p.INTERPOLATION){let b=[];for(let I of y.parts)if(typeof I=="string")b.push(I);else if(I.type===p.VARIABLE){let _=L(I.path,n,r);b.push(_!=null?String(_):"")}else{s=!1;break}if(!s)break;h[m]=b.join("")}else{s=!1;break}}if(!s)break;a[u]=h}else{s=!1;break}}if(s)return c[i]=a,c}}return null},rn=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!Y(e.whenCondition,o,n,r))return;let i=nn(e,t,n,r);if(i!==null)return i;if(e.fast){let s={};for(let f of e.properties){let u=f.parsedKey?v(f.parsedKey,t,n,r):f.key,d=f.value;if(d.type===p.LITERAL)s[u]=d.value;else if(d.type===p.VARIABLE)s[u]=L(d.path,n,r);else if(d.type===p.INTERPOLATION){let h=[];for(let g of d.parts)if(typeof g=="string")h.push(g);else if(g.type===p.VARIABLE){let m=L(g.path,n,r);h.push(m!=null?String(m):"")}else{let m=v(g,t,n,r);h.push(m!=null?String(m):"")}s[u]=h.join("")}else s[u]=v(d,t,n,r)}return s}let l={},c=null,a=!1;for(let s of e.properties)if(!s.key.startsWith("$if ")&&!s.key.match(/^\$if\s+\w+.*:?$/)&&!s.key.startsWith("$elif")&&!s.key.startsWith("$else")&&!s.key.startsWith("$for ")){a=!0;break}for(let s of e.properties)if(s.key.startsWith("$if ")||s.key.match(/^\$if\s+\w+.*:?$/)){let f=v(s.value,t,n,r);if(!a&&f!==null&&f!==void 0)return Array.isArray(f)&&f.length===1?f[0]:f;typeof f=="object"&&f!==null&&!Array.isArray(f)&&Object.assign(l,f)}else if(s.key.startsWith("$for ")){if(e.properties.length===1)return v(s.value,t,n,r)}else{let f=s.value;if(f&&f.type===p.OBJECT&&f.properties){let u=f.properties.find(d=>d.key.startsWith("$for "));if(u){let d=v(u.value,t,n,r);d!==void 0&&(l[s.key]=d)}else{let d=v(s.value,t,n,r);d!==void 0&&(l[s.key]=d)}}else{let u=s.parsedKey?v(s.parsedKey,t,n,r):s.key,d=v(s.value,t,n,r);d!==void 0&&(l[u]=d)}}return l},rt={},on=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let l=v(i,t,n,r);Array.isArray(l)&&i.flatten!==!1?o.push(...l):o.push(l)}else{let l=v(i,t,n,r);l!==rt&&l!==void 0&&o.push(l)}return o},sn=(e,t,n,r)=>{let{name:o,data:i,whenCondition:l}=e,c=t.partials||{},a=t.functions||t;if(l&&!Y(l,a,n,r))return;if(!c[o])throw new S(`Partial '${o}' is not defined`);let s=r._partialStack||[];if(s.includes(o))throw new S(`Circular partial reference detected: ${o}`);let f=c[o],u=n,d={...r,_partialStack:[...s,o]};if(r){u={...n};for(let h of Object.keys(r))h.startsWith("_")||(u[h]=r[h])}if(i){let h=v(i,t,n,r);u={...u,...h}}return v(f,t,u,d)},ln=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),l=i[0],c=i.slice(1);if(!r||!(l in r))throw new S(`Path reference '#{${o}}' refers to '${l}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(l in r.__paths__))throw new S(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let a=r.__paths__[l];if(typeof a=="number"){if(c.length>0)throw new S(`Path reference '#{${o}}' - cannot access properties on index variable '${l}'`);return String(a)}return c.length>0&&(a+="."+c.join(".")),a},Ae=Ht;var an=/\$\{([^}]*)\}/g,cn=/#\{([^}]*)\}/g,it=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=un(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},un=(e,t={})=>e.trim()?fn(e).map(r=>dn(r.trim(),t)):[],fn=e=>{let t=[],n="",r=0,o=!1,i="";for(let l=0;l<e.length;l++){let c=e[l],a=l>0?e[l-1]:"";!o&&(c==='"'||c==="'")?(o=!0,i=c,n+=c):o&&c===i&&a!=="\\"?(o=!1,i="",n+=c):!o&&c==="("?(r++,n+=c):!o&&c===")"?(r--,n+=c):!o&&c===","&&r===0?(t.push(n),n=""):n+=c}return n&&t.push(n),t},dn=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:p.LITERAL,value:parseFloat(e)};if(e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};let n=it(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),o=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,l=null;for(let{op:c,type:a}of o){let s=0;for(;s<r.length;){let f=j(r.substring(s),c);if(f===-1)break;let u=s+f;u>i&&(i=u,l={op:c,type:a}),s=u+c.length}}if(i!==-1)try{return C(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},st=/^\w+\(.*\)$/,pn=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,hn=e=>{if(!(!e||e.trim()===""||st.test(e))&&pn.test(e))throw e.includes("?")&&e.includes(":")?new w(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new w(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new w(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},ot=e=>{let t=e.trim();if(st.test(t))throw new w(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new w(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new w(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new w(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new w(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:p.PATH_REFERENCE,path:t}},Z=(e,t={})=>{let n=e.trim();hn(n);let r=it(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let o=0;for(let i of n)i==="["?o++:i==="]"&&o--;if(o!==0)throw new Error("Invalid array index syntax")}return{type:p.VARIABLE,path:n}},Le=(e,t={})=>{let n=e,r=[];(e.includes("\\${")||e.includes("\\#{"))&&(n=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),n=n.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),n=n.replace(/\\(\$\{[^}]*\})/g,(s,f)=>{let u=`__ESCAPED_${r.length}__`;return r.push(f),u}),n=n.replace(/\\(#\{[^}]*\})/g,(s,f)=>{let u=`__ESCAPED_${r.length}__`;return r.push(f),u}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(an)],i=[...n.matchAll(cn)],l=[...o.map(s=>({match:s,type:"variable"})),...i.map(s=>({match:s,type:"pathref"}))].sort((s,f)=>s.match.index-f.match.index);if(l.length===0){let s=n;for(let f=0;f<r.length;f++)s=s.replace(`__ESCAPED_${f}__`,r[f]);return{type:p.LITERAL,value:s}}if(l.length===1&&l[0].match[0]===n&&r.length===0){let{match:s,type:f}=l[0];try{return f==="variable"?Z(s[1],t):ot(s[1])}catch(u){if(u.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw u}}let c=[],a=0;for(let{match:s,type:f}of l){let[u,d]=s,h=s.index;if(h>a){let g=n.substring(a,h);for(let m=0;m<r.length;m++)g=g.replace(`__ESCAPED_${m}__`,r[m]);g&&c.push(g)}try{let g;f==="variable"?g=Z(d.trim(),t):g=ot(d.trim()),c.push(g)}catch(g){if(g.message==="Invalid array index syntax")c.push(u);else throw g}a=h+u.length}if(a<n.length){let s=n.substring(a);for(let f=0;f<r.length;f++)s=s.replace(`__ESCAPED_${f}__`,r[f]);s&&c.push(s)}return{type:p.INTERPOLATION,parts:c}};var D=(e,t)=>typeof e=="string"?Le(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?yn(e,t):mn(e,t):{type:p.LITERAL,value:e},gn=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new w("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new w("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new w("Empty $each body not allowed");if(n.$partial!==void 0)throw new w("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},yn=(e,t)=>{let n=[],r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){if(i.$each!==void 0)try{let a=gn(i),s=Object.keys(a);if(s.length===1&&/^\$for(?::\w+)?\s/.test(s[0])){let f=lt(s[0],a[s[0]],t,!0);n.push(f),r=!0;continue}}catch(a){throw a instanceof w?a:new w(a.message)}let c=Object.keys(i);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let a=lt(c[0],i[c[0]],t);n.push(a),r=!0;continue}}let l=D(i,t);n.push(l),(l.type===p.FUNCTION||l.type===p.CONDITIONAL||l.type===p.LOOP||l.type===p.PARTIAL||l.type===p.OBJECT&&!l.fast||l.type===p.ARRAY&&!l.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},mn=(e,t)=>{let n=[],r=!1,o=null,i=Object.entries(e),l=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new w("$partial value must be a string");if(e.$partial.trim()==="")throw new w("$partial value cannot be an empty string");let a=["$if","$elif","$else","$for"],s=[];for(let[b]of i)for(let I of a)if(b===I||b.startsWith(I+" ")||b.startsWith(I+"#")){s.push(I);break}if(s.length>0)throw new w(`Cannot use $partial with ${s.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:f,$when:u,...d}=e,h={},g=!1;for(let[b,I]of Object.entries(d)){let _=b;(b.startsWith("\\$")||b.startsWith("$$"))&&(_=b.slice(1)),h[_]=I,g=!0}let m=null;if(g&&(m=D(h,t),m.type===p.OBJECT)){let b=!1;for(let I of m.properties)if(I.value.type===p.VARIABLE||I.value.type===p.INTERPOLATION||I.value.type===p.FUNCTION||I.value.type===p.CONDITIONAL||I.value.type===p.OBJECT&&!I.value.fast||I.value.type===p.ARRAY&&!I.value.fast){b=!0;break}b&&(m.fast=!1)}let y={type:p.PARTIAL,name:f,data:m};if(u!==void 0){let b;if(typeof u=="string"){if(u.trim()==="")throw new w("Empty condition expression after '$when'");b=C(u,t)}else b={type:p.LITERAL,value:u};y.whenCondition=b}return y}for(let[a,s]of i)if(a==="$when"){if(o!==null)throw new w("Multiple '$when' directives on the same object are not allowed");if(s==null)throw new w("Missing condition expression after '$when'");let f=typeof s=="string"?s:JSON.stringify(s);if(f.trim()==="")throw new w("Empty condition expression after '$when'");o=C(f,t),r=!0}else if(a.startsWith("$when#")||a.startsWith("$when "))throw new w("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;l<i.length;){let[a,s]=i[l];if(a==="$when"){l++;continue}if(a==="$each")throw new w("$each can only be used inside arrays");if(a.startsWith("$if ")||a.match(/^\$if#\w+\s/)||a.match(/^\$if\s+\w+.*:$/)){let f=bn(i,l,t);n.push({key:a,value:f.node}),r=!0,l=f.nextIndex}else if(/^\$for(?::\w+)?\s/.test(a)){let f=a.match(/^\$for(?::(\w+))?\s/)?.[1]||"",u=f?`:${f}`:"";throw new w(`$for loops must be inside arrays - use '- $for${u} item in items:' instead of '$for${u} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(a.startsWith("$elif ")||a.startsWith("$else"))throw new w(`'${a.split(" ")[0]}' without matching '$if'`);if(a==="$if"||a==="$if:")throw new w("Missing condition expression after '$if'");{let f=D(s,t);(f.type===p.FUNCTION||f.type===p.CONDITIONAL||f.type===p.PARTIAL||f.type===p.OBJECT&&!f.fast||f.type===p.ARRAY&&!f.fast)&&(r=!0);let u=Le(a,t),d={key:a,value:f};(u.type!==p.LITERAL||u.value!==a)&&(d.parsedKey=u),n.push(d),l++}}}let c={type:p.OBJECT,properties:n,fast:!r};return o&&(c.whenCondition=o),c},bn=(e,t,n={})=>{let r=[],o=[],i=t,[l,c]=e[i],a=null,s;if(l.startsWith("$if#")){let u=l.match(/^\$if#(\w+)\s+(.+)$/);if(u)a=u[1],s=u[2];else throw new w(`Invalid conditional syntax: ${l}`)}else s=l.substring(4),s.endsWith(":")&&(s=s.slice(0,-1).trim());Ee(s);let f=C(s,n);for(r.push(f),o.push(D(c,n)),i++;i<e.length;){let[u,d]=e[i],h=!1,g;if(a?u.startsWith(`$elif#${a} `)?(g=u.substring(`$elif#${a} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(u===`$else#${a}`||u===`$else#${a}:`)&&(h=!0,g=null):u.startsWith("$elif ")?(g=u.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(u==="$else"||u==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{Ee(g);let m=C(g,n);r.push(m)}if(o.push(D(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:a},nextIndex:i}},C=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let s=e.slice(1,-1),f=0,u=!0;for(let d=0;d<s.length;d++)if(s[d]==="("?f++:s[d]===")"&&f--,f<0){u=!1;break}if(u&&f===0)return C(s,t)}let n=j(e,"||");if(n!==-1)return{type:p.BINARY,op:E.OR,left:C(e.substring(0,n).trim(),t),right:C(e.substring(n+2).trim(),t)};let r=j(e,"&&");if(r!==-1)return{type:p.BINARY,op:E.AND,left:C(e.substring(0,r).trim(),t),right:C(e.substring(r+2).trim(),t)};let o=[{op:">=",type:E.GTE},{op:"<=",type:E.LTE},{op:"==",type:E.EQ},{op:"!=",type:E.NEQ},{op:">",type:E.GT},{op:"<",type:E.LT},{op:" in ",type:E.IN}];for(let{op:s,type:f}of o){let u=j(e,s);if(u!==-1)return{type:p.BINARY,op:f,left:C(e.substring(0,u).trim(),t),right:C(e.substring(u+s.length).trim(),t)}}let i=-1,l=null,c=[{op:" + ",type:E.ADD},{op:" - ",type:E.SUBTRACT}];for(let{op:s,type:f}of c){let u=0;for(;u<e.length;){let d=j(e.substring(u),s);if(d===-1)break;let h=u+d;h>i&&(i=h,l={op:s,type:f}),u=h+s.length}}if(i!==-1&&l)return{type:p.BINARY,op:l.type,left:C(e.substring(0,i).trim(),t),right:C(e.substring(i+l.op.length).trim(),t)};let a=[" * "," / "," % "];for(let s of a)if(j(e,s)!==-1)throw new w(`Arithmetic operations are not allowed in conditionals: "${s}"`);return e.startsWith("!")?{type:p.UNARY,op:Q.NOT,operand:C(e.substring(1).trim(),t)}:at(e,t)},j=(e,t)=>{let n=0,r=0;for(;r<=e.length-t.length;){if(e[r]==="(")n++;else if(e[r]===")")n--;else if(n===0&&e.substring(r,r+t.length)===t)return r;r++}return-1},In=e=>{if(e=e.trim(),e==="true")return{type:p.LITERAL,value:!0};if(e==="false")return{type:p.LITERAL,value:!1};if(e==="null")return{type:p.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:p.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:p.LITERAL,value:""};if(e==="{}")return{type:p.LITERAL,value:{}};if(e==="[]")return{type:p.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:p.LITERAL,value:t}:{type:p.VARIABLE,path:e}},at=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return Z(n,t);let o=In(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return Z(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},wn=(e,t=!1)=>{let n=t?"$each":"$for";try{Xe(e)}catch(r){if(r instanceof w&&t){let o=r.message.replace(/\$for/g,"$each");throw new w(o.replace("Parse Error: ",""))}throw r}},lt=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let y=r?"$each":"$for";throw new w(`Invalid loop syntax (got: '${e.replace("$for",y)}')`)}let l=i[1],c=i[2].trim();wn(c,r);let a=c.match(/^(.+?)\s+in\s+(.+)$/);if(!a){let y=r?"$each":"$for";throw new w(`Invalid loop syntax - missing 'in' keyword (got: '${y} ${c}')`)}let s=a[1].trim(),f=a[2].trim(),u,d=null;if(s.includes(",")){let y=s.split(",").map(b=>b.trim());if(y.length!==2)throw new w(`Invalid loop variables: ${s}. Expected format: "item" or "item, index"`);u=y[0],d=y[1]}else u=s;let h=["this","undefined","null","true","false"];if(h.includes(u))throw new w(`Reserved variable name: ${u}`);if(d&&h.includes(d))throw new w(`Reserved variable name: ${d}`);let g=at(f,n),m=D(t,n);return{type:p.LOOP,itemVar:u,indexVar:d,iterable:g,body:m,flatten:l!=="nested"}};var _n=(e,t={})=>{let{functions:n={}}=t;return D(e,n)},ce=_n;var Ce={};Pt(Ce,{now:()=>xn});var xn=()=>Date.now();var vn=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ce,...r},l=ce(e,{functions:i}),c={};for(let[a,s]of Object.entries(o))c[a]=ce(s,{functions:i});return Ae(l,t,{functions:i,partials:c})},O=vn;var ct=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:l=a=>a,transformActionFirstArgument:c=a=>a}=n;for(let[a,s]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?o[a]=(...f)=>s(l(r),...f):i[a]=(...f)=>{r=ve(r,d=>s(c(d),...f))});return{...o,...i}},ue=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return ve(r,i=>{o.forEach(l=>{t.forEach(c=>{c(i,l)})})})};var En=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string","object"];if(!n.includes(e.type))throw new Error(`Invalid variable type: ${e.type} for variable ${t}. Expected one of: ${n.join(", ")}`);switch(e.type){case"number":return 0;case"boolean":return!1;case"string":return"";case"object":return{}}},ut=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=En(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},ft=(e,t)=>{let n=["context","global-device","global-account"];if(!e)throw new Error(`Variable scope is required for variable: ${t}`);if(!n.includes(e))throw new Error(`Invalid variable scope: ${e} for variable ${t}. Expected one of: ${n.join(", ")}`)},dt=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["set"],object:["set"]},o=r[e];if(!o)throw new Error(`Unknown variable type: ${e} for variable ${n}`);if(!Object.values(r).flat().includes(t))throw new Error(`Unknown operation: ${t}`);if(!o.includes(t))throw new Error(`Operation "${t}" is not valid for variable "${n}" of type "${e}". Valid operations: ${o.join(", ")}`)},Se=(e,t,n)=>{switch(t){case"set":return n;case"multiply":return(e??1)*n;case"divide":return(e??0)/n;case"increment":return(e??0)+(n??1);case"decrement":return(e??0)-(n??1);case"toggle":return!e;default:throw new Error(`Unknown operation: ${t}`)}},Oe=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n)),pt=(e,t="DD/MM/YYYY - HH:mm")=>{if(!e)return"";let n=new Date(e),r=o=>String(o).padStart(2,"0");return t.replace("DD",r(n.getDate())).replace("MM",r(n.getMonth()+1)).replace("YYYY",n.getFullYear()).replace("YY",String(n.getFullYear()).slice(-2)).replace("HH",r(n.getHours())).replace("mm",r(n.getMinutes())).replace("ss",r(n.getSeconds()))},An=(e,t)=>{let n=e?.gui,r=t?.gui;return JSON.stringify(n)===JSON.stringify(r)?null:n&&!r?{changeType:"delete",data:e}:r&&!e?{changeType:"add",data:t}:r&&e?{changeType:"update",data:t}:null},ke=(e={},t={})=>{let n={},r=["sfx","voice"],o=l=>{let c=e[l],a=t[l];a&&!c?n[l]={changeType:"add",data:a}:c&&!a?r.includes(l)||(n[l]={changeType:"delete",data:c}):c&&a&&JSON.stringify(c)!==JSON.stringify(a)&&(n[l]={changeType:"update",data:a})};o("background"),o("base"),o("bgm"),o("voice");let i=An(e.dialogue,t.dialogue);return i&&(n.dialogue=i),o("choice"),o("layout"),o("animation"),o("keyboard"),o("character"),o("visual"),o("sfx"),n},Ln=(e,t)=>{if(!e||!t)return;let n=e;for(let r of t.split(".")){if(n==null||!(r in Object(n)))return;n=n[r]}return n},Cn=(e,t)=>{if(typeof e!="string")return e;if(e==="_event"){if(t==null)throw new Error('Action template binding "_event" requires event context "_event".');return t}if(!e.startsWith("_event."))return e;if(t==null)throw new Error(`Action template binding "${e}" requires event context "_event".`);let n=e.slice(7),r=Ln(t,n);if(r===void 0)throw new Error(`Action template binding "${e}" could not be resolved from "_event".`);return r},$e=(e,t)=>Array.isArray(e)?e.map(n=>$e(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,$e(r,t)])):Cn(e,t),ht=(e,t)=>{if(!t)return e;if(Object.prototype.hasOwnProperty.call(t,"event"))throw new Error('Action template context key "event" is no longer supported. Use "_event".');let n=$e(e,t._event);return O(n,t)};var fe=(e,t)=>e?!t(e)&&e.animations?{animationsOnly:!0,state:{animations:structuredClone(e.animations)}}:{animationsOnly:!1,state:null}:{animationsOnly:!1,state:null},gt=(e,t)=>{if(!e||e.length===0)return{hasValidItems:!1,processedItems:[]};let n=e.map(r=>structuredClone(r)).filter(r=>t(r)||r.animations);return{hasValidItems:n.length>0,processedItems:n}},$n=()=>({}),Sn=(e,t)=>{t.base&&(e.base={...t.base})},On=(e,t)=>{if(t.background){let{animationsOnly:n,state:r}=fe(t.background,o=>!!o.resourceId);if(n){e.background=r;return}if(!t.background.resourceId){delete e.background;return}e.background=structuredClone(t.background)}else e.background?.animations&&(e.background.animations={})},kn=(e,t)=>{if(!t.dialogue){e.dialogue&&e.dialogue.mode==="adv"&&(e.dialogue.content=void 0,e.dialogue.characterId=void 0);return}if(e.dialogue||(e.dialogue={}),t.dialogue.gui){let{animationsOnly:n,state:r}=fe(t.dialogue.gui,o=>!!o.resourceId);n?e.dialogue.gui={...e.dialogue.gui,...r}:e.dialogue.gui={...t.dialogue.gui}}else e.dialogue?.gui?.animations&&(e.dialogue.gui.animations={});if(t.dialogue.mode==="adv"&&(e.dialogue.content=e.dialogue.content||void 0,e.dialogue.characterId=e.dialogue.characterId||void 0,e.dialogue.mode="adv"),t.dialogue.mode==="nvl"&&(e.dialogue?.mode!=="nvl"&&(e.dialogue.lines=[]),e.dialogue.mode="nvl"),t.dialogue.content!==void 0&&(e.dialogue.content=t.dialogue.content),delete e.dialogue.characterId,t.dialogue.characterId&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character&&(e.dialogue.character={...t.dialogue.character}),t.dialogue.clear){delete e.dialogue;return}t.dialogue?.clearPage&&e.dialogue?.mode==="nvl"&&(e.dialogue.lines=[]),t.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&e.dialogue.lines.push({content:t.dialogue.content,characterId:t.dialogue.characterId||null})},Rn=(e,t)=>{if(t.sfx){if(!t.sfx.items||t.sfx.items.length===0){delete e.sfx;return}e.sfx=t.sfx}else e.sfx&&delete e.sfx},Tn=(e,t)=>{if(t.bgm){if(!t.bgm.resourceId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},Nn=(e,t)=>{if(t.visual){let{hasValidItems:n,processedItems:r}=gt(t.visual.items,o=>!!o.resourceId);n?e.visual={items:r}:delete e.visual}else e.visual?.items&&(e.visual.items=e.visual.items.map(n=>n.animations?{...n,animations:{}}:n))},Pn=(e,t)=>{if(!t.character){e.character?.items&&(e.character.items=e.character.items.map(o=>o.animations?{...o,animations:{}}:o));return}let{hasValidItems:n,processedItems:r}=gt(t.character.items,o=>o.sprites&&o.sprites.length>0||o.transformId||o.resourceId);n?e.character={items:r}:delete e.character},Vn=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Dn=(e,t)=>{if(t.layout){let{animationsOnly:n,state:r}=fe(t.layout,o=>!!o.resourceId);if(n){e.layout=r;return}if(!t.layout.resourceId){delete e.layout;return}e.layout=t.layout}else e.layout&&delete e.layout},Mn=(e,t)=>{if(t.choice){let{animationsOnly:n,state:r}=fe(t.choice,o=>!!o.resourceId);if(n){e.choice={...e.choice,...r};return}if(!t.choice.resourceId){delete e.choice;return}e.choice=t.choice}else e.choice&&delete e.choice},Bn=(e,t)=>{t.keyboard&&(e.keyboard=t.keyboard)},Fn=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},jn=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},ee=e=>ue($n,[jn,Sn,On,Rn,Tn,Nn,kn,Pn,Vn,Dn,Mn,Bn,Fn])(e);var H={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n})),formatDate:pt},yt=(e,t)=>{if(!e||typeof e!="string"||!e.includes("${"))return e;let n=O(e,t);return n&&typeof n=="object"?e:n},q=({animations:e,animationsDef:t,resources:n,previousResourceId:r,currentResourceId:o,idPrefix:i,targetId:l,outTargetId:c})=>{if(t){if(t.in){let a=t.in.resourceId||t.in,s=n?.tweens?.[a];s&&!r&&e.push({id:`${i}-animation-in`,type:"tween",targetId:l,properties:structuredClone(s.properties)})}if(t.out){let a=t.out.resourceId||t.out,s=n?.tweens?.[a];s&&r&&r!==o&&e.push({id:`${i}-animation-out`,type:"tween",targetId:c||l,properties:structuredClone(s.properties)})}if(t.update){let a=t.update.resourceId||t.update,s=n?.tweens?.[a];s&&r&&r===o&&e.push({id:`${i}-animation-update`,type:"tween",targetId:l,properties:structuredClone(s.properties)})}}},Un=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),Wn=(e,{presentationState:t,resources:n,variables:r})=>{let{elements:o}=e;if(t.base){let i=o.find(l=>l.id==="story");if(!i)return e;if(t.base.resourceId){let l=n?.layouts[t.base.resourceId];if(l){let c={id:"base",type:"container",children:l.elements},a=O(c,{variables:r},{functions:H});i.children.unshift(a)}}}return e},zn=(e,{presentationState:t,previousPresentationState:n,resources:r={},isLineCompleted:o,skipTransitionsAndAnimations:i,variables:l})=>{let{elements:c,animations:a}=e;if(t.background){let s=c.find(f=>f.id==="story");if(!s)return e;if(t.background.resourceId){let{images:f={},videos:u={}}=r,d=f[t.background.resourceId]||u[t.background.resourceId];if(d){let h=u[t.background.resourceId]!==void 0,g={id:`bg-cg-${t.background.resourceId}`,type:h?"video":"sprite",x:0,y:0,src:d.fileId,width:d.width,height:d.height};h&&(g.loop=t.background.loop??!1,g.volume=d.volume??500),s.children.push(g)}}if(t.background.resourceId){let{layouts:f={}}=r,u=f[t.background.resourceId];if(u){let d={id:`bg-cg-${t.background.resourceId}`,type:"container",children:u.elements},h=O(d,{variables:l},{functions:H});s.children.push(h)}}if(t.background.animations&&!o&&!i){let f=n?.background?.resourceId,u=t.background.resourceId;q({animations:a,animationsDef:t.background.animations,resources:r,previousResourceId:f,currentResourceId:u,idPrefix:"bg-cg",targetId:`bg-cg-${u}`,outTargetId:`bg-cg-${f}`})}}return e},Yn=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i})=>{let{elements:l,animations:c}=e;if(t.character&&r){let a=l.find(u=>u.id==="story");if(!a)return e;let s=t.character.items||[],f=n?.character?.items||[];for(let u=0;u<s.length;u++){let d=s[u],{transformId:h,sprites:g}=d,m=f.find($=>$.id===d.id),y=m?.sprites&&m.sprites.length>0,b=g&&g.length>0;if(d.animations&&d.animations.out&&!g&&!h){if(!o&&y){let $=d.animations.out.resourceId,N=r?.tweens?.[$];if(N){let V={id:"character-animation-out",type:"tween",targetId:`character-container-${d.id}`,properties:N.properties};c.push(V)}}continue}if(!g||g.length===0||!h){console.warn("Character item missing sprites or transformId:",d);continue}let I=g.map(({resourceId:$})=>$),_=`character-container-${d.id}-${u}-${I.join("-")}`,x=r.transforms[h];if(!x){console.warn("Transform not found:",h);continue}let A={type:"container",id:_,x:d.x??x.x,y:d.y??x.y,anchorX:x.anchorX,anchorY:x.anchorY,rotation:x.rotation,scaleX:x.scaleX,scaleY:x.scaleY,children:[]};for(let $ of g){let N=r.images[$.resourceId];if(!N){console.warn(`Image resource not found: ${$.resourceId}`);continue}A.children.push({type:"sprite",id:`${_}-${$.id}`,src:N.fileId,width:N.width,height:N.height,x:0,y:0})}a.children.push(A),d.animations&&!o&&!i&&q({animations:c,animationsDef:d.animations,resources:r,previousResourceId:y,currentResourceId:b,idPrefix:"character",targetId:_})}}return e},Hn=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,variables:l})=>{let{elements:c,animations:a}=e;if(t.visual&&r){let s=c.find(u=>u.id==="story");if(!s)return e;let f=t.visual.items;for(let u of f){if(u.resourceId){let{images:d={},videos:h={},spritesheets:g={}}=r,m=g[u.resourceId];if(m){let y=r.transforms?.[u.transformId]||{},b=u.animationName;if(b){let I=m.animations?.[b];if(!I)throw new Error(`Animation '${b}' not found in spritesheet resource '${u.resourceId}'`);let _={id:`visual-${u.id}`,type:"animated-sprite",x:u.x??y.x??0,y:u.y??y.y??0,width:u.width??m.width,height:u.height??m.height,alpha:u.alpha??1,anchorX:y.anchorX,anchorY:y.anchorY,rotation:y.rotation,scaleX:y.scaleX,scaleY:y.scaleY,spritesheetSrc:m.fileId,spritesheetData:m.jsonData,animation:{frames:I.frames,animationSpeed:u.animationSpeed??I.animationSpeed??.5,loop:u.loop??I.loop??!0}};s.children.push(structuredClone(_))}}else{let y=d[u.resourceId]||h[u.resourceId];if(y){let b=h[u.resourceId]!==void 0,I=r.transforms[u.transformId],_={id:`visual-${u.id}`,type:b?"video":"sprite",src:y.fileId,width:y.width,height:y.height,x:I.x,y:I.y,anchorX:I.anchorX,anchorY:I.anchorY,rotation:I.rotation,scaleX:I.scaleX,scaleY:I.scaleY};b&&(_.loop=y.loop??!1,_.volume=y.volume??500),s.children.push(_)}}}if(u.resourceId){let{layouts:d={}}=r,h=d[u.resourceId];if(h){let g=r.transforms[u.transformId],m={id:`visual-${u.id}`,type:"container",children:structuredClone(h.elements),x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY},y=O(m,{variables:l},{functions:H});s.children.push(y)}}if(u.animations&&!o&&!i){let h=(n?.visual?.items||[]).find(g=>g.id===u.id);q({animations:a,animationsDef:u.animations,resources:r,previousResourceId:h?.resourceId,currentResourceId:u.resourceId,idPrefix:u.id,targetId:`visual-${u.id}`})}}}return e},qn=(e,{presentationState:t,previousPresentationState:n,resources:r={},dialogueUIHidden:o,autoMode:i,skipMode:l,canRollback:c,skipOnlyViewedLines:a,isLineCompleted:s,skipTransitionsAndAnimations:f,l10n:u,variables:d,saveSlots:h=[]})=>{let{elements:g,animations:m}=e;if(!t.dialogue||o)return e;let y=g.find(b=>b.id==="story");if(!y)return e;if(t.dialogue.gui&&t.dialogue.gui.resourceId){let{layouts:b={}}=r,I=b[t.dialogue.gui.resourceId];if(I){let _;t.dialogue.characterId&&(_=r.characters[t.dialogue.characterId]),t.dialogue.character&&(_={..._,name:t.dialogue.character.name});let x={elements:I.elements},A={variables:d,autoMode:i,skipMode:l,canRollback:c,skipOnlyViewedLines:a,isLineCompleted:s,saveSlots:h,effectiveSoundVolume:d?._muteAll?0:d?._soundVolume??500,textSpeed:d?._textSpeed??50,dialogue:{character:{name:_?.name||""},content:(t.dialogue?.content||[{text:""}]).map(V=>({...V,text:yt(V.text,{variables:d,l10n:u})})),lines:(t.dialogue?.lines||[]).map(V=>({content:V.content?.map(Me=>({...Me,text:yt(Me.text,{variables:d,l10n:u})})),characterName:V.characterId&&r.characters?.[V.characterId]?.name||""}))},l10n:u},$=O(x,A,{functions:H});$=O($,{l10n:u});let N=$?.elements;if(Array.isArray(N))for(let V of N)y.children.push(structuredClone(V));else N&&y.children.push(structuredClone(N))}}return t.dialogue.gui?.animations&&!s&&!f&&q({animations:m,animationsDef:t.dialogue.gui.animations,resources:r,previousResourceId:n?.dialogue?.gui?.resourceId,currentResourceId:t.dialogue.gui?.resourceId,idPrefix:"dialogue-gui",targetId:"dialogue-container"}),e},Kn=(e,{presentationState:t,previousPresentationState:n,resources:r,isLineCompleted:o,skipTransitionsAndAnimations:i,screen:l})=>{let{elements:c,animations:a}=e;if(t.choice&&r){let s=c.find(u=>u.id==="story");if(!s)return e;s.children.push({id:"choice-blocker",type:"rect",fill:"transparent",width:l.width,height:l.height,x:0,y:0,click:{actionPayload:{actions:{}}}});let f=r?.layouts[t.choice.resourceId];if(f&&f.elements){let u={elements:f.elements},h=O(u,{choice:{items:t.choice?.items??[]}})?.elements;if(Array.isArray(h))for(let g of h)s.children.push(structuredClone(g));else h&&s.children.push(structuredClone(h))}t.choice.animations&&!o&&!i&&q({animations:a,animationsDef:t.choice.animations,resources:r,previousResourceId:n?.choice?.resourceId,currentResourceId:t.choice.resourceId,idPrefix:"choice",targetId:"choice-container"})}return e},Jn=(e,{presentationState:t,resources:n})=>{if(t.keyboard?.resourceId){let r=n?.keyboards?.[t.keyboard.resourceId];r&&(e.global.keyboard=r)}return e},Xn=(e,{presentationState:t,resources:n,variables:r})=>{let{elements:o,audio:i}=e;if(t.bgm&&n){if(!o.find(s=>s.id==="story"))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;let a=r?._muteAll?0:r?._musicVolume??500;i.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:a,delay:t.bgm.delay??null})}return e},Gn=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let o=t.sfx.items;for(let i of o){let l=n.sounds?.[i.resourceId];l&&r.push({id:i.id,type:"sound",src:l.fileId,loop:i.loop??l.loop??!0,volume:i.volume??l.volume??500,delay:i.delay??l.delay??null})}}return e},Qn=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:o,volume:i,loop:l}=t.voice;return r.push({id:`voice-${o}`,type:"sound",src:o,volume:i??500,loop:l??!1}),e},Zn=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:l,canRollback:c,currentLocalizationPackageId:a,saveSlots:s=[],isLineCompleted:f,skipTransitionsAndAnimations:u})=>{let{elements:d,animations:h}=e;if(t.layout){let g=d.find(x=>x.id==="story");if(!g)return e;let m=r.layouts[t.layout.resourceId];if(!m)return e;Array.isArray(m.transitions)&&!f&&!u&&m.transitions.forEach(x=>{h.push(x)});let y={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:m.elements||[]},b={variables:o,saveSlots:s,autoMode:i,skipMode:l,canRollback:c,currentLocalizationPackageId:a,effectiveSoundVolume:o?._muteAll?0:o?._soundVolume??500,textSpeed:o?._textSpeed??50},I=O(y,b,{functions:H});I=O(I,{i18n:{}});let _=x=>{let A={...x};return x.src&&x.src.startsWith("file:")&&(A.src=x.src),x.children&&Array.isArray(x.children)&&(A.children=x.children.map(_)),A};g.children.push(_(I))}if(t.layout?.animations&&!f&&!u){let g=n?.layout?.resourceId,m=t.layout?.resourceId;q({animations:h,animationsDef:t.layout.animations,resources:r,previousResourceId:g,currentResourceId:m,idPrefix:"layout",targetId:`layout-${m}`,outTargetId:`layout-${g}`})}return e},er=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,canRollback:i,currentLocalizationPackageId:l,layeredViews:c=[],dialogueHistory:a=[],saveSlots:s=[],l10n:f,screen:u})=>{let{elements:d,animations:h}=e;return c&&c.length>0&&c.forEach((g,m)=>{let y=t.layouts[g.resourceId];if(!y){console.warn(`LayeredView layout not found: ${g.resourceId}`);return}Array.isArray(y.transitions)&&y.transitions.forEach(A=>{h.push(A)});let b={id:`layeredView-${m}`,type:"container",x:0,y:0,children:[{id:`layeredView-${m}-blocker`,type:"rect",fill:"transparent",width:u.width,height:u.height,x:0,y:0,click:{actionPayload:{actions:{}}}},...y.elements||[]]},I=a.map(A=>{let $=t.characters?.[A.characterId];return{...A,characterName:$?.name||""}}),_={variables:n,autoMode:r,skipMode:o,canRollback:i,currentLocalizationPackageId:l,saveSlots:s,effectiveSoundVolume:n?._muteAll?0:n?._soundVolume??500,textSpeed:n?._textSpeed??50,historyDialogue:I,characters:t.characters||{}},x=O(b,_,{functions:H});x=O(x,{i18n:{},l10n:f}),d.push(x)}),e},mt=e=>ue(Un,[Wn,zn,Yn,Hn,qn,Kn,Jn,Zn,Xn,Gn,Qn,er])(e);var K={manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1},applyMode:"persistent"},bt=e=>{if((e.global.nextLineConfig?.applyMode??"persistent")!=="singleLine")return;let n=e.global.nextLineConfig?.auto?.enabled===!0;e.global.nextLineConfig={manual:{...K.manual},auto:{...K.auto},applyMode:K.applyMode},n&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"})},tr=e=>{let{global:{currentLocalizationPackageId:t,saveSlots:n={},variables:r={}},projectData:o}=e,i=o.story.initialSceneId,l=o.story.scenes[i],c=l.initialSectionId,a=l.sections[c],s={sceneId:i,sectionId:c,lineId:a.initialLineId??a.lines[0].id},{contextVariableDefaultValues:f,globalVariablesDefaultValues:u}=ut(o),d={...u,...r};return{projectData:o,global:{isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,isDialogueHistoryShowing:!1,currentLocalizationPackageId:t,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{...K.manual},auto:{...K.auto},applyMode:K.applyMode},saveSlots:n,layeredViews:[],variables:d},contexts:[{currentPointerMode:"read",pointers:{read:s,history:{sectionId:void 0,lineId:void 0,historySequenceIndex:void 0}},historySequence:[{sectionId:s.sectionId,initialState:{...f},lines:[{id:s.lineId}]}],configuration:{},views:[],bgm:{resourceId:void 0},variables:f}]}},nr=({state:e})=>e.global.layeredViews||[],rr=({state:e})=>e.global.pendingEffects,It=({state:e})=>e.global.skipMode,or=({state:e})=>e.global.autoMode,wt=({state:e})=>e.global.dialogueUIHidden,Te=({state:e})=>{let t=e.contexts[e.contexts.length-1];if(!t)return[];let{sectionId:n,lineId:r}=t.pointers.read,o=k({state:e},{sectionId:n});if(!o?.lines||!Array.isArray(o.lines))return[];let i=o.lines.findIndex(a=>a.id===r);return o.lines.slice(0,i+1).filter(a=>a.actions?.dialogue).map(a=>{let s=a.actions.dialogue,f="";return s.characterId&&(f=e.projectData.resources?.characters?.[s.characterId]?.name||""),{content:s.content,characterId:s.characterId,characterName:f}})},ir=({state:e})=>e.global.currentLocalizationPackageId,Ne=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(a=>a.sectionId===n);if(!o)return!1;if(o.lastLineId===void 0||r===void 0)return!0;let i=k({state:e},{sectionId:n});if(!i||!i.lines||!Array.isArray(i.lines))return!1;let l=i.lines.findIndex(a=>a.id===o.lastLineId),c=i.lines.findIndex(a=>a.id===r);return l===-1||c===-1?o.lastLineId===r:c<l},sr=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},lr=({state:e})=>e.global.nextLineConfig,ar=({state:e})=>e.global.saveSlots,cr=({state:e},t)=>{let{slotKey:n}=t;return e.global.saveSlots[n]},U=({state:e})=>{let t=e.contexts[e.contexts.length-1];if(!t)return;let n=t.pointers?.[t.currentPointerMode];return{currentPointerMode:t.currentPointerMode,pointer:n}},k=({state:e},t)=>{let{sectionId:n}=t,r=e.projectData?.story?.scenes||{};for(let o in r){let i=r[o];if(i.sections&&i.sections[n])return i.sections[n]}},_t=({state:e})=>{let t=U({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,o=k({state:e},{sectionId:n});if(!(!o?.lines||!Array.isArray(o.lines)))return o.lines.find(i=>i.id===r)},ur=({state:e})=>{let t=U({state:e})?.pointer,n=t?.sectionId,r=t?.lineId,i=k({state:e},{sectionId:n})?.lines||[],l=i.findIndex(s=>s.id===r);if(l<0)return;let c;return i.slice(0,l+1).forEach(s=>{if(!s?.actions||!Object.prototype.hasOwnProperty.call(s.actions,"choice"))return;let f=s.actions.choice;if(!f?.resourceId){f?.animations||(c=void 0);return}c=f.resourceId}),c},xt=({state:e})=>{let{sectionId:t,lineId:n}=U({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(s=>s.id===n),c=o.slice(0,i+1).map(s=>{let f=s.actions||{},u={};return Object.keys(f).forEach(d=>{u[d]=f[d]}),u});return ee(c)},fr=({state:e})=>{let t=vt({state:e}),r=_t({state:e})?.actions??{},o=ee([t??{},r]);return ke(t??{},o??{})},dr=({state:e},{sectionId:t})=>{let n=k({state:e},{sectionId:t});if(!n?.lines)return{lines:[]};let r=[],o={};for(let i of n.lines){let l=i.actions||{},c=ee([o,l]),a=ke(o,c);r.push({id:i.id,changes:a}),o=c}return{lines:r}},vt=({state:e})=>{let{sectionId:t,lineId:n}=U({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(a=>a.id===n);if(i<=0)return null;let c=o.slice(0,i).map(a=>{let s=a.actions||{},f={};return Object.keys(s).forEach(u=>{f[u]=s[u]}),f});return ee(c)},Et=({state:e},{slotsPerPage:t=6}={})=>{let o=(({...e.global.variables,...e.contexts[e.contexts.length-1].variables}.loadPage??1)-1)*t+1,i=[];for(let l=0;l<t;l++){let c=o+l,a=e.global.saveSlots&&e.global.saveSlots[c]||{};i.push({slotNumber:c,...a})}return{saveSlots:i}},pr=({state:e})=>{let t=xt({state:e}),n=vt({state:e}),r={...e.global.variables,...e.contexts[e.contexts.length-1].variables},{saveSlots:o}=Et({state:e});return mt({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,screen:e.projectData.screen,l10n:e.projectData.l10n.packages[e.global.currentLocalizationPackageId],currentLocalizationPackageId:e.global.currentLocalizationPackageId,dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,canRollback:kt({state:e}),skipOnlyViewedLines:!r._skipUnseenText,isLineCompleted:e.global.isLineCompleted,skipTransitionsAndAnimations:!!r._skipTransitionsAndAnimations,layeredViews:e.global.layeredViews,dialogueHistory:Te({state:e}),saveSlots:o,variables:r})},hr=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),e),gr=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),e),yr=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),e),mr=({state:e})=>(e.global.layeredViews=[],e.global.pendingEffects.push({name:"render"}),e),At=({state:e})=>{if(e.global.skipMode&&(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"})),e.global.autoMode=!0,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.isLineCompleted){let t=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:t}})}return e.global.pendingEffects.push({name:"render"}),e},de=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),br=({state:e})=>(e.global.autoMode?de({state:e}):At({state:e}),e),Lt=({state:e})=>(e.global.autoMode&&(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"})),e.global.skipMode=!0,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"startSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),J=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ir=({state:e})=>(It({state:e})?J({state:e}):Lt({state:e}),e),Ct=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),e),$t=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),e),wr=({state:e})=>(wt({state:e})?Ct({state:e}):$t({state:e}),e),_r=({state:e})=>{let t=Te({state:e});return e.global.isDialogueHistoryShowing=!0,e.global.pendingEffects.push({name:"render"}),e},xr=({state:e})=>(e.global.isDialogueHistoryShowing=!1,e.global.pendingEffects.push({name:"render"}),e),vr=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},Er=({state:e})=>(e.global.pendingEffects=[],e),Ar=({state:e},t)=>(e.global.pendingEffects.push(t),e),St=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(i=>i.sectionId===n);if(o){let i=k({state:e},{sectionId:n});if(i?.lines&&o.lastLineId!==void 0){let l=i.lines.findIndex(a=>a.id===o.lastLineId),c=i.lines.findIndex(a=>a.id===r);(l===-1||c>l)&&(o.lastLineId=r)}else o.lastLineId=r}else e.global.viewedRegistry.sections.push({sectionId:n,lastLineId:r});return e.global.pendingEffects.push({name:"render"}),e},Lr=({state:e},t)=>{let{resourceId:n}=t;return e.global.viewedRegistry.resources.find(o=>o.resourceId===n)||e.global.viewedRegistry.resources.push({resourceId:n}),e.global.pendingEffects.push({name:"render"}),e},Cr=({state:e},t)=>{let{manual:n,auto:r,applyMode:o}=t,i=e.global.nextLineConfig.auto?.enabled,l=e.global.nextLineConfig?.applyMode;n&&r?(e.global.nextLineConfig={manual:n,auto:r},o!==void 0?e.global.nextLineConfig.applyMode=o:l!==void 0&&(e.global.nextLineConfig.applyMode=l)):(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r),o!==void 0&&(e.global.nextLineConfig.applyMode=o));let c=e.global.nextLineConfig.auto?.enabled;return c===!0&&!i?e.global.nextLineConfig.auto?.trigger==="fromStart"?e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):e.global.isLineCompleted&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}}):c===!1&&i&&e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.pendingEffects.push({name:"render"}),e},$r=({state:e},t)=>{let{slot:n,thumbnailImage:r}=t,o=String(n),i={contexts:[...e.contexts],viewedRegistry:e.global.viewedRegistry},l={slotKey:o,date:Date.now(),image:r,state:i};return e.global.saveSlots[o]=l,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},Sr=({state:e},t)=>{let{slot:n}=t,r=String(n),o=e.global.saveSlots[r];return o&&(e.global.viewedRegistry=o.state.viewedRegistry,e.contexts=o.state.contexts,e.global.pendingEffects.push({name:"render"})),e},Or=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},kr=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let o=e.contexts[e.contexts.length-1];if(!o)return console.warn("No context available for jumpToLine"),e;let i=n||o.pointers.read?.sectionId;if(n&&!k({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let l=k({state:e},{sectionId:i});return!l?.lines||!Array.isArray(l.lines)?(console.warn(`Section ${i} has no lines`),e):l.lines.find(a=>a.id===r)?(o.pointers.read={sectionId:i,lineId:r},e.global.isLineCompleted=!1,te({state:e},{lineId:r}),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},Ot=({state:e},t)=>{let{item:n}=t,r=e.contexts[e.contexts.length-1];if(r&&r.historySequence){let o={...r.variables};r.historySequence.push({sectionId:n.sectionId,initialState:o,lines:[]})}return e.global.pendingEffects.push({name:"render"}),e},te=({state:e},t)=>{let{lineId:n}=t,r=e.contexts[e.contexts.length-1];if(!r?.historySequence)return e;let o=r.historySequence;if(o.length===0)return e;let i=o[o.length-1];return i.lines||(i.lines=[]),i.lines.push({id:n}),e},Rr=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;if(!e.global.isLineCompleted){if(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}),e.global.autoMode){let a=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:a}})}let c=e.global.nextLineConfig;return c?.auto?.enabled&&c.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:c.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e}let t=U({state:e})?.pointer,n=t?.sectionId,o=k({state:e},{sectionId:n})?.lines||[],l=o.findIndex(c=>c.id===t?.lineId)+1;if(l<o.length){let c=o[l],a=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&a&&!Ne({state:e},{sectionId:n,lineId:c.id}))return J({state:e}),e;let s=e.contexts[e.contexts.length-1];if(s){let u=s.pointers.read.lineId;u&&n&&St({state:e},{sectionId:n,lineId:u}),s.pointers.read={sectionId:n,lineId:c.id}}e.global.isLineCompleted=!1,te({state:e},{lineId:c.id}),bt(e),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"});let f=e.global.nextLineConfig;f?.auto?.enabled&&f.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:f.auto.delay}})}else e.global.autoMode&&de({state:e}),e.global.skipMode&&J({state:e});return e},Tr=({state:e})=>{if(e.global.isLineCompleted)return e;if(e.global.isLineCompleted=!0,e.global.autoMode){let n=e.global.variables._autoForwardTime??1e3;e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:n}})}let t=e.global.nextLineConfig;return t?.auto?.enabled&&t.auto.trigger!=="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:t.auto.delay}}),e.global.pendingEffects.push({name:"render"}),e},Nr=({state:e},t)=>{let{sectionId:n}=t,r=k({state:e},{sectionId:n});if(!r||!r.lines||r.lines.length===0)return e;let o=r.lines,i=e.contexts[e.contexts.length-1];if(!i||!i.pointers)return e;let l=i.pointers.history||i.pointers.read;if(i.currentPointerMode!=="history"||!i.pointers.history){if(!l)return e;i.currentPointerMode="history",i.pointers.history={sectionId:n,lineId:l?.lineId};let f=o.findIndex(u=>u.id===l.lineId)-1;if(f>=0&&f<o.length){let u=o[f];i.pointers.history={sectionId:n,lineId:u.id}}return e.global.pendingEffects.push({name:"render"}),e}let a=o.findIndex(s=>s.id===i.pointers.history.lineId)-1;if(a>=0&&a<o.length){let s=o[a];i.pointers.history={sectionId:n,lineId:s.id},e.global.pendingEffects.push({name:"render"})}return e},Pr=({state:e},t)=>{let{sectionId:n}=t,r=k({state:e},{sectionId:n});if(!r)return console.warn(`Section not found: ${n}`),e;let o=r.lines?.[0];if(!o)return console.warn(`Section ${n} has no lines`),e;e.global.autoMode&&de({state:e}),e.global.skipMode&&J({state:e});let i=e.contexts[e.contexts.length-1];return i&&(i.pointers.read={sectionId:n,lineId:o.id},Ot({state:e},{item:{sectionId:n}}),te({state:e},{lineId:o.id})),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},Vr=({state:e})=>{if(ur({state:e}))return e;let t=U({state:e})?.pointer,n=t?.sectionId,o=k({state:e},{sectionId:n})?.lines||[],l=o.findIndex(c=>c.id===t?.lineId)+1;if(l<o.length){let c=o[l],a=!e.global.variables?._skipUnseenText;if(e.global.skipMode&&a&&!Ne({state:e},{sectionId:n,lineId:c.id}))return J({state:e}),e;let s=e.contexts[e.contexts.length-1];s&&(s.pointers.read={sectionId:n,lineId:c.id}),e.global.isLineCompleted=!1,te({state:e},{lineId:c.id}),bt(e),e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e.global.nextLineConfig.auto?.enabled&&e.global.nextLineConfig.auto.trigger==="fromStart"&&e.global.pendingEffects.push({name:"nextLineConfigTimer",payload:{delay:e.global.nextLineConfig.auto.delay}})}else e.global.nextLineConfig.auto?.enabled&&(e.global.nextLineConfig.auto.enabled=!1,e.global.pendingEffects.push({name:"clearNextLineConfigTimer"}));return e},Dr=({state:e},t)=>{let{id:n,operations:r=[]}=t;if(!n)throw new Error("updateVariable requires an id field");if(typeof n!="string"||!/^[a-zA-Z0-9]+$/.test(n))throw new Error(`updateVariable id must be alphanumeric, got: "${n}"`);let o=e.contexts[e.contexts.length-1],i=!1,l=!1,c=!1;if(r.forEach(({variableId:a,op:s,value:f})=>{let u=e.projectData.resources?.variables?.[a],d=u?.scope,h=u?.type;ft(d,a),dt(h,s,a);let g=d==="context"?o.variables:e.global.variables;d==="context"?i=!0:d==="global-device"?l=!0:d==="global-account"&&(c=!0),g[a]=Se(g[a],s,f)}),i){let a=o.historySequence;if(a&&a.length>0){let s=a[a.length-1];if(s.lines&&s.lines.length>0){let f=s.lines[s.lines.length-1];f.updateVariableIds||(f.updateVariableIds=[]),f.updateVariableIds.push(n)}}}if(l){let a=Oe(e.global.variables,e.projectData.resources?.variables,"global-device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:a}})}if(c){let a=Oe(e.global.variables,e.projectData.resources?.variables,"global-account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:a}})}return e.global.pendingEffects.push({name:"render"}),e},Re=(e,t,n="")=>{if(e!=null){if(n==="updateVariable"&&typeof e=="object"&&e.id===t&&Array.isArray(e.operations))return e;if(Array.isArray(e)){for(let r of e){let o=Re(r,t,n);if(o)return o}return}if(typeof e=="object")for(let r of Object.keys(e)){let o=Re(e[r],t,r);if(o)return o}}},Pe=({state:e},t)=>{let{offset:n}=t;if(n===void 0||typeof n!="number")return console.warn("selectLineIdByOffset requires a numeric offset"),null;let r=e.contexts[e.contexts.length-1];if(!r)return null;let o=r.pointers.read?.sectionId,i=r.pointers.read?.lineId;if(!o||!i)return null;let c=r.historySequence?.find(u=>u.sectionId===o);if(!c?.lines||c.lines.length===0)return null;let a=c.lines.findLastIndex(u=>u.id===i);if(a===-1)return null;let s=a+n;if(s<0||s>=c.lines.length)return null;let f=c.lines[s];return{sectionId:o,lineId:f.id}},kt=({state:e})=>Pe({state:e},{offset:-1})!==null,Mr=({state:e},t)=>{let{offset:n=-1}=t;if(n>=0)throw new Error("rollbackByOffset requires a negative offset");let r=Pe({state:e},{offset:n});return r?Rt({state:e},{sectionId:r.sectionId,lineId:r.lineId}):e},Rt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.contexts[e.contexts.length-1];if(!o)throw new Error("No context available for rollbackToLine");let l=o.historySequence?.find(s=>s.sectionId===n);if(!l?.lines)throw new Error(`Section ${n} not found in history or has no lines`);let c=l.lines.findIndex(s=>s.id===r);if(c===-1)throw new Error(`Line ${r} not found in section ${n} history`);let a=l.initialState||{};o.variables={...a};for(let s=0;s<c;s++){let u=l.lines[s].updateVariableIds||[];for(let d of u){let h=Re(e.projectData,d);if(!h)throw new Error(`Action definition not found for ID: ${d}`);let g=h.operations||[];for(let{variableId:m,op:y,value:b}of g)e.projectData.resources?.variables?.[m]?.scope==="context"&&(o.variables[m]=Se(o.variables[m],y,b))}}return l.lines=l.lines.slice(0,c),l.lines.push({id:r}),o.pointers.read={sectionId:n,lineId:r},o.currentPointerMode="read",o.pointers.history={sectionId:null,lineId:null,historySequenceIndex:null},e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},Tt=e=>{let t=tr(e);return ct(t,{selectPendingEffects:rr,selectSkipMode:It,selectAutoMode:or,selectDialogueUIHidden:wt,selectDialogueHistory:Te,selectCurrentLocalizationPackageId:ir,selectIsLineViewed:Ne,selectIsResourceViewed:sr,selectNextLineConfig:lr,selectSaveSlots:ar,selectSaveSlot:cr,selectCurrentPointer:U,selectSection:k,selectCurrentLine:_t,selectPresentationState:xt,selectPresentationChanges:fr,selectSectionLineChanges:dr,selectCurrentPageSlots:Et,selectRenderState:pr,selectLayeredViews:nr,selectLineIdByOffset:Pe,selectCanRollback:kt,startAutoMode:At,stopAutoMode:de,toggleAutoMode:br,startSkipMode:Lt,stopSkipMode:J,toggleSkipMode:Ir,showDialogueUI:Ct,hideDialogueUI:$t,toggleDialogueUI:wr,showDialogueHistory:_r,hideDialogueHistory:xr,setCurrentLocalizationPackageId:vr,clearPendingEffects:Er,appendPendingEffect:Ar,addViewedLine:St,addViewedResource:Lr,setNextLineConfig:Cr,saveSaveSlot:$r,loadSaveSlot:Sr,updateProjectData:Or,sectionTransition:Pr,jumpToLine:kr,addToHistorySequence:Ot,addLineToHistory:te,nextLine:Rr,markLineCompleted:Tr,prevLine:Nr,rollbackToLine:Rt,rollbackByOffset:Mr,pushLayeredView:hr,popLayeredView:gr,replaceLastLayeredView:yr,clearLayeredViews:mr,updateVariable:Dr,nextLineFromSystem:Vr},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Ve(e){let t,{handlePendingEffects:n}=e,r=()=>{for(;t.selectPendingEffects().length>0;){let y=[...t.selectPendingEffects()];t.clearPendingEffects(),n(y)}},o=({initialState:y})=>{t=Tt(y),t.appendPendingEffect({name:"render"}),m(),r()},i=()=>t.selectPresentationState(),l=()=>t.selectPresentationChanges(),c=y=>t.selectSectionLineChanges(y),a=()=>t.selectRenderState(),s=()=>t.selectSaveSlots(),f=()=>t.selectSkipMode(),u=()=>t.selectAutoMode(),d=(y,b)=>{t[y]&&(t[y](b),r())},h=y=>{if(!y)return;if(Object.prototype.hasOwnProperty.call(y,"event"))throw new Error('eventContext key "event" is no longer supported. Use "_event".');let{_event:b,...I}=y,_=t.selectAllVariables?t.selectAllVariables():void 0,x=t.selectCurrentL10n?t.selectCurrentL10n():void 0;return{...I,_event:b,variables:_,l10n:x}},g=(y,b)=>{let I=h(b),_=ht(y,I);Object.entries(_).forEach(([x,A])=>{d(x,A)})},m=()=>{let y=t.selectCurrentLine();y?.actions&&g(y.actions)};return{init:o,handleAction:d,handleActions:g,selectRenderState:a,selectPresentationState:i,selectPresentationChanges:l,selectSectionLineChanges:c,selectSaveSlots:s,handleLineActions:m}}var De=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},Br=({engine:e,routeGraphics:t},n)=>{let r=e.selectRenderState();t.render(r)},Fr=({engine:e},t)=>{e.handleLineActions()},jr=({engine:e,ticker:t,autoTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=l=>{n.addElapsed(l.deltaMS);let c=r.delay??1e3;n.getElapsed()>=c&&(t.remove(i),n.setCallback(null),n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},Ur=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Wr=({engine:e,ticker:t,skipTimer:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=l=>{n.addElapsed(l.deltaMS),n.getElapsed()>=30&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}))};n.setCallback(i),t.add(i)},zr=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Yr=({engine:e,ticker:t,nextLineConfigTimerState:n},r)=>{let o=n.getCallback();o&&t.remove(o),n.setElapsed(0);let i=l=>{n.addElapsed(l.deltaMS);let c=r.delay??1e3;n.getElapsed()>=c&&(n.setElapsed(0),e.handleAction("nextLineFromSystem",{}),t.remove(i),n.setCallback(null))};n.setCallback(i),t.add(i)},Hr=({ticker:e,nextLineConfigTimerState:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},qr=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},Kr=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Jr=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},Xr={render:Br,saveSlots:qr,saveGlobalDeviceVariables:Kr,saveGlobalAccountVariables:Jr,handleLineActions:Fr,startAutoNextTimer:jr,clearAutoNextTimer:Ur,startSkipNextTimer:Wr,clearSkipNextTimer:zr,nextLineConfigTimer:Yr,clearNextLineConfigTimer:Hr},Gr=({getEngine:e,routeGraphics:t,ticker:n})=>{let r=De(),o=De(),i=De();return async l=>{let c=e(),a=l.reduce((u,d)=>(u[d.name]=d,u),{}),s=Object.values(a),f={engine:c,routeGraphics:t,ticker:n,autoTimer:r,skipTimer:o,nextLineConfigTimerState:i};for(let u of s){let d=Xr[u.name];d&&d(f,u.payload)}}},Qr=Gr;var Jo=Ve;export{Qr as createEffectsHandler,Jo as default};
|
package/package.json
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "route-engine-js",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.35",
|
|
4
4
|
"description": "A lightweight Visual Novel engine built in JavaScript for creating interactive narrative games with branching storylines",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/RouteVN/route-engine.git"
|
|
8
|
+
},
|
|
9
|
+
"bugs": {
|
|
10
|
+
"url": "https://github.com/RouteVN/route-engine/issues"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/RouteVN/route-engine#readme",
|
|
5
13
|
"keywords": [
|
|
6
14
|
"game-engine",
|
|
7
15
|
"visual-novel",
|
|
@@ -30,7 +38,7 @@
|
|
|
30
38
|
"lint": "bun run prettier src -c",
|
|
31
39
|
"lint:fix": "bun run prettier src -w",
|
|
32
40
|
"coverage": "bun run vitest run --coverage",
|
|
33
|
-
"vt:generate": "bun run esbuild.js && rtgl vt generate
|
|
41
|
+
"vt:generate": "bun run esbuild.js && rtgl vt generate",
|
|
34
42
|
"vt:docker": "bun run esbuild.js && docker run --rm --user $(id -u):$(id -g) -e RTGL_VT_DEBUG=true -v \"$PWD:/app\" -w /app han4wluc/rtgl:playwright-v1.57.0-rtgl-v1.0.0-rc12 rtgl vt screenshot --wait-event vt:ready --concurrency 2",
|
|
35
43
|
"vt:report": "bun run vt:docker && rtgl vt report",
|
|
36
44
|
"vt:accept": "rtgl vt accept",
|