route-engine-js 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var nt=Object.defineProperty;var rt=(e,t)=>{for(var n in t)nt(e,n,{get:t[n],enumerable:!0})};var xe=Symbol.for("immer-nothing"),be=Symbol.for("immer-draftable"),L=Symbol.for("immer-state");function O(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var M=Object.getPrototypeOf;function B(e){return!!e&&!!e[L]}function S(e){return e?$e(e)||Array.isArray(e)||!!e[be]||!!e.constructor?.[be]||G(e)||q(e):!1}var it=Object.prototype.constructor.toString();function $e(e){if(!e||typeof e!="object")return!1;let t=M(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)===it}function K(e,t){H(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function H(e){let t=e[L];return t?t.type_:Array.isArray(e)?1:G(e)?2:q(e)?3:0}function ie(e,t){return H(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Le(e,t,n){let r=H(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function ot(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function G(e){return e instanceof Map}function q(e){return e instanceof Set}function N(e){return e.copy_||e.base_}function oe(e,t){if(G(e))return new Map(e);if(q(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=$e(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[L];let i=Reflect.ownKeys(r);for(let s=0;s<i.length;s++){let c=i[s],a=r[c];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[c]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[c]})}return Object.create(M(e),r)}else{let r=M(e);if(r!==null&&n)return{...e};let i=Object.create(r);return Object.assign(i,e)}}function ue(e,t=!1){return Q(e)||B(e)||!S(e)||(H(e)>1&&(e.set=e.add=e.clear=e.delete=st),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>ue(r,!0))),e}function st(){O(2)}function Q(e){return Object.isFrozen(e)}var ct={};function D(e){let t=ct[e];return t||O(0,e),t}var z;function Re(){return z}function at(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function we(e,t){t&&(D("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function se(e){ce(e),e.drafts_.forEach(lt),e.drafts_=null}function ce(e){e===z&&(z=e.parent_)}function Ae(e){return z=at(z,e)}function lt(e){let t=e[L];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Ee(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[L].modified_&&(se(t),O(4)),S(e)&&(e=J(t,e),t.parent_||X(t,e)),t.patches_&&D("Patches").generateReplacementPatches_(n[L].base_,e,t.patches_,t.inversePatches_)):e=J(t,n,[]),se(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==xe?e:void 0}function J(e,t,n){if(Q(t))return t;let r=t[L];if(!r)return K(t,(i,s)=>ve(e,r,t,i,s,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return X(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let i=r.copy_,s=i,c=!1;r.type_===3&&(s=new Set(i),i.clear(),c=!0),K(s,(a,l)=>ve(e,r,i,a,l,n,c)),X(e,i,!1),n&&e.patches_&&D("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function ve(e,t,n,r,i,s,c){if(B(i)){let a=s&&t&&t.type_!==3&&!ie(t.assigned_,r)?s.concat(r):void 0,l=J(e,i,a);if(Le(n,r,l),B(l))e.canAutoFreeze_=!1;else return}else c&&n.add(i);if(S(i)&&!Q(i)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;J(e,i),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&X(e,i)}}function X(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ue(t,n)}function ut(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Re(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=r,s=fe;n&&(i=[r],s=U);let{revoke:c,proxy:a}=Proxy.revocable(i,s);return r.draft_=a,r.revoke_=c,a}var fe={get(e,t){if(t===L)return e;let n=N(e);if(!ie(n,t))return ft(e,n,t);let r=n[t];return e.finalized_||!S(r)?r:r===ne(e.base_,t)?(re(e),e.copy_[t]=le(r,e)):r},has(e,t){return t in N(e)},ownKeys(e){return Reflect.ownKeys(N(e))},set(e,t,n){let r=Oe(N(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let i=ne(N(e),t),s=i?.[L];if(s&&s.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(ot(n,i)&&(n!==void 0||ie(e.base_,t)))return!0;re(e),ae(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 ne(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,re(e),ae(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=N(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){O(11)},getPrototypeOf(e){return M(e.base_)},setPrototypeOf(){O(12)}},U={};K(fe,(e,t)=>{U[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});U.deleteProperty=function(e,t){return U.set.call(this,e,t,void 0)};U.set=function(e,t,n){return fe.set.call(this,e[0],t,n,e[0])};function ne(e,t){let n=e[L];return(n?N(n):e)[t]}function ft(e,t,n){let r=Oe(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Oe(e,t){if(!(t in e))return;let n=M(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=M(n)}}function ae(e){e.modified_||(e.modified_=!0,e.parent_&&ae(e.parent_))}function re(e){e.copy_||(e.copy_=oe(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var dt=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let s=n;n=t;let c=this;return function(l=s,...o){return c.produce(l,u=>n.call(this,u,...o))}}typeof n!="function"&&O(6),r!==void 0&&typeof r!="function"&&O(7);let i;if(S(t)){let s=Ae(this),c=le(t,void 0),a=!0;try{i=n(c),a=!1}finally{a?se(s):ce(s)}return we(s,r),Ee(i,s)}else if(!t||typeof t!="object"){if(i=n(t),i===void 0&&(i=t),i===xe&&(i=void 0),this.autoFreeze_&&ue(i,!0),r){let s=[],c=[];D("Patches").generateReplacementPatches_(t,i,s,c),r(s,c)}return i}else O(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(c,...a)=>this.produceWithPatches(c,l=>t(l,...a));let r,i;return[this.produce(t,n,(c,a)=>{r=c,i=a}),r,i]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){S(e)||O(8),B(e)&&(e=pt(e));let t=Ae(this),n=le(e,void 0);return n[L].isManual_=!0,ce(t),n}finishDraft(e,t){let n=e&&e[L];(!n||!n.isManual_)&&O(9);let{scope_:r}=n;return we(r,t),Ee(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 i=t[n];if(i.path.length===0&&i.op==="replace"){e=i.value;break}}n>-1&&(t=t.slice(n+1));let r=D("Patches").applyPatches_;return B(e)?r(e,t):this.produce(e,i=>r(i,t))}};function le(e,t){let n=G(e)?D("MapSet").proxyMap_(e,t):q(e)?D("MapSet").proxySet_(e,t):ut(e,t);return(t?t.scope_:Re()).drafts_.push(n),n}function pt(e){return B(e)||O(10,e),Ce(e)}function Ce(e){if(!S(e)||Q(e))return e;let t=e[L],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=oe(e,t.scope_.immer_.useStrictShallowCopy_)}else n=oe(e,!0);return K(n,(r,i)=>{Le(n,r,Ce(i))}),t&&(t.finalized_=!1),n}var R=new dt,de=R.produce,Xn=R.produceWithPatches.bind(R),Hn=R.setAutoFreeze.bind(R),Gn=R.setUseStrictShallowCopy.bind(R),qn=R.applyPatches.bind(R),Qn=R.createDraft.bind(R),Zn=R.finishDraft.bind(R);var Te=(e,t,n={})=>{let r=structuredClone(e),i={},s={},{transformSelectorFirstArgument:c=l=>l,transformActionFirstArgument:a=l=>l}=n;for(let[l,o]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?i[l]=(...u)=>o(c(r),...u):s[l]=(...u)=>{r=de(r,p=>o(a(p),...u))});return{...i,...s}},Z=(e,t)=>n=>{let r=e(),i=Array.isArray(n)?n:[n];return de(r,s=>{i.forEach(c=>{t.forEach(a=>{a(s,c)})})})};var ht=()=>({}),yt=(e,t)=>{t.base&&(e.base={...t.base})},gt=(e,t)=>{t.background&&(e.background={...t.background})},mt=(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&&(e.dialogue.gui={...t.dialogue.gui}),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),t.dialogue.characterId!==void 0&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character&&(e.dialogue.character={...t.dialogue.character}),t.dialogue.clear){delete e.dialogue;return}t.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&(t.dialogue.clear&&(e.dialogue.lines=[]),e.dialogue.lines.push({content:t.dialogue.content}))},_t=(e,t)=>{t.sfx?e.sfx=t.sfx:e.sfx&&delete e.sfx},It=(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}}},bt=(e,t)=>{t.visual&&(e.visual=t.visual)},wt=(e,t)=>{t.character&&(t.character.items||delete e.character,e.character=structuredClone(t.character))},At=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Et=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},vt=(e,t)=>{t.choice?e.choice=t.choice:e.choice&&delete e.choice},xt=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},$t=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},pe=e=>Z(ht,[$t,yt,gt,_t,It,bt,mt,wt,At,Et,vt,xt])(e);var d={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},A={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},j={NOT:0};var _=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},$=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var he=e=>{if(!e||e.trim()==="")throw new _("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new _(`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 _(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Pe=e=>{if(e.trim().endsWith(" in"))throw new _(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new _(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new _(`Missing iterable expression after 'in' (got: '$for ${e}')`);let r=t.includes(",")?t.split(",").map(i=>i.trim()):[t.trim()];for(let i of r){if(!i)throw new _(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(i))throw new _(`Invalid loop syntax (got: '$for ${e}')`)}};var ke=(e,t,n=!1)=>{if(t===null)return new $(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new $(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new $(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new $(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},Ne=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new $(`Unknown function '${e}' (${n})`)};var Lt=(e,t,n={})=>{let r={},i={};n&&typeof n=="object"&&(n.functions!==void 0||n.partials!==void 0?(r=n.functions||{},i=n.partials||{}):typeof n=="object"&&(r=n));let c=b(e,{functions:r,partials:i},t,{});return c===void 0?{}:c},b=(e,t,n,r)=>{let i=t.functions||t;if(e.var&&!e.type)return E(e.var,n,r);if(e.type===d.LITERAL)return e.value;if(e.type===d.VARIABLE)return E(e.path,n,r);if(e.type===d.INTERPOLATION)return Ot(e.parts,t,n,r);switch(e.type){case d.FUNCTION:return De(e,t,n,r);case d.BINARY:return Ve(e,t,n,r);case d.UNARY:return Me(e,t,n,r);case d.CONDITIONAL:return Tt(e,t,n,r);case d.LOOP:return Dt(e,t,n,r);case d.OBJECT:return Mt(e,t,n,r);case d.ARRAY:return Bt(e,t,n,r);case d.PARTIAL:return Ft(e,t,n,r);case d.PATH_REFERENCE:return Wt(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Se=new Map,Rt=e=>{let t=[],n="",r=!1;for(let i=0;i<e.length;i++){let s=e[i];if(s==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(s==="]"){if(r&&n){let c=n.trim();if(/^\d+$/.test(c))t.push({type:"index",value:parseInt(c,10)});else if(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'")){let a=c.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:c});n=""}r=!1}else n+=s}return n&&t.push({type:"property",value:n}),t},E=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=Se.get(e);if(!r){let s=[],c="",a=0;for(let l=0;l<e.length;l++){let o=e[l];o==="["?(a++,c+=o):o==="]"?(a--,c+=o):o==="."&&a===0?c&&(s.push(c),c=""):c+=o}c&&s.push(c),r=[];for(let l of s){let o=Rt(l.trim());r.push(...o)}Se.set(e,r)}let i=t;for(let s=0;s<r.length;s++){let c=r[s];if(c.type==="property"&&c.value in n){i=n[c.value];continue}if(i==null)return;(c.type==="property"||c.type==="index")&&(i=i[c.value])}return i},Ot=(e,t,n,r)=>{let i=[];for(let s of e)if(typeof s=="string")i.push(s);else{let c=b(s,t,n,r);i.push(c!=null?String(c):"")}return i.join("")},De=(e,t,n,r)=>{let i=t.functions||t,s=i[e.name];if(!s)throw Ne(e.name,i);let c=e.args.map(a=>b(a,t,n,r));return s(...c)},F=(e,t,n,r)=>{if(e.var&&!e.type)return E(e.var,n,r);switch(e.type){case d.VARIABLE:return E(e.path,n,r);case d.LITERAL:return e.value;case d.BINARY:return Ve(e,t,n,r);case d.UNARY:return Me(e,t,n,r);case d.FUNCTION:return De(e,t,n,r);default:return b(e,t,n,r)}},Ve=(e,t,n,r)=>{if(e.op===A.AND||e.op===A.OR){let c=F(e.left,t,n,r),a=F(e.right,t,n,r);switch(e.op){case A.AND:return c&&a;case A.OR:return c||a}}let i=b(e.left,t,n,r),s=b(e.right,t,n,r);switch(e.op){case A.EQ:return i==s;case A.NEQ:return i!=s;case A.GT:return i>s;case A.LT:return i<s;case A.GTE:return i>=s;case A.LTE:return i<=s;case A.IN:return Array.isArray(s)?s.includes(i):!1;case A.ADD:if(typeof i!="number"||typeof s!="number")throw new $(`Arithmetic operations require numbers. Got ${typeof i} + ${typeof s}`);return i+s;case A.SUBTRACT:if(typeof i!="number"||typeof s!="number")throw new $(`Arithmetic operations require numbers. Got ${typeof i} - ${typeof s}`);return i-s;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Me=(e,t,n,r)=>{let i=e.op===j.NOT?F(e.operand,t,n,r):b(e.operand,t,n,r);switch(e.op){case j.NOT:return!i;default:throw new Error(`Unknown unary operator: ${e.op}`)}},Ct=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let i=e.conditions[0];if(i.type===d.VARIABLE)if(E(i.path,n,r)){let c=e.bodies[0];if(c.type===d.OBJECT&&c.properties.length<=5){let a={};for(let l of c.properties){let o=l.parsedKey?b(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===d.LITERAL)a[o]=u.value;else if(u.type===d.VARIABLE)a[o]=E(u.path,n,r);else if(u.type===d.INTERPOLATION){let f=[];for(let p of u.parts)if(typeof p=="string")f.push(p);else if(p.type===d.VARIABLE){let h=E(p.path,n,r);f.push(h!=null?String(h):"")}else{let h=b(p,t,n,r);f.push(h!=null?String(h):"")}a[o]=f.join("")}else a[o]=b(u,t,n,r)}return a}}else{let c=e.bodies[1];if(c.type===d.OBJECT&&c.properties.length<=5){let a={};for(let l of c.properties){let o=l.parsedKey?b(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===d.LITERAL)a[o]=u.value;else if(u.type===d.VARIABLE)a[o]=E(u.path,n,r);else if(u.type===d.INTERPOLATION){let f=[];for(let p of u.parts)if(typeof p=="string")f.push(p);else if(p.type===d.VARIABLE){let h=E(p.path,n,r);f.push(h!=null?String(h):"")}else{let h=b(p,t,n,r);f.push(h!=null?String(h):"")}a[o]=f.join("")}else a[o]=b(u,t,n,r)}return a}}}return null},Tt=(e,t,n,r)=>{let i=Ct(e,t,n,r);if(i!==null)return i;for(let s=0;s<e.conditions.length;s++){let c=e.conditions[s];if(c===null||F(c,t,n,r))return b(e.bodies[s],t,n,r)}return Be},Pt=(e,t)=>{let n=e.body,r=e.itemVar;if(n.type===d.CONDITIONAL&&n.conditions.length===1&&n.conditions[0].type===d.VARIABLE){let i=n.conditions[0].path,s=n.bodies[0];if(i.startsWith(r+".")){let c=i.substring(r.length+1);if(s.type===d.OBJECT&&s.properties.length<=5){for(let l of s.properties)if(l.parsedKey)return null;let a=[];for(let l=0;l<t.length;l++){let o=t[l];if(o[c]){let u={};for(let f of s.properties){let p=f.key,h=f.value;if(h.type===d.LITERAL)u[p]=h.value;else if(h.type===d.VARIABLE){let y=h.path;if(y===r)u[p]=o;else if(y.startsWith(r+".")){let g=y.substring(r.length+1);u[p]=o[g]}else return null}else if(h.type===d.INTERPOLATION){let y=[],g=!0;for(let m of h.parts)if(typeof m=="string")y.push(m);else if(m.type===d.VARIABLE){let I=m.path;if(I===r)y.push(o!=null?String(o):"");else if(I.startsWith(r+".")){let w=I.substring(r.length+1),v=o[w];y.push(v!=null?String(v):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[p]=y.join("")}else return null}a.push(u)}}return a}}}return null},kt=(e,t)=>{let n=e.body,r=e.itemVar,i=Pt(e,t);if(i!==null)return i;if(n.type===d.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let s=[],c=!0;for(let a of n.properties){let l=a.key,o=a.value;if(o.type===d.LITERAL)s.push({key:l,type:"literal",value:o.value});else if(o.type===d.VARIABLE){let u=o.path;if(u===r)s.push({key:l,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))s.push({key:l,type:"prop",prop:f});else{c=!1;break}}else{c=!1;break}}else if(o.type===d.INTERPOLATION&&o.parts.length===1){let u=o.parts[0];if(u.type===d.VARIABLE){let f=u.path;if(f===r)s.push({key:l,type:"item_string"});else if(f.startsWith(r+".")){let p=f.substring(r.length+1);if(!p.includes(".")&&!p.includes("["))s.push({key:l,type:"prop_string",prop:p});else{c=!1;break}}else{c=!1;break}}else{c=!1;break}}else{c=!1;break}}if(c){let a=new Array(t.length);if(s.length===3&&s[0].type==="prop"&&s[0].key==="id"&&s[1].type==="prop_string"&&s[1].key==="title"&&s[2].type==="prop"&&s[2].key==="completed")for(let l=0;l<t.length;l++){let o=t[l];a[l]={id:o.id,title:o.title!=null?String(o.title):"",completed:o.completed}}else for(let l=0;l<t.length;l++){let o=t[l],u={};for(let f of s)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=o;else if(f.type==="prop")u[f.key]=o[f.prop];else if(f.type==="item_string")u[f.key]=o!=null?String(o):"";else if(f.type==="prop_string"){let p=o[f.prop];u[f.key]=p!=null?String(p):""}a[l]=u}return a}}return null},Nt=(e,t,n,r,i)=>{let s=[],c=e.body;if(c.type===d.OBJECT&&c.fast!==!1){let a=e.itemVar,l=e.indexVar;for(let o=0;o<i.length;o++){let u=i[o],f={},p={...r,[a]:u,...l&&{[l]:o}};p.__paths__||(p.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let y=h.split("."),g=y[0];g in r.__paths__&&(h=r.__paths__[g],y.length>1&&(h+="."+y.slice(1).join(".")))}p.__paths__={...p.__paths__,[a]:`${h}[${o}]`,...l&&{[l]:o}};for(let y of c.properties){let g=y.parsedKey?b(y.parsedKey,t,n,p):y.key,m=y.value;if(m.type===d.LITERAL)f[g]=m.value;else if(m.type===d.VARIABLE){let I=m.path;if(I===a)f[g]=u;else if(I===l)f[g]=o;else if(I.startsWith(a+".")){let w=I.substring(a.length+1);!w.includes(".")&&!w.includes("[")?f[g]=u[w]:f[g]=E(I,n,{...r,[a]:u,...l&&{[l]:o}})}else f[g]=E(I,n,{...r,[a]:u,...l&&{[l]:o}})}else if(m.type===d.INTERPOLATION){let I=[];for(let w of m.parts)if(typeof w=="string")I.push(w);else if(w.type===d.VARIABLE){let v=w.path,T;if(v===a)T=u;else if(v===l)T=o;else if(v.startsWith(a+".")){let te=v.substring(a.length+1);!te.includes(".")&&!te.includes("[")?T=u[te]:T=E(v,n,{...r,[a]:u,...l&&{[l]:o}})}else T=E(v,n,{...r,[a]:u,...l&&{[l]:o}});I.push(T!=null?String(T):"")}else{let v={...r,[a]:u,...l&&{[l]:o}},T=b(w,t,n,v);I.push(T!=null?String(T):"")}f[g]=I.join("")}else{let I={...r,[a]:u,...l&&{[l]:o}};f[g]=b(m,t,n,I)}}s.push(f)}return s}return null},St=(e,t,n)=>{let r=e.body;if(r.type===d.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let s=r.properties[0].value;if(s.type===d.CONDITIONAL&&s.conditions.length===1&&s.conditions[0].type===d.VARIABLE&&s.conditions[0].path==="item.visible"){let c=s.bodies[0];if(c.type===d.OBJECT&&c.properties.length===2){let a=c.properties[0],l=c.properties[1];if(a.key==="id"&&a.value.type===d.VARIABLE&&a.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===d.CONDITIONAL){let o=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let p={id:f.id};f.highlighted?(p.highlight=!0,p.message=`This item is highlighted: ${f.name}`):(p.highlight=!1,p.message=f.name),o.push(p)}}return o}}}}return null},Dt=(e,t,n,r)=>{let i=b(e.iterable,t,n,r);if(!Array.isArray(i)){let o,u=!1;if(e.iterable.type===d.FUNCTION){u=!0;let p=e.iterable.args.map(h=>h.type===d.LITERAL?typeof h.value=="string"?`'${h.value}'`:String(h.value):h.type===d.VARIABLE?h.path:h.type===d.FUNCTION?`${h.name}(...)`:"?").join(", ");o=`${e.iterable.name}(${p})`}else o=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${o}`;throw ke(f,i,u)}if(!e.indexVar){let o=St(e,i,e.itemVar);if(o!==null)return o}if(!e.indexVar){let o=kt(e,i);if(o!==null)return o}let s=Nt(e,t,n,r,i);if(s!==null)return s;let c=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let o=a.split("."),u=o[0];u in r.__paths__&&(a=r.__paths__[u],o.length>1&&(a+="."+o.slice(1).join(".")))}let l=!1;e.body.type===d.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(o=>o.type===d.OBJECT&&o.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let o=0;o<i.length;o++){let u=e.indexVar?{...r,[e.itemVar]:i[o],[e.indexVar]:o}:{...r,[e.itemVar]:i[o]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${o}]`},e.indexVar&&(u.__paths__[e.indexVar]=o);let f=b(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!l){let p=f[0];c.push(p===void 0?{}:p)}else c.push(f===void 0?{}:f)}return c},Vt=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let i=e.properties[0],s=i.parsedKey?b(i.parsedKey,t,n,r):i.key,c=i.value;if(c.type===d.OBJECT&&c.properties.length<=10&&!c.whenCondition){let a={},l={},o=!0;for(let u of c.properties){let f=u.parsedKey?b(u.parsedKey,t,n,r):u.key,p=u.value;if(p.type===d.LITERAL)l[f]=p.value;else if(p.type===d.VARIABLE)l[f]=E(p.path,n,r);else if(p.type===d.INTERPOLATION){let h=[];for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===d.VARIABLE){let g=E(y.path,n,r);h.push(g!=null?String(g):"")}else{o=!1;break}if(!o)break;l[f]=h.join("")}else if(p.type===d.OBJECT&&p.properties.length<=5){let h={};for(let y of p.properties){let g=y.key,m=y.value;if(m.type===d.LITERAL)h[g]=m.value;else if(m.type===d.VARIABLE)h[g]=E(m.path,n,r);else if(m.type===d.INTERPOLATION){let I=[];for(let w of m.parts)if(typeof w=="string")I.push(w);else if(w.type===d.VARIABLE){let v=E(w.path,n,r);I.push(v!=null?String(v):"")}else{o=!1;break}if(!o)break;h[g]=I.join("")}else{o=!1;break}}if(!o)break;l[f]=h}else{o=!1;break}}if(o)return a[s]=l,a}}return null},Mt=(e,t,n,r)=>{let i=t.functions||t;if(e.whenCondition&&!F(e.whenCondition,i,n,r))return;let s=Vt(e,t,n,r);if(s!==null)return s;if(e.fast){let o={};for(let u of e.properties){let f=u.parsedKey?b(u.parsedKey,t,n,r):u.key,p=u.value;if(p.type===d.LITERAL)o[f]=p.value;else if(p.type===d.VARIABLE)o[f]=E(p.path,n,r);else if(p.type===d.INTERPOLATION){let h=[];for(let y of p.parts)if(typeof y=="string")h.push(y);else if(y.type===d.VARIABLE){let g=E(y.path,n,r);h.push(g!=null?String(g):"")}else{let g=b(y,t,n,r);h.push(g!=null?String(g):"")}o[f]=h.join("")}else o[f]=b(p,t,n,r)}return o}let c={},a=null,l=!1;for(let o of e.properties)if(!o.key.startsWith("$if ")&&!o.key.match(/^\$if\s+\w+.*:?$/)&&!o.key.startsWith("$elif")&&!o.key.startsWith("$else")&&!o.key.startsWith("$for ")){l=!0;break}for(let o of e.properties)if(o.key.startsWith("$if ")||o.key.match(/^\$if\s+\w+.*:?$/)){let u=b(o.value,t,n,r);if(!l&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(c,u)}else if(o.key.startsWith("$for ")){if(e.properties.length===1)return b(o.value,t,n,r)}else{let u=o.value;if(u&&u.type===d.OBJECT&&u.properties){let f=u.properties.find(p=>p.key.startsWith("$for "));if(f){let p=b(f.value,t,n,r);p!==void 0&&(c[o.key]=p)}else{let p=b(o.value,t,n,r);p!==void 0&&(c[o.key]=p)}}else{let f=o.parsedKey?b(o.parsedKey,t,n,r):o.key,p=b(o.value,t,n,r);p!==void 0&&(c[f]=p)}}return c},Be={},Bt=(e,t,n,r)=>{let i=[];for(let s of e.items)if(s.type===d.LOOP){let c=b(s,t,n,r);Array.isArray(c)&&s.flatten!==!1?i.push(...c):i.push(c)}else{let c=b(s,t,n,r);c!==Be&&c!==void 0&&i.push(c)}return i},Ft=(e,t,n,r)=>{let{name:i,data:s,whenCondition:c}=e,a=t.partials||{},l=t.functions||t;if(c&&!F(c,l,n,r))return;if(!a[i])throw new $(`Partial '${i}' is not defined`);let o=r._partialStack||[];if(o.includes(i))throw new $(`Circular partial reference detected: ${i}`);let u=a[i],f=n,p={...r,_partialStack:[...o,i]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(s){let h=b(s,t,n,r);f={...f,...h}}return b(u,t,f,p)},Wt=(e,t,n,r)=>{let{path:i}=e,s=i.split("."),c=s[0],a=s.slice(1);if(!r||!(c in r))throw new $(`Path reference '#{${i}}' refers to '${c}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(c in r.__paths__))throw new $(`Path reference '#{${i}}' cannot be resolved - path tracking may not be initialized properly`);let l=r.__paths__[c];if(typeof l=="number"){if(a.length>0)throw new $(`Path reference '#{${i}}' - cannot access properties on index variable '${c}'`);return String(l)}return a.length>0&&(l+="."+a.join(".")),l},ye=Lt;var zt=/\$\{([^}]*)\}/g,Ut=/#\{([^}]*)\}/g,We=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,i]=n,s=jt(i,t);return{isFunction:!0,type:d.FUNCTION,name:r,args:s}},jt=(e,t={})=>e.trim()?Yt(e).map(r=>Kt(r.trim(),t)):[],Yt=e=>{let t=[],n="",r=0,i=!1,s="";for(let c=0;c<e.length;c++){let a=e[c],l=c>0?e[c-1]:"";!i&&(a==='"'||a==="'")?(i=!0,s=a,n+=a):i&&a===s&&l!=="\\"?(i=!1,s="",n+=a):!i&&a==="("?(r++,n+=a):!i&&a===")"?(r--,n+=a):!i&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},Kt=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:d.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:d.LITERAL,value:parseFloat(e)};if(e==="true")return{type:d.LITERAL,value:!0};if(e==="false")return{type:d.LITERAL,value:!1};if(e==="null")return{type:d.LITERAL,value:null};let n=We(e,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};let r=e.trim(),i=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],s=-1,c=null;for(let{op:a,type:l}of i){let o=0;for(;o<r.length;){let u=V(r.substring(o),a);if(u===-1)break;let f=o+u;f>s&&(s=f,c={op:a,type:l}),o=f+a.length}}if(s!==-1)try{return x(r,t)}catch{return{type:d.VARIABLE,path:r}}return{type:d.VARIABLE,path:r}},ze=/^\w+\(.*\)$/,Jt=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Xt=e=>{if(!(!e||e.trim()===""||ze.test(e))&&Jt.test(e))throw e.includes("?")&&e.includes(":")?new _(`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 _(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new _(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Fe=e=>{let t=e.trim();if(ze.test(t))throw new _(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new _(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new _(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new _(`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 _(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:d.PATH_REFERENCE,path:t}},Y=(e,t={})=>{let n=e.trim();Xt(n);let r=We(n,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};if(n.includes("[")&&!/[\s+\-*/%|&?:]/.test(n)){let i=0;for(let s of n)s==="["?i++:s==="]"&&i--;if(i!==0)throw new Error("Invalid array index syntax")}return{type:d.VARIABLE,path:n}},ge=(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,(o,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(o,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let i=[...n.matchAll(zt)],s=[...n.matchAll(Ut)],c=[...i.map(o=>({match:o,type:"variable"})),...s.map(o=>({match:o,type:"pathref"}))].sort((o,u)=>o.match.index-u.match.index);if(c.length===0){let o=n;for(let u=0;u<r.length;u++)o=o.replace(`__ESCAPED_${u}__`,r[u]);return{type:d.LITERAL,value:o}}if(c.length===1&&c[0].match[0]===n&&r.length===0){let{match:o,type:u}=c[0];try{return u==="variable"?Y(o[1],t):Fe(o[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:d.LITERAL,value:n};throw f}}let a=[],l=0;for(let{match:o,type:u}of c){let[f,p]=o,h=o.index;if(h>l){let y=n.substring(l,h);for(let g=0;g<r.length;g++)y=y.replace(`__ESCAPED_${g}__`,r[g]);y&&a.push(y)}try{let y;u==="variable"?y=Y(p.trim(),t):y=Fe(p.trim()),a.push(y)}catch(y){if(y.message==="Invalid array index syntax")a.push(f);else throw y}l=h+f.length}if(l<n.length){let o=n.substring(l);for(let u=0;u<r.length;u++)o=o.replace(`__ESCAPED_${u}__`,r[u]);o&&a.push(o)}return{type:d.INTERPOLATION,parts:a}};var k=(e,t)=>typeof e=="string"?ge(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?Gt(e,t):qt(e,t):{type:d.LITERAL,value:e},Ht=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new _("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new _("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new _("Empty $each body not allowed");if(n.$partial!==void 0)throw new _("Cannot use $partial with $each at the same level. Wrap $partial in a parent object if you need conditionals.");return{[`$for ${r}`]:n}},Gt=(e,t)=>{let n=[],r=!1;for(let i=0;i<e.length;i++){let s=e[i];if(typeof s=="object"&&s!==null&&!Array.isArray(s)){if(s.$each!==void 0)try{let l=Ht(s),o=Object.keys(l);if(o.length===1&&/^\$for(?::\w+)?\s/.test(o[0])){let u=Ue(o[0],l[o[0]],t,!0);n.push(u),r=!0;continue}}catch(l){throw l instanceof _?l:new _(l.message)}let a=Object.keys(s);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let l=Ue(a[0],s[a[0]],t);n.push(l),r=!0;continue}}let c=k(s,t);n.push(c),(c.type===d.FUNCTION||c.type===d.CONDITIONAL||c.type===d.LOOP||c.type===d.PARTIAL||c.type===d.OBJECT&&!c.fast||c.type===d.ARRAY&&!c.fast)&&(r=!0)}return{type:d.ARRAY,items:n,fast:!r}},qt=(e,t)=>{let n=[],r=!1,i=null,s=Object.entries(e),c=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new _("$partial value must be a string");if(e.$partial.trim()==="")throw new _("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],o=[];for(let[I]of s)for(let w of l)if(I===w||I.startsWith(w+" ")||I.startsWith(w+"#")){o.push(w);break}if(o.length>0)throw new _(`Cannot use $partial with ${o.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...p}=e,h={},y=!1;for(let[I,w]of Object.entries(p)){let v=I;(I.startsWith("\\$")||I.startsWith("$$"))&&(v=I.slice(1)),h[v]=w,y=!0}let g=null;if(y&&(g=k(h,t),g.type===d.OBJECT)){let I=!1;for(let w of g.properties)if(w.value.type===d.VARIABLE||w.value.type===d.INTERPOLATION||w.value.type===d.FUNCTION||w.value.type===d.CONDITIONAL||w.value.type===d.OBJECT&&!w.value.fast||w.value.type===d.ARRAY&&!w.value.fast){I=!0;break}I&&(g.fast=!1)}let m={type:d.PARTIAL,name:u,data:g};if(f!==void 0){let I;if(typeof f=="string"){if(f.trim()==="")throw new _("Empty condition expression after '$when'");I=x(f,t)}else I={type:d.LITERAL,value:f};m.whenCondition=I}return m}for(let[l,o]of s)if(l==="$when"){if(i!==null)throw new _("Multiple '$when' directives on the same object are not allowed");if(o==null)throw new _("Missing condition expression after '$when'");let u=typeof o=="string"?o:JSON.stringify(o);if(u.trim()==="")throw new _("Empty condition expression after '$when'");i=x(u,t),r=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new _("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;c<s.length;){let[l,o]=s[c];if(l==="$when"){c++;continue}if(l==="$each")throw new _("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=Qt(s,c,t);n.push({key:l,value:u.node}),r=!0,c=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new _(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(l.startsWith("$elif ")||l.startsWith("$else"))throw new _(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new _("Missing condition expression after '$if'");{let u=k(o,t);(u.type===d.FUNCTION||u.type===d.CONDITIONAL||u.type===d.PARTIAL||u.type===d.OBJECT&&!u.fast||u.type===d.ARRAY&&!u.fast)&&(r=!0);let f=ge(l,t),p={key:l,value:u};(f.type!==d.LITERAL||f.value!==l)&&(p.parsedKey=f),n.push(p),c++}}}let a={type:d.OBJECT,properties:n,fast:!r};return i&&(a.whenCondition=i),a},Qt=(e,t,n={})=>{let r=[],i=[],s=t,[c,a]=e[s],l=null,o;if(c.startsWith("$if#")){let f=c.match(/^\$if#(\w+)\s+(.+)$/);if(f)l=f[1],o=f[2];else throw new _(`Invalid conditional syntax: ${c}`)}else o=c.substring(4),o.endsWith(":")&&(o=o.slice(0,-1).trim());he(o);let u=x(o,n);for(r.push(u),i.push(k(a,n)),s++;s<e.length;){let[f,p]=e[s],h=!1,y;if(l?f.startsWith(`$elif#${l} `)?(y=f.substring(`$elif#${l} `.length),y.endsWith(":")&&(y=y.slice(0,-1).trim()),h=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(h=!0,y=null):f.startsWith("$elif ")?(y=f.substring(6),y.endsWith(":")&&(y=y.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,y=null),h){if(y===null)r.push(null);else{he(y);let g=x(y,n);r.push(g)}if(i.push(k(p,n)),s++,y===null)break}else break}return{node:{type:d.CONDITIONAL,conditions:r,bodies:i,id:l},nextIndex:s}},x=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let o=e.slice(1,-1),u=0,f=!0;for(let p=0;p<o.length;p++)if(o[p]==="("?u++:o[p]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return x(o,t)}let n=V(e,"||");if(n!==-1)return{type:d.BINARY,op:A.OR,left:x(e.substring(0,n).trim(),t),right:x(e.substring(n+2).trim(),t)};let r=V(e,"&&");if(r!==-1)return{type:d.BINARY,op:A.AND,left:x(e.substring(0,r).trim(),t),right:x(e.substring(r+2).trim(),t)};let i=[{op:">=",type:A.GTE},{op:"<=",type:A.LTE},{op:"==",type:A.EQ},{op:"!=",type:A.NEQ},{op:">",type:A.GT},{op:"<",type:A.LT},{op:" in ",type:A.IN}];for(let{op:o,type:u}of i){let f=V(e,o);if(f!==-1)return{type:d.BINARY,op:u,left:x(e.substring(0,f).trim(),t),right:x(e.substring(f+o.length).trim(),t)}}let s=-1,c=null,a=[{op:" + ",type:A.ADD},{op:" - ",type:A.SUBTRACT}];for(let{op:o,type:u}of a){let f=0;for(;f<e.length;){let p=V(e.substring(f),o);if(p===-1)break;let h=f+p;h>s&&(s=h,c={op:o,type:u}),f=h+o.length}}if(s!==-1&&c)return{type:d.BINARY,op:c.type,left:x(e.substring(0,s).trim(),t),right:x(e.substring(s+c.op.length).trim(),t)};let l=[" * "," / "," % "];for(let o of l)if(V(e,o)!==-1)throw new _(`Arithmetic operations are not allowed in conditionals: "${o}"`);return e.startsWith("!")?{type:d.UNARY,op:j.NOT,operand:x(e.substring(1).trim(),t)}:je(e,t)},V=(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},Zt=e=>{if(e=e.trim(),e==="true")return{type:d.LITERAL,value:!0};if(e==="false")return{type:d.LITERAL,value:!1};if(e==="null")return{type:d.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:d.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:d.LITERAL,value:""};if(e==="{}")return{type:d.LITERAL,value:{}};if(e==="[]")return{type:d.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:d.LITERAL,value:t}:{type:d.VARIABLE,path:e}},je=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return Y(n,t);let i=Zt(n);if(i.type===d.LITERAL)return i;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:d.VARIABLE,path:n};try{return Y(n,t)}catch(s){if(s.message&&s.message.includes("not supported"))return i;throw s}},en=(e,t=!1)=>{let n=t?"$each":"$for";try{Pe(e)}catch(r){if(r instanceof _&&t){let i=r.message.replace(/\$for/g,"$each");throw new _(i.replace("Parse Error: ",""))}throw r}},Ue=(e,t,n,r=!1)=>{let i=/^\$for(?::(\w+))?\s+(.+)$/,s=e.match(i);if(!s){let m=r?"$each":"$for";throw new _(`Invalid loop syntax (got: '${e.replace("$for",m)}')`)}let c=s[1],a=s[2].trim();en(a,r);let l=a.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let m=r?"$each":"$for";throw new _(`Invalid loop syntax - missing 'in' keyword (got: '${m} ${a}')`)}let o=l[1].trim(),u=l[2].trim(),f,p=null;if(o.includes(",")){let m=o.split(",").map(I=>I.trim());if(m.length!==2)throw new _(`Invalid loop variables: ${o}. Expected format: "item" or "item, index"`);f=m[0],p=m[1]}else f=o;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new _(`Reserved variable name: ${f}`);if(p&&h.includes(p))throw new _(`Reserved variable name: ${p}`);let y=je(u,n),g=k(t,n);return{type:d.LOOP,itemVar:f,indexVar:p,iterable:y,body:g,flatten:c!=="nested"}};var tn=(e,t={})=>{let{functions:n={}}=t;return k(e,n)},ee=tn;var me={};rt(me,{now:()=>nn});var nn=()=>Date.now();var rn=(e,t,n={})=>{let{functions:r={},partials:i={}}=n,s={...me,...r},c=ee(e,{functions:s}),a={};for(let[l,o]of Object.entries(i))a[l]=ee(o,{functions:s});return ye(c,t,{functions:s,partials:a})},P=rn;var _e={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n}))},on=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[]}),sn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.base){let i=r.find(s=>s.id==="story");if(!i)return e;if(t.base.resourceId){let s=n?.layouts[t.base.resourceId];s&&i.children.unshift({id:"base",type:"container",children:s.elements})}}return e},cn=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:i,autoMode:s,skipMode:c,currentLocalizationPackageId:a})=>{let{elements:l}=e,o=e.animations||[];if(t.background){let u=l.find(f=>f.id==="story");if(!u)return e;if(t.background.resourceId){let{images:f={}}=r,p=f[t.background.resourceId];p&&u.children.push({id:`bg-cg-${t.background.resourceId}`,type:"sprite",x:0,y:0,src:p.fileId,width:p.width,height:p.height})}if(t.background.resourceId){let{layouts:f={}}=r,p=f[t.background.resourceId];p&&u.children.push({id:`bg-cg-${t.background.resourceId}`,type:"container",children:p.elements})}if(t.background.animations){if(t.background.animations.in){let f=t.background.animations.in.resourceId,p=r?.tweens[f];p&&o.push({id:"bg-cg-animation-in",type:"tween",targetId:`bg-cg-${t.background.resourceId}`,properties:p.properties})}if(t.background.animations.out){let f=t.background.animations.out.resourceId,p=n?.background?.resourceId,h=r?.tweens[f];h&&p&&o.push({id:"bg-cg-animation-out",type:"tween",targetId:`bg-cg-${p}`,properties:h.properties})}if(t.background.animations.update){let f=t.background.animations.update.resourceId,p=r?.tweens[f];p&&o.push({id:"bg-cg-animation-update",type:"tween",targetId:`bg-cg-${t.background.resourceId}`,properties:p.properties})}}}return e},an=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,i=e.animations||[];if(t.character&&n){let s=r.find(a=>a.id==="story");if(!s)return e;let c=t.character.items||[];for(let a of c){let{transformId:l,sprites:o}=a;if(a.animations&&a.animations.out&&!o&&!l){let h=a.animations.out.resourceId,y=n?.tweens[h];if(y){let g={id:"character-animation-out",type:"tween",targetId:`character-container-${a.id}`,properties:y.properties};i.push(g)}continue}if(!o||o.length===0||!l){console.warn("Character item missing sprites or transformId:",a);continue}let u=o.map(({resourceId:h})=>h),f=n.transforms[l];if(!f){console.warn("Transform not found:",l);continue}let p={type:"container",id:`character-container-${a.id}`,x:f.x,y:f.y,anchorX:f.anchorX,anchorY:f.anchorY,rotation:f.rotation,scaleX:f.scaleX,scaleY:f.scaleY,children:[]};for(let h of o){let y=n.images[h.resourceId];if(!y){console.warn(`Image resource not found: ${h.resourceId}`);continue}p.children.push({type:"sprite",id:`${a.id}-${h.id}`,src:y.fileId,width:y.width,height:y.height,x:0,y:0})}if(s.children.push(p),a.animations){if(a.animations.in){let h=a.animations.in.resourceId,y=n?.tweens[h];y&&i.push({id:"character-animation-in",type:"tween",targetId:`character-container-${a.id}`,properties:y.properties})}if(a.animations.update){let h=a.animations.update.resourceId,y=n?.tweens[h];if(y){let g={id:"character-animation-update",type:"tween",targetId:`character-container-${a.id}`,properties:y.properties};i.push(g)}}}}}return e},ln=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,i=e.animations||[];if(t.visual&&n){let s=r.find(a=>a.id==="story");if(!s)return e;let c=t.visual.items;for(let a of c){if(a.resourceId){let{images:l={}}=n,o=l[a.resourceId];if(o){let u=n.transforms[a.transformId];s.children.push({id:`visual-${a.id}`,type:"sprite",src:o.fileId,width:o.width,height:o.height,x:u.x,y:u.y,anchorX:u.anchorX,anchorY:u.anchorY,rotation:u.rotation,scaleX:u.scaleX,scaleY:u.scaleY})}}if(a.resourceId){let{layouts:l={}}=n,o=l[a.resourceId];if(o){let u=n.transforms[a.transformId];s.children.push({id:`visual-${a.id}`,type:"container",children:o.elements,x:u.x,y:u.y,anchorX:u.anchorX,anchorY:u.anchorY,rotation:u.rotation,scaleX:u.scaleX,scaleY:u.scaleY})}}if(a.animations){if(a.animations.in){let l=a.animations.in.resourceId||a.animations.in,o=n?.tweens[l];o&&i.push({id:`${a.id}-animation`,type:"tween",targetId:`visual-${a.id}`,properties:o.properties})}if(a.animations.out){let l=a.animations.out.resourceId||a.animations.out,o=n?.tweens[l];o&&i.push({id:`${a.id}-animation-2`,type:"tween",targetId:`visual-${a.id}`,properties:o.properties})}}}}return e},un=(e,{presentationState:t,resources:n={},dialogueUIHidden:r,autoMode:i,skipMode:s,l10n:c,variables:a})=>{let{elements:l}=e;if(!t.dialogue||r)return e;let o=l.find(u=>u.id==="story");if(!o)return e;if(t.dialogue.gui&&t.dialogue.gui.resourceId){let{layouts:u={}}=n,f=u[t.dialogue.gui.resourceId];if(f){let p;t.dialogue.characterId&&(p=n.characters[t.dialogue.characterId]),t.dialogue.character&&(p={...p,name:t.dialogue.character.name});let h={elements:f.elements},y={variables:a,autoMode:i,skipMode:s,dialogue:{character:{name:p?.name||""},content:t.dialogue?.content||[{text:""}],lines:t.dialogue?.lines||[]},l10n:c},g=P(h,y,{functions:_e});g=P(g,{l10n:c});let m=g?.elements;if(Array.isArray(m))for(let I of m)o.children.push(structuredClone(I));else m&&o.children.push(structuredClone(m))}}return e},fn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.choice&&n){let i=r.find(o=>o.id==="story");if(!i)return e;let s=n?.layouts[t.choice.resourceId];if(!s||!s.elements)return e;let c={elements:s.elements},l=P(c,{choice:{items:t.choice.items}})?.elements;if(Array.isArray(l))for(let o of l)i.children.push(structuredClone(o));else l&&i.children.push(structuredClone(l))}return e},dn=(e,{presentationState:t,resources:n})=>{let{elements:r,audio:i}=e;if(t.bgm&&n){if(!r.find(a=>a.id==="story"))return e;let c=n.sounds[t.bgm.resourceId];if(!c)return e;i.push({id:"bgm",type:"sound",src:c.fileId,loop:t.bgm.loop??!0,volume:t.bgm.volume??500,delay:t.bgm.delay??null})}return e},pn=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let i=t.sfx.items;for(let s of i){let c=n.sounds?.[s.resourceId];c&&r.push({id:s.id,type:"sound",src:c.fileId,loop:s.loop??c.loop??!0,volume:s.volume??c.volume??500,delay:s.delay??c.delay??null})}}return e},hn=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:i,volume:s,loop:c}=t.voice;return r.push({id:`voice-${i}`,type:"sound",src:i,volume:s??500,loop:c??!1}),e},yn=(e,{presentationState:t,resources:n={},variables:r,autoMode:i,skipMode:s,currentLocalizationPackageId:c})=>{let{elements:a}=e,l=e.animations||[];if(t.layout){let o=a.find(g=>g.id==="story");if(!o)return e;let u=n.layouts[t.layout.resourceId];if(!u)return e;Array.isArray(u.transitions)&&u.transitions.forEach(g=>{l.push(g)});let f={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:u.elements||[]},h=P(f,{variables:r,autoMode:i,skipMode:s,currentLocalizationPackageId:c},{functions:_e});h=P(h,{i18n:{}});let y=g=>{let m={...g};return g.src&&g.src.startsWith("file:")&&(m.src=g.src),g.children&&Array.isArray(g.children)&&(m.children=g.children.map(y)),m};o.children.push(y(h))}return e},gn=(e,{resources:t={},variables:n,autoMode:r,skipMode:i,currentLocalizationPackageId:s})=>{let{elements:c}=e,a=e.animations||[],l=[];return l&&l.length>0&&l.forEach((o,u)=>{if(o.resourceType==="layout"){let f=t.layouts[o.resourceId];if(!f){console.warn(`Modal layout not found: ${o.resourceId}`);return}Array.isArray(f.transitions)&&f.transitions.forEach(m=>{a.push(m)});let p={id:`modal-${u}`,type:"container",x:0,y:0,children:f.elements||[]},y=P(p,{variables:n,autoMode:r,skipMode:i,currentLocalizationPackageId:s},{functions:_e});y=P(y,{i18n:{}});let g=m=>{let I={...m};if(m.src&&m.src.startsWith("file:")){let w=m.src.replace("file:","");I.src=resolveFile(w)}return m.children&&Array.isArray(m.children)&&(I.children=m.children.map(g)),I};c.push(g(y))}}),e},Ye=e=>Z(on,[sn,cn,an,ln,un,fn,yn,dn,pn,hn,gn])(e);var mn=e=>{let{global:{currentLocalizationPackageId:t},projectData:n}=e,r={sceneId:n.story.initialSceneId,sectionId:n.story.scenes[n.story.initialSceneId].initialSectionId,lineId:n.story.scenes[n.story.initialSceneId].sections[n.story.scenes[n.story.initialSceneId].initialSectionId].lines[0].id};return{projectData:n,global:{isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,dialogueUIHidden:!1,currentLocalizationPackageId:t,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1}},saveSlots:{}},contexts:[{currentPointerMode:"read",pointers:{read:r,history:{sectionId:void 0,lineId:void 0,historySequenceIndex:void 0}},historySequence:[{sectionId:"..."}],configuration:{},views:[],bgm:{resourceId:void 0},variables:{}}]}},_n=({state:e})=>e.global.pendingEffects,Ke=({state:e})=>e.global.skipMode,In=({state:e})=>e.global.autoMode,Je=({state:e})=>e.global.dialogueUIHidden,bn=({state:e})=>e.global.currentLocalizationPackageId,wn=({state:e},t)=>{let{sectionId:n,lineId:r}=t,i=e.global.viewedRegistry.sections.find(l=>l.sectionId===n);if(!i)return!1;if(i.lastLineId===void 0||r===void 0)return!0;let s=C({state:e},{sectionId:n});if(!s||!s.lines||!Array.isArray(s.lines))return!1;let c=s.lines.findIndex(l=>l.id===i.lastLineId),a=s.lines.findIndex(l=>l.id===r);return c===-1||a===-1?i.lastLineId===r:a<c},An=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(i=>i.resourceId===n)},En=({state:e})=>e.global.nextLineConfig,vn=({state:e})=>e.global.saveSlots,xn=({state:e},t)=>{let{slotKey:n}=t;return e.global.saveSlots[n]},W=({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}},C=({state:e},t)=>{let{sectionId:n}=t,r=e.projectData?.story?.scenes||{};for(let i in r){let s=r[i];if(s.sections&&s.sections[n])return s.sections[n]}},$n=({state:e})=>{let t=W({state:e});if(!t?.pointer)return;let{sectionId:n,lineId:r}=t.pointer,i=C({state:e},{sectionId:n});if(!(!i?.lines||!Array.isArray(i.lines)))return i.lines.find(s=>s.id===r)},Xe=({state:e})=>{let{sectionId:t,lineId:n}=W({state:e}).pointer,i=C({state:e},{sectionId:t})?.lines||[],s=i.findIndex(o=>o.id===n),c=i.slice(0,s+1);console.log("currentLines",c);let a=c.map(o=>{let u=o.actions||{},f={};return Object.keys(u).forEach(p=>{f[p]=u[p]}),f});return pe(a)},Ln=({state:e})=>{let{sectionId:t,lineId:n}=W({state:e}).pointer,i=C({state:e},{sectionId:t})?.lines||[],s=i.findIndex(l=>l.id===n);if(s<=0)return null;let a=i.slice(0,s).map(l=>{let o=l.actions||{},u={};return Object.keys(o).forEach(f=>{u[f]=o[f]}),u});return pe(a)},Rn=({state:e})=>{let t=Xe({state:e}),n=Ln({state:e});console.log("presentationState",t);let r=Ye({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,l10n:e.projectData.l10n.packages[e.global.currentLocalizationPackageId]});return console.log("renderState",r),r},He=({state:e})=>(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.pendingEffects.push({name:"startAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Ge=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),On=({state:e})=>(e.global.autoMode?Ge({state:e}):He({state:e}),e),qe=({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),Qe=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Cn=({state:e})=>(Ke({state:e})?Qe({state:e}):qe({state:e}),e),Ze=({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),Tn=({state:e})=>(Je({state:e})?Ze({state:e}):et({state:e}),e),Pn=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},kn=({state:e})=>(e.global.pendingEffects=[],e),Nn=({state:e},t)=>(e.global.pendingEffects.push(t),e),Sn=({state:e},t)=>{let{sectionId:n,lineId:r}=t,i=e.global.viewedRegistry.sections.find(s=>s.sectionId===n);return i?i.lastLineId=r:e.global.viewedRegistry.sections.push({sectionId:n,lastLineId:r}),e.global.pendingEffects.push({name:"render"}),e},Dn=({state:e},t)=>{let{resourceId:n}=t;return e.global.viewedRegistry.resources.find(i=>i.resourceId===n)||e.global.viewedRegistry.resources.push({resourceId:n}),e.global.pendingEffects.push({name:"render"}),e},Vn=({state:e},t)=>{let{manual:n,auto:r}=t;return n&&r?e.global.nextLineConfig={manual:n,auto:r}:(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r)),e.global.pendingEffects.push({name:"render"}),e},Mn=({state:e},t)=>{let{slotKey:n,date:r,image:i,state:s}=t;return e.global.saveSlots[n]={slotKey:n,date:r,image:i,state:s},e.global.pendingEffects.push({name:"render"}),e},Bn=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},Fn=({state:e},t)=>{let{sectionId:n,lineId:r}=t;if(!r)return console.warn("jumpToLine requires lineId parameter"),e;let i=e.contexts[e.contexts.length-1];if(!i)return console.warn("No context available for jumpToLine"),e;let s=n||i.pointers.read?.sectionId;if(n&&!C({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let c=C({state:e},{sectionId:s});return!c?.lines||!Array.isArray(c.lines)?(console.warn(`Section ${s} has no lines`),e):c.lines.find(l=>l.id===r)?(i.pointers.read={sectionId:s,lineId:r},e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e):(console.warn(`Line not found: ${r} in section ${s}`),e)},Wn=({state:e},t)=>{let{item:n}=t,r=e.contexts[e.contexts.length-1];return r&&r.historySequence&&r.historySequence.push(n),e.global.pendingEffects.push({name:"render"}),e},zn=({state:e})=>{if(e.global.nextLineConfig?.auto?.enabled!==!0||e.global.nextLineConfig?.auto?.trigger!=="fromComplete")return e;let t=W({state:e})?.pointer,n=t?.sectionId,i=C({state:e},{sectionId:n})?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=e.contexts[e.contexts.length-1];l&&(l.pointers.read={sectionId:n,lineId:a.id}),e.global.isLineCompleted=!1,e.global.nextLineConfig.auto={},e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}return e},Un=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;let t=W({state:e})?.pointer,n=t?.sectionId,i=C({state:e},{sectionId:n})?.lines||[],c=i.findIndex(a=>a.id===t?.lineId)+1;if(c<i.length){let a=i[c],l=e.contexts[e.contexts.length-1];l&&(l.pointers.read={sectionId:n,lineId:a.id}),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}return e},jn=({state:e})=>(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e),Yn=({state:e},t)=>{let{sectionId:n}=t,r=C({state:e},{sectionId:n});if(!r||!r.lines||r.lines.length===0)return e;let i=r.lines,s=e.contexts[e.contexts.length-1];if(!s||!s.pointers)return e;let c=s.pointers.history||s.pointers.read;if(s.currentPointerMode!=="history"||!s.pointers.history){if(!c)return e;s.currentPointerMode="history",s.pointers.history={sectionId:n,lineId:c?.lineId};let u=i.findIndex(f=>f.id===c.lineId)-1;if(u>=0&&u<i.length){let f=i[u];s.pointers.history={sectionId:n,lineId:f.id}}return e.global.pendingEffects.push({name:"render"}),e}let l=i.findIndex(o=>o.id===s.pointers.history.lineId)-1;if(l>=0&&l<i.length){let o=i[l];s.pointers.history={sectionId:n,lineId:o.id},e.global.pendingEffects.push({name:"render"})}return e},Kn=({state:e},t)=>{let{sectionId:n}=t,r=C({state:e},{sectionId:n});if(!r)return console.warn(`Section not found: ${n}`),e;let i=r.lines?.[0];if(!i)return console.warn(`Section ${n} has no lines`),e;let s=e.contexts[e.contexts.length-1];return s&&(s.pointers.read={sectionId:n,lineId:i.id}),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},tt=e=>{let t=mn(e);return Te(t,{selectPendingEffects:_n,selectSkipMode:Ke,selectAutoMode:In,selectDialogueUIHidden:Je,selectCurrentLocalizationPackageId:bn,selectIsLineViewed:wn,selectIsResourceViewed:An,selectNextLineConfig:En,selectSaveSlots:vn,selectSaveSlot:xn,selectCurrentPointer:W,selectSection:C,selectCurrentLine:$n,selectPresentationState:Xe,selectRenderState:Rn,startAutoMode:He,stopAutoMode:Ge,toggleAutoMode:On,startSkipMode:qe,stopSkipMode:Qe,toggleSkipMode:Cn,showDialogueUI:Ze,hideDialogueUI:et,toggleDialogueUI:Tn,setCurrentLocalizationPackageId:Pn,clearPendingEffects:kn,appendPendingEffect:Nn,addViewedLine:Sn,addViewedResource:Dn,setNextLineConfig:Vn,replaceSaveSlot:Mn,updateProjectData:Bn,sectionTransition:Kn,jumpToLine:Fn,addToHistory:Wn,nextLine:Un,nextLineFromCompleted:zn,markLineCompleted:jn,prevLine:Yn},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Ie(e){let t,{handlePendingEffects:n}=e,r=({initialState:o})=>{t=tt(o),t.appendPendingEffect({name:"render"}),l(),n(t.selectPendingEffects()),t.clearPendingEffects()},i=()=>t.selectPresentationState(),s=()=>t.selectRenderState(),c=(o,u)=>{t[o]&&(t[o](u),n(t.selectPendingEffects()),t.clearPendingEffects())},a=o=>{Object.entries(o).forEach(([u,f])=>{c(u,f)})},l=()=>{let o=t.selectCurrentLine();o&&o.actions&&a(o.actions)};return{init:r,handleAction:c,handleActions:a,selectRenderState:s,selectPresentationState:i,handleLineActions:l}}var Mr=Ie;export{Mr as default};
1
+ var dt=Object.defineProperty;var pt=(e,t)=>{for(var n in t)dt(e,n,{get:t[n],enumerable:!0})};var ke=Symbol.for("immer-nothing"),Ae=Symbol.for("immer-draftable"),$=Symbol.for("immer-state");function C(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var M=Object.getPrototypeOf;function B(e){return!!e&&!!e[$]}function T(e){return e?Ce(e)||Array.isArray(e)||!!e[Ae]||!!e.constructor?.[Ae]||G(e)||q(e):!1}var ht=Object.prototype.constructor.toString();function Ce(e){if(!e||typeof e!="object")return!1;let t=M(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)===ht}function K(e,t){X(e)===0?Reflect.ownKeys(e).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function X(e){let t=e[$];return t?t.type_:Array.isArray(e)?1:G(e)?2:q(e)?3:0}function ie(e,t){return X(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Re(e,t,n){let r=X(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function gt(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function G(e){return e instanceof Map}function q(e){return e instanceof Set}function P(e){return e.copy_||e.base_}function se(e,t){if(G(e))return new Map(e);if(q(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let n=Ce(e);if(t===!0||t==="class_only"&&!n){let r=Object.getOwnPropertyDescriptors(e);delete r[$];let o=Reflect.ownKeys(r);for(let i=0;i<o.length;i++){let l=o[i],a=r[l];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(r[l]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[l]})}return Object.create(M(e),r)}else{let r=M(e);if(r!==null&&n)return{...e};let o=Object.create(r);return Object.assign(o,e)}}function fe(e,t=!1){return Q(e)||B(e)||!T(e)||(X(e)>1&&(e.set=e.add=e.clear=e.delete=yt),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>fe(r,!0))),e}function yt(){C(2)}function Q(e){return Object.isFrozen(e)}var mt={};function V(e){let t=mt[e];return t||C(0,e),t}var U;function Se(){return U}function bt(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function xe(e,t){t&&(V("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ae(e){le(e),e.drafts_.forEach(It),e.drafts_=null}function le(e){e===U&&(U=e.parent_)}function Le(e){return U=bt(U,e)}function It(e){let t=e[$];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $e(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[$].modified_&&(ae(t),C(4)),T(e)&&(e=H(t,e),t.parent_||J(t,e)),t.patches_&&V("Patches").generateReplacementPatches_(n[$].base_,e,t.patches_,t.inversePatches_)):e=H(t,n,[]),ae(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==ke?e:void 0}function H(e,t,n){if(Q(t))return t;let r=t[$];if(!r)return K(t,(o,i)=>Oe(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return J(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),K(i,(a,c)=>Oe(e,r,o,a,c,n,l)),J(e,o,!1),n&&e.patches_&&V("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function Oe(e,t,n,r,o,i,l){if(B(o)){let a=i&&t&&t.type_!==3&&!ie(t.assigned_,r)?i.concat(r):void 0,c=H(e,o,a);if(Re(n,r,c),B(c))e.canAutoFreeze_=!1;else return}else l&&n.add(o);if(T(o)&&!Q(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;H(e,o),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&J(e,o)}}function J(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&fe(t,n)}function wt(e,t){let n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Se(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=de;n&&(o=[r],i=W);let{revoke:l,proxy:a}=Proxy.revocable(o,i);return r.draft_=a,r.revoke_=l,a}var de={get(e,t){if(t===$)return e;let n=P(e);if(!ie(n,t))return _t(e,n,t);let r=n[t];return e.finalized_||!T(r)?r:r===re(e.base_,t)?(oe(e),e.copy_[t]=ue(r,e)):r},has(e,t){return t in P(e)},ownKeys(e){return Reflect.ownKeys(P(e))},set(e,t,n){let r=Ne(P(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let o=re(P(e),t),i=o?.[$];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(gt(n,o)&&(n!==void 0||ie(e.base_,t)))return!0;oe(e),ce(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 re(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,oe(e),ce(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=P(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){C(11)},getPrototypeOf(e){return M(e.base_)},setPrototypeOf(){C(12)}},W={};K(de,(e,t)=>{W[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});W.deleteProperty=function(e,t){return W.set.call(this,e,t,void 0)};W.set=function(e,t,n){return de.set.call(this,e[0],t,n,e[0])};function re(e,t){let n=e[$];return(n?P(n):e)[t]}function _t(e,t,n){let r=Ne(t,n);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Ne(e,t){if(!(t in e))return;let n=M(e);for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=M(n)}}function ce(e){e.modified_||(e.modified_=!0,e.parent_&&ce(e.parent_))}function oe(e){e.copy_||(e.copy_=se(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var vt=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(c=i,...s){return l.produce(c,u=>n.call(this,u,...s))}}typeof n!="function"&&C(6),r!==void 0&&typeof r!="function"&&C(7);let o;if(T(t)){let i=Le(this),l=ue(t,void 0),a=!0;try{o=n(l),a=!1}finally{a?ae(i):le(i)}return xe(i,r),$e(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===ke&&(o=void 0),this.autoFreeze_&&fe(o,!0),r){let i=[],l=[];V("Patches").generateReplacementPatches_(t,o,i,l),r(i,l)}return o}else C(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(l,...a)=>this.produceWithPatches(l,c=>t(c,...a));let r,o;return[this.produce(t,n,(l,a)=>{r=l,o=a}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){T(e)||C(8),B(e)&&(e=Et(e));let t=Le(this),n=ue(e,void 0);return n[$].isManual_=!0,le(t),n}finishDraft(e,t){let n=e&&e[$];(!n||!n.isManual_)&&C(9);let{scope_:r}=n;return xe(r,t),$e(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=V("Patches").applyPatches_;return B(e)?r(e,t):this.produce(e,o=>r(o,t))}};function ue(e,t){let n=G(e)?V("MapSet").proxyMap_(e,t):q(e)?V("MapSet").proxySet_(e,t):wt(e,t);return(t?t.scope_:Se()).drafts_.push(n),n}function Et(e){return B(e)||C(10,e),Pe(e)}function Pe(e){if(!T(e)||Q(e))return e;let t=e[$],n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=se(e,t.scope_.immer_.useStrictShallowCopy_)}else n=se(e,!0);return K(n,(r,o)=>{Re(n,r,Pe(o))}),t&&(t.finalized_=!1),n}var O=new vt,pe=O.produce,Rr=O.produceWithPatches.bind(O),Sr=O.setAutoFreeze.bind(O),Nr=O.setUseStrictShallowCopy.bind(O),Pr=O.applyPatches.bind(O),Tr=O.createDraft.bind(O),Vr=O.finishDraft.bind(O);var Te=(e,t,n={})=>{let r=structuredClone(e),o={},i={},{transformSelectorFirstArgument:l=c=>c,transformActionFirstArgument:a=c=>c}=n;for(let[c,s]of Object.entries(t))c!=="createInitialState"&&(c.startsWith("select")?o[c]=(...u)=>s(l(r),...u):i[c]=(...u)=>{r=pe(r,d=>s(a(d),...u))});return{...o,...i}},Z=(e,t)=>n=>{let r=e(),o=Array.isArray(n)?n:[n];return pe(r,i=>{o.forEach(l=>{t.forEach(a=>{a(i,l)})})})};var At=(e,t)=>{if(e.default!==void 0)return e.default;let n=["number","boolean","string"];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""}},Ve=e=>{let t={},n={};return e.resources?.variables?(Object.entries(e.resources.variables).forEach(([r,o])=>{let i=At(o,r);o.scope==="context"?t[r]=i:n[r]=i}),{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}):{contextVariableDefaultValues:t,globalVariablesDefaultValues:n}},De=(e,t)=>Object.fromEntries(Object.entries({...e,...t}).map(([n,r])=>[n,String(r)])),Me=(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(", ")}`)},Be=(e,t,n)=>{let r={number:["set","increment","decrement","multiply","divide"],boolean:["set","toggle"],string:["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(", ")}`)},je=(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}`)}},he=(e,t,n)=>Object.fromEntries(Object.entries(e).filter(([r])=>t?.[r]?.scope===n));var xt=()=>({}),Lt=(e,t)=>{t.base&&(e.base={...t.base})},$t=(e,t)=>{t.background&&(e.background={...t.background})},Ot=(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&&(e.dialogue.gui={...t.dialogue.gui}),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),t.dialogue.characterId!==void 0&&(e.dialogue.characterId=t.dialogue.characterId),t.dialogue.character&&(e.dialogue.character={...t.dialogue.character}),t.dialogue.clear){delete e.dialogue;return}t.dialogue?.mode==="nvl"&&t.dialogue.content!==void 0&&(t.dialogue.clear&&(e.dialogue.lines=[]),e.dialogue.lines.push({content:t.dialogue.content}))},kt=(e,t)=>{t.sfx?e.sfx=t.sfx:e.sfx&&delete e.sfx},Ct=(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}}},Rt=(e,t)=>{t.visual&&(e.visual=t.visual)},St=(e,t)=>{t.character&&(t.character.items||delete e.character,e.character=structuredClone(t.character))},Nt=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},Pt=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},Tt=(e,t)=>{t.choice?e.choice=t.choice:e.choice&&delete e.choice},Vt=(e,t)=>{t.keyboard&&(e.keyboard=t.keyboard)},Dt=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Mt=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},ge=e=>Z(xt,[Mt,Lt,$t,kt,Ct,Rt,Ot,St,Nt,Pt,Tt,Vt,Dt])(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},v={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8,ADD:10,SUBTRACT:11},z={NOT:0};var b=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},L=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var ye=e=>{if(!e||e.trim()==="")throw new b("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let n=e.includes("===")?"==":"!=";throw new b(`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 b(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Fe=e=>{if(e.trim().endsWith(" in"))throw new b(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new b(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,n]=e.split(" in ");if(!n||n.trim()==="")throw new b(`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 b(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(o))throw new b(`Invalid loop syntax (got: '$for ${e}')`)}};var Ue=(e,t,n=!1)=>{if(t===null)return new L(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new L(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return n?new L(`Cannot iterate over non-array value in loop '${e}' - got ${r} instead`):new L(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},We=(e,t)=>{let n=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new L(`Unknown function '${e}' (${n})`)};var Bt=(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=_(e,{functions:r,partials:o},t,{});return l===void 0?{}:l},_=(e,t,n,r)=>{let o=t.functions||t;if(e.var&&!e.type)return E(e.var,n,r);if(e.type===p.LITERAL)return e.value;if(e.type===p.VARIABLE)return E(e.path,n,r);if(e.type===p.INTERPOLATION)return Ft(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return Ye(e,t,n,r);case p.BINARY:return Ke(e,t,n,r);case p.UNARY:return He(e,t,n,r);case p.CONDITIONAL:return Wt(e,t,n,r);case p.LOOP:return Jt(e,t,n,r);case p.OBJECT:return Gt(e,t,n,r);case p.ARRAY:return qt(e,t,n,r);case p.PARTIAL:return Qt(e,t,n,r);case p.PATH_REFERENCE:return Zt(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},ze=new Map,jt=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 a=l.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:l});n=""}r=!1}else n+=i}return n&&t.push({type:"property",value:n}),t},E=(e,t,n)=>{if(!e)return;if(e in n)return n[e];let r=ze.get(e);if(!r){let i=[],l="",a=0;for(let c=0;c<e.length;c++){let s=e[c];s==="["?(a++,l+=s):s==="]"?(a--,l+=s):s==="."&&a===0?l&&(i.push(l),l=""):l+=s}l&&i.push(l),r=[];for(let c of i){let s=jt(c.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},Ft=(e,t,n,r)=>{let o=[];for(let i of e)if(typeof i=="string")o.push(i);else{let l=_(i,t,n,r);o.push(l!=null?String(l):"")}return o.join("")},Ye=(e,t,n,r)=>{let o=t.functions||t,i=o[e.name];if(!i)throw We(e.name,o);let l=e.args.map(a=>_(a,t,n,r));return i(...l)},j=(e,t,n,r)=>{if(e.var&&!e.type)return E(e.var,n,r);switch(e.type){case p.VARIABLE:return E(e.path,n,r);case p.LITERAL:return e.value;case p.BINARY:return Ke(e,t,n,r);case p.UNARY:return He(e,t,n,r);case p.FUNCTION:return Ye(e,t,n,r);default:return _(e,t,n,r)}},Ke=(e,t,n,r)=>{if(e.op===v.AND||e.op===v.OR){let l=j(e.left,t,n,r),a=j(e.right,t,n,r);switch(e.op){case v.AND:return l&&a;case v.OR:return l||a}}let o=_(e.left,t,n,r),i=_(e.right,t,n,r);switch(e.op){case v.EQ:return o==i;case v.NEQ:return o!=i;case v.GT:return o>i;case v.LT:return o<i;case v.GTE:return o>=i;case v.LTE:return o<=i;case v.IN:return Array.isArray(i)?i.includes(o):!1;case v.ADD:if(typeof o!="number"||typeof i!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof o} + ${typeof i}`);return o+i;case v.SUBTRACT:if(typeof o!="number"||typeof i!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof o} - ${typeof i}`);return o-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},He=(e,t,n,r)=>{let o=e.op===z.NOT?j(e.operand,t,n,r):_(e.operand,t,n,r);if(e.op===z.NOT)return!o;throw new Error(`Unknown unary operator: ${e.op}`)},Ut=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let o=e.conditions[0];if(o.type===p.VARIABLE)if(E(o.path,n,r)){let l=e.bodies[0];if(l.type===p.OBJECT&&l.properties.length<=5){let a={};for(let c of l.properties){let s=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)a[s]=u.value;else if(u.type===p.VARIABLE)a[s]=E(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=E(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}a[s]=f.join("")}else a[s]=_(u,t,n,r)}return a}}else{let l=e.bodies[1];if(l.type===p.OBJECT&&l.properties.length<=5){let a={};for(let c of l.properties){let s=c.parsedKey?_(c.parsedKey,t,n,r):c.key,u=c.value;if(u.type===p.LITERAL)a[s]=u.value;else if(u.type===p.VARIABLE)a[s]=E(u.path,n,r);else if(u.type===p.INTERPOLATION){let f=[];for(let d of u.parts)if(typeof d=="string")f.push(d);else if(d.type===p.VARIABLE){let h=E(d.path,n,r);f.push(h!=null?String(h):"")}else{let h=_(d,t,n,r);f.push(h!=null?String(h):"")}a[s]=f.join("")}else a[s]=_(u,t,n,r)}return a}}}return null},Wt=(e,t,n,r)=>{let o=Ut(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||j(l,t,n,r))return _(e.bodies[i],t,n,r)}return Je},zt=(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 c of i.properties)if(c.parsedKey)return null;let a=[];for(let c=0;c<t.length;c++){let s=t[c];if(s[l]){let u={};for(let f of i.properties){let d=f.key,h=f.value;if(h.type===p.LITERAL)u[d]=h.value;else if(h.type===p.VARIABLE){let g=h.path;if(g===r)u[d]=s;else if(g.startsWith(r+".")){let y=g.substring(r.length+1);u[d]=s[y]}else return null}else if(h.type===p.INTERPOLATION){let g=[],y=!0;for(let I of h.parts)if(typeof I=="string")g.push(I);else if(I.type===p.VARIABLE){let m=I.path;if(m===r)g.push(s!=null?String(s):"");else if(m.startsWith(r+".")){let w=m.substring(r.length+1),A=s[w];g.push(A!=null?String(A):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}a.push(u)}}return a}}}return null},Yt=(e,t)=>{let n=e.body,r=e.itemVar,o=zt(e,t);if(o!==null)return o;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let a of n.properties)if(a.parsedKey)return null;let i=[],l=!0;for(let a of n.properties){let c=a.key,s=a.value;if(s.type===p.LITERAL)i.push({key:c,type:"literal",value:s.value});else if(s.type===p.VARIABLE){let u=s.path;if(u===r)i.push({key:c,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:c,type:"prop",prop:f});else{l=!1;break}}else{l=!1;break}}else if(s.type===p.INTERPOLATION&&s.parts.length===1){let u=s.parts[0];if(u.type===p.VARIABLE){let f=u.path;if(f===r)i.push({key:c,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))i.push({key:c,type:"prop_string",prop:d});else{l=!1;break}}else{l=!1;break}}else{l=!1;break}}else{l=!1;break}}if(l){let a=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 c=0;c<t.length;c++){let s=t[c];a[c]={id:s.id,title:s.title!=null?String(s.title):"",completed:s.completed}}else for(let c=0;c<t.length;c++){let s=t[c],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=s;else if(f.type==="prop")u[f.key]=s[f.prop];else if(f.type==="item_string")u[f.key]=s!=null?String(s):"";else if(f.type==="prop_string"){let d=s[f.prop];u[f.key]=d!=null?String(d):""}a[c]=u}return a}}return null},Kt=(e,t,n,r,o)=>{let i=[],l=e.body;if(l.type===p.OBJECT&&l.fast!==!1){let a=e.itemVar,c=e.indexVar;for(let s=0;s<o.length;s++){let u=o[s],f={},d={...r,[a]:u,...c&&{[c]: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__,[a]:`${h}[${s}]`,...c&&{[c]:s}};for(let g of l.properties){let y=g.parsedKey?_(g.parsedKey,t,n,d):g.key,I=g.value;if(I.type===p.LITERAL)f[y]=I.value;else if(I.type===p.VARIABLE){let m=I.path;if(m===a)f[y]=u;else if(m===c)f[y]=s;else if(m.startsWith(a+".")){let w=m.substring(a.length+1);!w.includes(".")&&!w.includes("[")?f[y]=u[w]:f[y]=E(m,n,{...r,[a]:u,...c&&{[c]:s}})}else f[y]=E(m,n,{...r,[a]:u,...c&&{[c]:s}})}else if(I.type===p.INTERPOLATION){let m=[];for(let w of I.parts)if(typeof w=="string")m.push(w);else if(w.type===p.VARIABLE){let A=w.path,R;if(A===a)R=u;else if(A===c)R=s;else if(A.startsWith(a+".")){let ne=A.substring(a.length+1);!ne.includes(".")&&!ne.includes("[")?R=u[ne]:R=E(A,n,{...r,[a]:u,...c&&{[c]:s}})}else R=E(A,n,{...r,[a]:u,...c&&{[c]:s}});m.push(R!=null?String(R):"")}else{let A={...r,[a]:u,...c&&{[c]:s}},R=_(w,t,n,A);m.push(R!=null?String(R):"")}f[y]=m.join("")}else{let m={...r,[a]:u,...c&&{[c]:s}};f[y]=_(I,t,n,m)}}i.push(f)}return i}return null},Ht=(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 a=l.properties[0],c=l.properties[1];if(a.key==="id"&&a.value.type===p.VARIABLE&&a.value.path==="item.id"&&c.key==="$if item.highlighted"&&c.value.type===p.CONDITIONAL){let s=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let d={id:f.id};f.highlighted?(d.highlight=!0,d.message=`This item is highlighted: ${f.name}`):(d.highlight=!1,d.message=f.name),s.push(d)}}return s}}}}return null},Jt=(e,t,n,r)=>{let o=_(e.iterable,t,n,r);if(!Array.isArray(o)){let s,u=!1;if(e.iterable.type===p.FUNCTION){u=!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 f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${s}`;throw Ue(f,o,u)}if(!e.indexVar){let s=Ht(e,o,e.itemVar);if(s!==null)return s}if(!e.indexVar){let s=Yt(e,o);if(s!==null)return s}let i=Kt(e,t,n,r,o);if(i!==null)return i;let l=[],a=e.iterable.path||"";if(r&&r.__paths__&&a){let s=a.split("."),u=s[0];u in r.__paths__&&(a=r.__paths__[u],s.length>1&&(a+="."+s.slice(1).join(".")))}let c=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?c=!1:c=e.body._shouldPreserveArray??=e.body.items.some(s=>s.type===p.OBJECT&&s.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let s=0;s<o.length;s++){let u=e.indexVar?{...r,[e.itemVar]:o[s],[e.indexVar]:s}:{...r,[e.itemVar]:o[s]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${s}]`},e.indexVar&&(u.__paths__[e.indexVar]=s);let f=_(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!c){let d=f[0];l.push(d===void 0?{}:d)}else l.push(f===void 0?{}:f)}return l},Xt=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let o=e.properties[0],i=o.parsedKey?_(o.parsedKey,t,n,r):o.key,l=o.value;if(l.type===p.OBJECT&&l.properties.length<=10&&!l.whenCondition){let a={},c={},s=!0;for(let u of l.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)c[f]=d.value;else if(d.type===p.VARIABLE)c[f]=E(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=E(g.path,n,r);h.push(y!=null?String(y):"")}else{s=!1;break}if(!s)break;c[f]=h.join("")}else if(d.type===p.OBJECT&&d.properties.length<=5){let h={};for(let g of d.properties){let y=g.key,I=g.value;if(I.type===p.LITERAL)h[y]=I.value;else if(I.type===p.VARIABLE)h[y]=E(I.path,n,r);else if(I.type===p.INTERPOLATION){let m=[];for(let w of I.parts)if(typeof w=="string")m.push(w);else if(w.type===p.VARIABLE){let A=E(w.path,n,r);m.push(A!=null?String(A):"")}else{s=!1;break}if(!s)break;h[y]=m.join("")}else{s=!1;break}}if(!s)break;c[f]=h}else{s=!1;break}}if(s)return a[i]=c,a}}return null},Gt=(e,t,n,r)=>{let o=t.functions||t;if(e.whenCondition&&!j(e.whenCondition,o,n,r))return;let i=Xt(e,t,n,r);if(i!==null)return i;if(e.fast){let s={};for(let u of e.properties){let f=u.parsedKey?_(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)s[f]=d.value;else if(d.type===p.VARIABLE)s[f]=E(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=E(g.path,n,r);h.push(y!=null?String(y):"")}else{let y=_(g,t,n,r);h.push(y!=null?String(y):"")}s[f]=h.join("")}else s[f]=_(d,t,n,r)}return s}let l={},a=null,c=!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 ")){c=!0;break}for(let s of e.properties)if(s.key.startsWith("$if ")||s.key.match(/^\$if\s+\w+.*:?$/)){let u=_(s.value,t,n,r);if(!c&&u!==null&&u!==void 0)return Array.isArray(u)&&u.length===1?u[0]:u;typeof u=="object"&&u!==null&&!Array.isArray(u)&&Object.assign(l,u)}else if(s.key.startsWith("$for ")){if(e.properties.length===1)return _(s.value,t,n,r)}else{let u=s.value;if(u&&u.type===p.OBJECT&&u.properties){let f=u.properties.find(d=>d.key.startsWith("$for "));if(f){let d=_(f.value,t,n,r);d!==void 0&&(l[s.key]=d)}else{let d=_(s.value,t,n,r);d!==void 0&&(l[s.key]=d)}}else{let f=s.parsedKey?_(s.parsedKey,t,n,r):s.key,d=_(s.value,t,n,r);d!==void 0&&(l[f]=d)}}return l},Je={},qt=(e,t,n,r)=>{let o=[];for(let i of e.items)if(i.type===p.LOOP){let l=_(i,t,n,r);Array.isArray(l)&&i.flatten!==!1?o.push(...l):o.push(l)}else{let l=_(i,t,n,r);l!==Je&&l!==void 0&&o.push(l)}return o},Qt=(e,t,n,r)=>{let{name:o,data:i,whenCondition:l}=e,a=t.partials||{},c=t.functions||t;if(l&&!j(l,c,n,r))return;if(!a[o])throw new L(`Partial '${o}' is not defined`);let s=r._partialStack||[];if(s.includes(o))throw new L(`Circular partial reference detected: ${o}`);let u=a[o],f=n,d={...r,_partialStack:[...s,o]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(i){let h=_(i,t,n,r);f={...f,...h}}return _(u,t,f,d)},Zt=(e,t,n,r)=>{let{path:o}=e,i=o.split("."),l=i[0],a=i.slice(1);if(!r||!(l in r))throw new L(`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 L(`Path reference '#{${o}}' cannot be resolved - path tracking may not be initialized properly`);let c=r.__paths__[l];if(typeof c=="number"){if(a.length>0)throw new L(`Path reference '#{${o}}' - cannot access properties on index variable '${l}'`);return String(c)}return a.length>0&&(c+="."+a.join(".")),c},me=Bt;var en=/\$\{([^}]*)\}/g,tn=/#\{([^}]*)\}/g,Ge=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,o]=n,i=nn(o,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:i}},nn=(e,t={})=>e.trim()?rn(e).map(r=>on(r.trim(),t)):[],rn=e=>{let t=[],n="",r=0,o=!1,i="";for(let l=0;l<e.length;l++){let a=e[l],c=l>0?e[l-1]:"";!o&&(a==='"'||a==="'")?(o=!0,i=a,n+=a):o&&a===i&&c!=="\\"?(o=!1,i="",n+=a):!o&&a==="("?(r++,n+=a):!o&&a===")"?(r--,n+=a):!o&&a===","&&r===0?(t.push(n),n=""):n+=a}return n&&t.push(n),t},on=(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=Ge(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:a,type:c}of o){let s=0;for(;s<r.length;){let u=D(r.substring(s),a);if(u===-1)break;let f=s+u;f>i&&(i=f,l={op:a,type:c}),s=f+a.length}}if(i!==-1)try{return x(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},qe=/^\w+\(.*\)$/,sn=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,an=e=>{if(!(!e||e.trim()===""||qe.test(e))&&sn.test(e))throw e.includes("?")&&e.includes(":")?new b(`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 b(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new b(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},Xe=e=>{let t=e.trim();if(qe.test(t))throw new b(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new b(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new b(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new b(`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 b(`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}},Y=(e,t={})=>{let n=e.trim();an(n);let r=Ge(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}},be=(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,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\(#\{[^}]*\})/g,(s,u)=>{let f=`__ESCAPED_${r.length}__`;return r.push(u),f}),n=n.replace(/\\DOUBLE_ESC_VAR/g,"\\"),n=n.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let o=[...n.matchAll(en)],i=[...n.matchAll(tn)],l=[...o.map(s=>({match:s,type:"variable"})),...i.map(s=>({match:s,type:"pathref"}))].sort((s,u)=>s.match.index-u.match.index);if(l.length===0){let s=n;for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);return{type:p.LITERAL,value:s}}if(l.length===1&&l[0].match[0]===n&&r.length===0){let{match:s,type:u}=l[0];try{return u==="variable"?Y(s[1],t):Xe(s[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let a=[],c=0;for(let{match:s,type:u}of l){let[f,d]=s,h=s.index;if(h>c){let g=n.substring(c,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&a.push(g)}try{let g;u==="variable"?g=Y(d.trim(),t):g=Xe(d.trim()),a.push(g)}catch(g){if(g.message==="Invalid array index syntax")a.push(f);else throw g}c=h+f.length}if(c<n.length){let s=n.substring(c);for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);s&&a.push(s)}return{type:p.INTERPOLATION,parts:a}};var N=(e,t)=>typeof e=="string"?be(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?cn(e,t):un(e,t):{type:p.LITERAL,value:e},ln=e=>{let{$each:t,...n}=e;if(typeof t!="string")throw new b("$each value must be a non-empty string");let r=t.trim();if(r==="")throw new b("$each value must be a non-empty string");if(Object.keys(n).length===0)throw new b("Empty $each body not allowed");if(n.$partial!==void 0)throw new b("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 c=ln(i),s=Object.keys(c);if(s.length===1&&/^\$for(?::\w+)?\s/.test(s[0])){let u=Qe(s[0],c[s[0]],t,!0);n.push(u),r=!0;continue}}catch(c){throw c instanceof b?c:new b(c.message)}let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let c=Qe(a[0],i[a[0]],t);n.push(c),r=!0;continue}}let l=N(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}},un=(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 b("$partial value must be a string");if(e.$partial.trim()==="")throw new b("$partial value cannot be an empty string");let c=["$if","$elif","$else","$for"],s=[];for(let[m]of i)for(let w of c)if(m===w||m.startsWith(w+" ")||m.startsWith(w+"#")){s.push(w);break}if(s.length>0)throw new b(`Cannot use $partial with ${s.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...d}=e,h={},g=!1;for(let[m,w]of Object.entries(d)){let A=m;(m.startsWith("\\$")||m.startsWith("$$"))&&(A=m.slice(1)),h[A]=w,g=!0}let y=null;if(g&&(y=N(h,t),y.type===p.OBJECT)){let m=!1;for(let w of y.properties)if(w.value.type===p.VARIABLE||w.value.type===p.INTERPOLATION||w.value.type===p.FUNCTION||w.value.type===p.CONDITIONAL||w.value.type===p.OBJECT&&!w.value.fast||w.value.type===p.ARRAY&&!w.value.fast){m=!0;break}m&&(y.fast=!1)}let I={type:p.PARTIAL,name:u,data:y};if(f!==void 0){let m;if(typeof f=="string"){if(f.trim()==="")throw new b("Empty condition expression after '$when'");m=x(f,t)}else m={type:p.LITERAL,value:f};I.whenCondition=m}return I}for(let[c,s]of i)if(c==="$when"){if(o!==null)throw new b("Multiple '$when' directives on the same object are not allowed");if(s==null)throw new b("Missing condition expression after '$when'");let u=typeof s=="string"?s:JSON.stringify(s);if(u.trim()==="")throw new b("Empty condition expression after '$when'");o=x(u,t),r=!0}else if(c.startsWith("$when#")||c.startsWith("$when "))throw new b("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;l<i.length;){let[c,s]=i[l];if(c==="$when"){l++;continue}if(c==="$each")throw new b("$each can only be used inside arrays");if(c.startsWith("$if ")||c.match(/^\$if#\w+\s/)||c.match(/^\$if\s+\w+.*:$/)){let u=fn(i,l,t);n.push({key:c,value:u.node}),r=!0,l=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(c)){let u=c.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new b(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'. For cleaner object generation syntax, consider using $each.`)}else{if(c.startsWith("$elif ")||c.startsWith("$else"))throw new b(`'${c.split(" ")[0]}' without matching '$if'`);if(c==="$if"||c==="$if:")throw new b("Missing condition expression after '$if'");{let u=N(s,t);(u.type===p.FUNCTION||u.type===p.CONDITIONAL||u.type===p.PARTIAL||u.type===p.OBJECT&&!u.fast||u.type===p.ARRAY&&!u.fast)&&(r=!0);let f=be(c,t),d={key:c,value:u};(f.type!==p.LITERAL||f.value!==c)&&(d.parsedKey=f),n.push(d),l++}}}let a={type:p.OBJECT,properties:n,fast:!r};return o&&(a.whenCondition=o),a},fn=(e,t,n={})=>{let r=[],o=[],i=t,[l,a]=e[i],c=null,s;if(l.startsWith("$if#")){let f=l.match(/^\$if#(\w+)\s+(.+)$/);if(f)c=f[1],s=f[2];else throw new b(`Invalid conditional syntax: ${l}`)}else s=l.substring(4),s.endsWith(":")&&(s=s.slice(0,-1).trim());ye(s);let u=x(s,n);for(r.push(u),o.push(N(a,n)),i++;i<e.length;){let[f,d]=e[i],h=!1,g;if(c?f.startsWith(`$elif#${c} `)?(g=f.substring(`$elif#${c} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${c}`||f===`$else#${c}:`)&&(h=!0,g=null):f.startsWith("$elif ")?(g=f.substring(6),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f==="$else"||f==="$else:")&&(h=!0,g=null),h){if(g===null)r.push(null);else{ye(g);let y=x(g,n);r.push(y)}if(o.push(N(d,n)),i++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:o,id:c},nextIndex:i}},x=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let s=e.slice(1,-1),u=0,f=!0;for(let d=0;d<s.length;d++)if(s[d]==="("?u++:s[d]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return x(s,t)}let n=D(e,"||");if(n!==-1)return{type:p.BINARY,op:v.OR,left:x(e.substring(0,n).trim(),t),right:x(e.substring(n+2).trim(),t)};let r=D(e,"&&");if(r!==-1)return{type:p.BINARY,op:v.AND,left:x(e.substring(0,r).trim(),t),right:x(e.substring(r+2).trim(),t)};let o=[{op:">=",type:v.GTE},{op:"<=",type:v.LTE},{op:"==",type:v.EQ},{op:"!=",type:v.NEQ},{op:">",type:v.GT},{op:"<",type:v.LT},{op:" in ",type:v.IN}];for(let{op:s,type:u}of o){let f=D(e,s);if(f!==-1)return{type:p.BINARY,op:u,left:x(e.substring(0,f).trim(),t),right:x(e.substring(f+s.length).trim(),t)}}let i=-1,l=null,a=[{op:" + ",type:v.ADD},{op:" - ",type:v.SUBTRACT}];for(let{op:s,type:u}of a){let f=0;for(;f<e.length;){let d=D(e.substring(f),s);if(d===-1)break;let h=f+d;h>i&&(i=h,l={op:s,type:u}),f=h+s.length}}if(i!==-1&&l)return{type:p.BINARY,op:l.type,left:x(e.substring(0,i).trim(),t),right:x(e.substring(i+l.op.length).trim(),t)};let c=[" * "," / "," % "];for(let s of c)if(D(e,s)!==-1)throw new b(`Arithmetic operations are not allowed in conditionals: "${s}"`);return e.startsWith("!")?{type:p.UNARY,op:z.NOT,operand:x(e.substring(1).trim(),t)}:Ze(e,t)},D=(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},dn=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}},Ze=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return Y(n,t);let o=dn(n);if(o.type===p.LITERAL)return o;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return Y(n,t)}catch(i){if(i.message&&i.message.includes("not supported"))return o;throw i}},pn=(e,t=!1)=>{let n=t?"$each":"$for";try{Fe(e)}catch(r){if(r instanceof b&&t){let o=r.message.replace(/\$for/g,"$each");throw new b(o.replace("Parse Error: ",""))}throw r}},Qe=(e,t,n,r=!1)=>{let o=/^\$for(?::(\w+))?\s+(.+)$/,i=e.match(o);if(!i){let I=r?"$each":"$for";throw new b(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let l=i[1],a=i[2].trim();pn(a,r);let c=a.match(/^(.+?)\s+in\s+(.+)$/);if(!c){let I=r?"$each":"$for";throw new b(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${a}')`)}let s=c[1].trim(),u=c[2].trim(),f,d=null;if(s.includes(",")){let I=s.split(",").map(m=>m.trim());if(I.length!==2)throw new b(`Invalid loop variables: ${s}. Expected format: "item" or "item, index"`);f=I[0],d=I[1]}else f=s;let h=["this","undefined","null","true","false"];if(h.includes(f))throw new b(`Reserved variable name: ${f}`);if(d&&h.includes(d))throw new b(`Reserved variable name: ${d}`);let g=Ze(u,n),y=N(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:l!=="nested"}};var hn=(e,t={})=>{let{functions:n={}}=t;return N(e,n)},ee=hn;var Ie={};pt(Ie,{now:()=>gn});var gn=()=>Date.now();var yn=(e,t,n={})=>{let{functions:r={},partials:o={}}=n,i={...Ie,...r},l=ee(e,{functions:i}),a={};for(let[c,s]of Object.entries(o))a[c]=ee(s,{functions:i});return me(l,t,{functions:i,partials:a})},S=yn;var we={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n}))},mn=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),bn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.base){let o=r.find(i=>i.id==="story");if(!o)return e;if(t.base.resourceId){let i=n?.layouts[t.base.resourceId];i&&o.children.unshift({id:"base",type:"container",children:i.elements})}}return e},In=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:o,autoMode:i,skipMode:l,currentLocalizationPackageId:a})=>{let{elements:c}=e,s=e.animations||[];if(t.background){let u=c.find(f=>f.id==="story");if(!u)return e;if(t.background.resourceId){let{images:f={},videos:d={}}=r,h=f[t.background.resourceId]||d[t.background.resourceId];if(h){let g=d[t.background.resourceId]!==void 0,y={id:`bg-cg-${t.background.resourceId}`,type:g?"video":"sprite",x:0,y:0,src:h.fileId,width:h.width,height:h.height};g&&(y.loop=h.loop??!1,y.volume=h.volume??500),u.children.push(y)}}if(t.background.resourceId){let{layouts:f={}}=r,d=f[t.background.resourceId];d&&u.children.push({id:`bg-cg-${t.background.resourceId}`,type:"container",children:d.elements})}if(t.background.animations){if(t.background.animations.in){let f=t.background.animations.in.resourceId,d=r?.tweens[f];d&&s.push({id:"bg-cg-animation-in",type:"tween",targetId:`bg-cg-${t.background.resourceId}`,properties:d.properties})}if(t.background.animations.out){let f=t.background.animations.out.resourceId,d=n?.background?.resourceId,h=r?.tweens[f];h&&d&&s.push({id:"bg-cg-animation-out",type:"tween",targetId:`bg-cg-${d}`,properties:h.properties})}if(t.background.animations.update){let f=t.background.animations.update.resourceId,d=r?.tweens[f];d&&s.push({id:"bg-cg-animation-update",type:"tween",targetId:`bg-cg-${t.background.resourceId}`,properties:d.properties})}}}return e},wn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,o=e.animations||[];if(t.character&&n){let i=r.find(a=>a.id==="story");if(!i)return e;let l=t.character.items||[];for(let a of l){let{transformId:c,sprites:s}=a;if(a.animations&&a.animations.out&&!s&&!c){let h=a.animations.out.resourceId,g=n?.tweens[h];if(g){let y={id:"character-animation-out",type:"tween",targetId:`character-container-${a.id}`,properties:g.properties};o.push(y)}continue}if(!s||s.length===0||!c){console.warn("Character item missing sprites or transformId:",a);continue}let u=s.map(({resourceId:h})=>h),f=n.transforms[c];if(!f){console.warn("Transform not found:",c);continue}let d={type:"container",id:`character-container-${a.id}`,x:a.x??f.x,y:a.y??f.y,anchorX:f.anchorX,anchorY:f.anchorY,rotation:f.rotation,scaleX:f.scaleX,scaleY:f.scaleY,children:[]};for(let h of s){let g=n.images[h.resourceId];if(!g){console.warn(`Image resource not found: ${h.resourceId}`);continue}d.children.push({type:"sprite",id:`${a.id}-${h.id}`,src:g.fileId,width:g.width,height:g.height,x:0,y:0})}if(i.children.push(d),a.animations){if(a.animations.in){let h=a.animations.in.resourceId,g=n?.tweens[h];g&&o.push({id:"character-animation-in",type:"tween",targetId:`character-container-${a.id}`,properties:g.properties})}if(a.animations.update){let h=a.animations.update.resourceId,g=n?.tweens[h];if(g){let y={id:"character-animation-update",type:"tween",targetId:`character-container-${a.id}`,properties:g.properties};o.push(y)}}}}}return e},_n=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,o=e.animations||[];if(t.visual&&n){let i=r.find(a=>a.id==="story");if(!i)return e;let l=t.visual.items;for(let a of l){if(a.resourceId){let{images:c={},videos:s={},spritesheets:u={}}=n,f=u[a.resourceId];if(f){let d=n.transforms?.[a.transformId]||{},h=a.animationName;if(h){let g=f.animations?.[h];if(!g)throw new Error(`Animation '${h}' not found in spritesheet resource '${a.resourceId}'`);let y={id:`visual-${a.id}`,type:"animated-sprite",x:a.x??d.x??0,y:a.y??d.y??0,width:a.width??100,height:a.height??100,alpha:a.alpha??1,anchorX:d.anchorX,anchorY:d.anchorY,rotation:d.rotation,scaleX:d.scaleX,scaleY:d.scaleY,spritesheetSrc:f.fileId,spritesheetData:f.jsonData,animation:{frames:g.frames,animationSpeed:a.animationSpeed??g.animationSpeed??.5,loop:a.loop??g.loop??!0}};i.children.push(y)}}else{let d=c[a.resourceId]||s[a.resourceId];if(d){let h=s[a.resourceId]!==void 0,g=n.transforms[a.transformId],y={id:`visual-${a.id}`,type:h?"video":"sprite",src:d.fileId,width:d.width,height:d.height,x:g.x,y:g.y,anchorX:g.anchorX,anchorY:g.anchorY,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY};h&&(y.loop=d.loop??!1,y.volume=d.volume??500),i.children.push(y)}}}if(a.resourceId){let{layouts:c={}}=n,s=c[a.resourceId];if(s){let u=n.transforms[a.transformId];i.children.push({id:`visual-${a.id}`,type:"container",children:s.elements,x:u.x,y:u.y,anchorX:u.anchorX,anchorY:u.anchorY,rotation:u.rotation,scaleX:u.scaleX,scaleY:u.scaleY})}}if(a.animations){if(a.animations.in){let c=a.animations.in.resourceId||a.animations.in,s=n?.tweens[c];s&&o.push({id:`${a.id}-animation`,type:"tween",targetId:`visual-${a.id}`,properties:s.properties})}if(a.animations.out){let c=a.animations.out.resourceId||a.animations.out,s=n?.tweens[c];s&&o.push({id:`${a.id}-animation-2`,type:"tween",targetId:`visual-${a.id}`,properties:s.properties})}}}}return e},vn=(e,{presentationState:t,resources:n={},dialogueUIHidden:r,autoMode:o,skipMode:i,skipOnlyViewedLines:l,l10n:a,variables:c})=>{let{elements:s}=e;if(!t.dialogue||r)return e;let u=s.find(f=>f.id==="story");if(!u)return e;if(t.dialogue.gui&&t.dialogue.gui.resourceId){let{layouts:f={}}=n,d=f[t.dialogue.gui.resourceId];if(d){let h;t.dialogue.characterId&&(h=n.characters[t.dialogue.characterId]),t.dialogue.character&&(h={...h,name:t.dialogue.character.name});let g={elements:d.elements},y={variables:c,autoMode:o,skipMode:i,skipOnlyViewedLines:l,dialogue:{character:{name:h?.name||""},content:t.dialogue?.content||[{text:""}],lines:t.dialogue?.lines||[]},l10n:a},I=S(g,y,{functions:we});I=S(I,{l10n:a});let m=I?.elements;if(Array.isArray(m))for(let w of m)u.children.push(structuredClone(w));else m&&u.children.push(structuredClone(m))}}return e},En=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.choice&&n){let o=r.find(s=>s.id==="story");if(!o)return e;let i=n?.layouts[t.choice.resourceId];if(!i||!i.elements)return e;let l={elements:i.elements},c=S(l,{choice:{items:t.choice.items}})?.elements;if(Array.isArray(c))for(let s of c)o.children.push(structuredClone(s));else c&&o.children.push(structuredClone(c))}return e},An=(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})=>{let{elements:r,audio:o}=e;if(t.bgm&&n){if(!r.find(a=>a.id==="story"))return e;let l=n.sounds[t.bgm.resourceId];if(!l)return e;o.push({id:"bgm",type:"sound",src:l.fileId,loop:t.bgm.loop??!0,volume:t.bgm.volume??500,delay:t.bgm.delay??null})}return e},Ln=(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},$n=(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},On=(e,{presentationState:t,resources:n={},variables:r,autoMode:o,skipMode:i,currentLocalizationPackageId:l})=>{let{elements:a}=e,c=e.animations||[];if(t.layout){let s=a.find(y=>y.id==="story");if(!s)return e;let u=n.layouts[t.layout.resourceId];if(!u)return e;Array.isArray(u.transitions)&&u.transitions.forEach(y=>{c.push(y)});let f={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:u.elements||[]},h=S(f,{variables:r,autoMode:o,skipMode:i,currentLocalizationPackageId:l},{functions:we});h=S(h,{i18n:{}});let g=y=>{let I={...y};return y.src&&y.src.startsWith("file:")&&(I.src=y.src),y.children&&Array.isArray(y.children)&&(I.children=y.children.map(g)),I};s.children.push(g(h))}return e},kn=(e,{resources:t={},variables:n,autoMode:r,skipMode:o,currentLocalizationPackageId:i,layeredViews:l=[],dialogueHistory:a=[]})=>{let{elements:c}=e,s=e.animations||[];return l&&l.length>0&&l.forEach((u,f)=>{let d=t.layouts[u.resourceId];if(!d){console.warn(`LayeredView layout not found: ${u.resourceId}`);return}Array.isArray(d.transitions)&&d.transitions.forEach(m=>{s.push(m)});let h={id:`layeredView-${f}`,type:"container",x:0,y:0,children:d.elements||[]},g=a.map(m=>{let w=t.characters?.[m.characterId];return{...m,characterName:w?.name||""}}),y={variables:n,autoMode:r,skipMode:o,currentLocalizationPackageId:i,historyDialogue:g,characters:t.characters||{}},I=S(h,y,{functions:we});I=S(I,{i18n:{}}),c.push(I)}),e},et=e=>Z(mn,[bn,In,wn,_n,vn,En,An,On,xn,Ln,$n,kn])(e);var Cn=e=>{let{global:{currentLocalizationPackageId:t,saveSlots:n={},variables:r={}},projectData:o}=e,i={sceneId:o.story.initialSceneId,sectionId:o.story.scenes[o.story.initialSceneId].initialSectionId,lineId:o.story.scenes[o.story.initialSceneId].sections[o.story.scenes[o.story.initialSceneId].initialSectionId].lines[0].id},{contextVariableDefaultValues:l,globalVariablesDefaultValues:a}=Ve(o),c={...a,...r},s={projectData:o,global:{autoplayDelay:1e3,isLineCompleted:!1,pendingEffects:[],autoMode:!1,skipMode:!1,skipOnlyViewedLines:!0,dialogueUIHidden:!1,isDialogueHistoryShowing:!1,currentLocalizationPackageId:t,viewedRegistry:{sections:[],resources:[]},nextLineConfig:{manual:{enabled:!0,requireLineCompleted:!1},auto:{enabled:!1}},saveSlots:n,layeredViews:[],variables:c},contexts:[{currentPointerMode:"read",pointers:{read:i,history:{sectionId:void 0,lineId:void 0,historySequenceIndex:void 0}},historySequence:[{sectionId:"..."}],configuration:{},views:[],bgm:{resourceId:void 0},variables:l}]};return console.log("Initial State:",s),s},Rn=({state:e})=>e.global.layeredViews||[],Sn=({state:e})=>e.global.pendingEffects,tt=({state:e})=>e.global.skipMode,Nn=({state:e})=>e.global.skipOnlyViewedLines,Pn=({state:e})=>e.global.autoMode,nt=({state:e})=>e.global.dialogueUIHidden,Tn=({state:e})=>e.global.autoplayDelay,_e=({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(c=>c.id===r);return o.lines.slice(0,i+1).filter(c=>c.actions?.dialogue).map(c=>{let s=c.actions.dialogue,u="";return s.characterId&&(u=e.projectData.resources?.characters?.[s.characterId]?.name||""),{content:s.content,characterId:s.characterId,characterName:u}})},Vn=({state:e})=>e.global.currentLocalizationPackageId,rt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,o=e.global.viewedRegistry.sections.find(c=>c.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(c=>c.id===o.lastLineId),a=i.lines.findIndex(c=>c.id===r);return l===-1||a===-1?o.lastLineId===r:a<l},Dn=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(o=>o.resourceId===n)},Mn=({state:e})=>e.global.nextLineConfig,Bn=({state:e})=>e.global.saveSlots,jn=({state:e},t)=>{let{slotKey:n}=t;return e.global.saveSlots[n]},F=({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]}},Fn=({state:e})=>{let t=F({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)},ot=({state:e})=>{let{sectionId:t,lineId:n}=F({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(s=>s.id===n),l=o.slice(0,i+1);console.log("currentLines",l);let a=l.map(s=>{let u=s.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return ge(a)},Un=({state:e})=>{let{sectionId:t,lineId:n}=F({state:e}).pointer,o=k({state:e},{sectionId:t})?.lines||[],i=o.findIndex(c=>c.id===n);if(i<=0)return null;let a=o.slice(0,i).map(c=>{let s=c.actions||{},u={};return Object.keys(s).forEach(f=>{u[f]=s[f]}),u});return ge(a)},Wn=({state:e})=>{let t=ot({state:e}),n=Un({state:e});console.log("presentationState",t);let r=et({presentationState:t,previousPresentationState:n,resources:e.projectData.resources,l10n:e.projectData.l10n.packages[e.global.currentLocalizationPackageId],dialogueUIHidden:e.global.dialogueUIHidden,autoMode:e.global.autoMode,skipMode:e.global.skipMode,skipOnlyViewedLines:e.global.skipOnlyViewedLines,layeredViews:e.global.layeredViews,dialogueHistory:_e({state:e}),variables:De(e.global.variables,e.contexts[e.contexts.length-1].variables)});return console.log("renderState",r),r},zn=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),e),Yn=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),e),Kn=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),e),Hn=({state:e})=>(e.global.layeredViews=[],e.global.pendingEffects.push({name:"render"}),e),it=({state:e})=>(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.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:e.global.autoplayDelay}}),e.global.pendingEffects.push({name:"render"}),e),ve=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Jn=({state:e})=>(e.global.autoMode?ve({state:e}):it({state:e}),e),st=({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),te=({state:e})=>(e.global.skipMode=!1,e.global.pendingEffects.push({name:"clearSkipNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Xn=({state:e})=>(tt({state:e})?te({state:e}):st({state:e}),e),Gn=({state:e},t)=>{let{skipOnlyViewedLines:n}=t;return e.global.skipOnlyViewedLines=n,e.global.pendingEffects.push({name:"render"}),e},qn=({state:e})=>(e.global.skipOnlyViewedLines=!e.global.skipOnlyViewedLines,e.global.pendingEffects.push({name:"render"}),e),at=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),e),lt=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),e),Qn=({state:e})=>(nt({state:e})?at({state:e}):lt({state:e}),e),Zn=({state:e})=>{let t=_e({state:e});return e.global.isDialogueHistoryShowing=!0,e.global.pendingEffects.push({name:"render"}),e},er=({state:e})=>(e.global.isDialogueHistoryShowing=!1,e.global.pendingEffects.push({name:"render"}),e),tr=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},nr=({state:e})=>(e.global.pendingEffects=[],e),rr=({state:e},t)=>(e.global.pendingEffects.push(t),e),ct=({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(c=>c.id===o.lastLineId),a=i.lines.findIndex(c=>c.id===r);(l===-1||a>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},or=({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},ir=({state:e},t)=>{let{manual:n,auto:r}=t;return n&&r?e.global.nextLineConfig={manual:n,auto:r}:(n&&(e.global.nextLineConfig.manual=n),r&&(e.global.nextLineConfig.auto=r)),e.global.pendingEffects.push({name:"render"}),e},sr=({state:e},{delay:t})=>(e.global.autoplayDelay=t,e.global.autoMode&&(e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"startAutoNextTimer",payload:{delay:e.global.autoplayDelay}})),e.global.pendingEffects.push({name:"render"}),e),ar=({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},lr=({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},cr=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},ur=({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(c=>c.id===r)?(o.pointers.read={sectionId:i,lineId:r},e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e):(console.warn(`Line not found: ${r} in section ${i}`),e)},fr=({state:e},t)=>{let{item:n}=t,r=e.contexts[e.contexts.length-1];return r&&r.historySequence&&r.historySequence.push({sectionId:n.sectionId}),e.global.pendingEffects.push({name:"render"}),e},dr=({state:e})=>{if(e.global.nextLineConfig?.auto?.enabled!==!0||e.global.nextLineConfig?.auto?.trigger!=="fromComplete")return e;let t=F({state:e})?.pointer,n=t?.sectionId,o=k({state:e},{sectionId:n})?.lines||[],l=o.findIndex(a=>a.id===t?.lineId)+1;if(l<o.length){let a=o[l],c=e.contexts[e.contexts.length-1];c&&(c.pointers.read={sectionId:n,lineId:a.id}),e.global.isLineCompleted=!1,e.global.nextLineConfig.auto={},e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}return e},pr=({state:e})=>{if(!e.global.nextLineConfig.manual.enabled)return e;let t=F({state:e})?.pointer,n=t?.sectionId,o=k({state:e},{sectionId:n})?.lines||[],l=o.findIndex(a=>a.id===t?.lineId)+1;if(l<o.length){let a=o[l];e.global.skipMode&&e.global.skipOnlyViewedLines&&(rt({state:e},{sectionId:n,lineId:a.id})||te({state:e}));let c=e.contexts[e.contexts.length-1];if(c){let s=c.pointers.read.lineId;s&&n&&ct({state:e},{sectionId:n,lineId:s}),c.pointers.read={sectionId:n,lineId:a.id}}e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}else e.global.autoMode&&ve({state:e}),e.global.skipMode&&te({state:e});return console.log("state",e),e},hr=({state:e})=>(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e),gr=({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 u=o.findIndex(f=>f.id===l.lineId)-1;if(u>=0&&u<o.length){let f=o[u];i.pointers.history={sectionId:n,lineId:f.id}}return e.global.pendingEffects.push({name:"render"}),e}let c=o.findIndex(s=>s.id===i.pointers.history.lineId)-1;if(c>=0&&c<o.length){let s=o[c];i.pointers.history={sectionId:n,lineId:s.id},e.global.pendingEffects.push({name:"render"})}return e},yr=({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;let i=e.contexts[e.contexts.length-1];return i&&(i.pointers.read={sectionId:n,lineId:o.id}),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},mr=({state:e},t)=>{let{operations:n=[]}=t,r=!1,o=!1;if(n.forEach(({variableId:i,op:l,value:a})=>{let c=e.projectData.resources?.variables?.[i],s=c?.scope,u=c?.type;Me(s,i),Be(u,l,i);let f=s==="context"?e.contexts[e.contexts.length-1].variables:e.global.variables;s==="global-device"?r=!0:s==="global-account"&&(o=!0),f[i]=je(f[i],l,a)}),r){let i=he(e.global.variables,e.projectData.resources?.variables,"global-device");e.global.pendingEffects.push({name:"saveGlobalDeviceVariables",payload:{globalDeviceVariables:i}})}if(o){let i=he(e.global.variables,e.projectData.resources?.variables,"global-account");e.global.pendingEffects.push({name:"saveGlobalAccountVariables",payload:{globalAccountVariables:i}})}return e.global.pendingEffects.push({name:"render"}),e},ut=e=>{let t=Cn(e);return Te(t,{selectPendingEffects:Sn,selectSkipMode:tt,selectSkipOnlyViewedLines:Nn,selectAutoMode:Pn,selectDialogueUIHidden:nt,selectDialogueHistory:_e,selectCurrentLocalizationPackageId:Vn,selectIsLineViewed:rt,selectIsResourceViewed:Dn,selectNextLineConfig:Mn,selectSaveSlots:Bn,selectSaveSlot:jn,selectCurrentPointer:F,selectSection:k,selectCurrentLine:Fn,selectPresentationState:ot,selectAutoplayDelay:Tn,selectRenderState:Wn,selectLayeredViews:Rn,startAutoMode:it,stopAutoMode:ve,toggleAutoMode:Jn,startSkipMode:st,stopSkipMode:te,toggleSkipMode:Xn,setSkipOnlyViewedLines:Gn,toggleSkipOnlyViewedLines:qn,showDialogueUI:at,hideDialogueUI:lt,toggleDialogueUI:Qn,showDialogueHistory:Zn,hideDialogueHistory:er,setCurrentLocalizationPackageId:tr,clearPendingEffects:nr,appendPendingEffect:rr,addViewedLine:ct,addViewedResource:or,setNextLineConfig:ir,saveSaveSlot:ar,loadSaveSlot:lr,setAutoplayDelay:sr,updateProjectData:cr,sectionTransition:yr,jumpToLine:ur,addToHistorySequence:fr,nextLine:pr,nextLineFromCompleted:dr,markLineCompleted:hr,prevLine:gr,pushLayeredView:zn,popLayeredView:Yn,replaceLastLayeredView:Kn,clearLayeredViews:Hn,updateVariable:mr},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Ee(e){let t,{handlePendingEffects:n}=e,r=({initialState:u})=>{t=ut(u),t.appendPendingEffect({name:"render"}),s(),n(t.selectPendingEffects()),t.clearPendingEffects()},o=()=>t.selectPresentationState(),i=()=>t.selectRenderState(),l=()=>t.selectSaveSlots(),a=(u,f)=>{t[u]&&(t[u](f),n(t.selectPendingEffects()),t.clearPendingEffects())},c=u=>{Object.entries(u).forEach(([f,d])=>{a(f,d)})},s=()=>{let u=t.selectCurrentLine();u&&u.actions&&c(u.actions)};return{init:r,handleAction:a,handleActions:c,selectRenderState:i,selectPresentationState:o,selectSaveSlots:l,handleLineActions:s}}var ft=()=>{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)},Ir=({engine:e},t)=>{e.handleLineActions()},wr=({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 a=r.delay??1e3;n.getElapsed()>=a&&(n.setElapsed(0),e.handleAction("nextLine",{}))};n.setCallback(i),t.add(i)},_r=({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=l=>{n.addElapsed(l.deltaMS),n.getElapsed()>=30&&(n.setElapsed(0),e.handleAction("nextLine",{}))};n.setCallback(i),t.add(i)},Er=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},Ar=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},xr=({},e)=>{localStorage.setItem("globalDeviceVariables",JSON.stringify(e.globalDeviceVariables))},Lr=({},e)=>{localStorage.setItem("globalAccountVariables",JSON.stringify(e.globalAccountVariables))},$r={render:br,saveSlots:Ar,saveGlobalDeviceVariables:xr,saveGlobalAccountVariables:Lr,handleLineActions:Ir,startAutoNextTimer:wr,clearAutoNextTimer:_r,startSkipNextTimer:vr,clearSkipNextTimer:Er},Or=({getEngine:e,routeGraphics:t,ticker:n})=>{let r=ft(),o=ft();return async i=>{let l=e(),a=i.reduce((u,f)=>(u[f.name]=f,u),{}),c=Object.values(a),s={engine:l,routeGraphics:t,ticker:n,autoTimer:r,skipTimer:o};for(let u of c){let f=$r[u.name];f&&f(s,u.payload)}}},kr=Or;var Ao=Ee;export{kr as createEffectsHandler,Ao as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "main": "dist/RouteEngine.js",
6
6
  "exports": {
@@ -14,9 +14,9 @@
14
14
  "test": "vitest run",
15
15
  "test:watch": "vitest",
16
16
  "build": "bun run esbuild.js",
17
- "lint": "bunx prettier src -c",
18
- "lint:fix": "bunx prettier src -w",
19
- "coverage": "vitest run --coverage",
17
+ "lint": "bun run prettier src -c",
18
+ "lint:fix": "bun run prettier src -w",
19
+ "coverage": "bun run vitest run --coverage",
20
20
  "vt:generate": "bun run esbuild.js && rtgl vt generate --skip-screenshots",
21
21
  "serve": "bun run esbuild.js && bunx serve -p 3004 .rettangoli/vt/_site"
22
22
  },
@@ -24,11 +24,13 @@
24
24
  "immer": "^10.1.1",
25
25
  "jempl": "1.0.0",
26
26
  "js-yaml": "^4.1.0",
27
- "puty": "^0.0.6"
27
+ "puty": "^0.1.1"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@vitest/coverage-v8": "^3.2.4",
31
31
  "@vitest/ui": "^3.2.4",
32
- "vitest": "^3.2.4"
32
+ "husky": "^9.1.7",
33
+ "prettier": "^3.7.4",
34
+ "vitest": "^4.0.16"
33
35
  }
34
36
  }