route-engine-js 0.1.7 → 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 st=Object.defineProperty;var at=(e,t)=>{for(var n in t)st(e,n,{get:t[n],enumerable:!0})};var ke=Symbol.for("immer-nothing"),Ee=Symbol.for("immer-draftable"),$=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[$]}function T(e){return e?Ce(e)||Array.isArray(e)||!!e[Ee]||!!e.constructor?.[Ee]||q(e)||G(e):!1}var ct=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)===ct}function Y(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:q(e)?2:G(e)?3:0}function oe(e,t){return X(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Oe(e,t,n){let r=X(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function lt(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function q(e){return e instanceof Map}function G(e){return e instanceof Set}function P(e){return e.copy_||e.base_}function se(e,t){if(q(e))return new Map(e);if(G(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 i=Reflect.ownKeys(r);for(let o=0;o<i.length;o++){let a=i[o],c=r[a];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(r[a]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[a]})}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 fe(e,t=!1){return Q(e)||B(e)||!T(e)||(X(e)>1&&(e.set=e.add=e.clear=e.delete=ut),Object.freeze(e),t&&Object.entries(e).forEach(([n,r])=>fe(r,!0))),e}function ut(){O(2)}function Q(e){return Object.isFrozen(e)}var ft={};function V(e){let t=ft[e];return t||O(0,e),t}var U;function Re(){return U}function dt(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ve(e,t){t&&(V("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ae(e){ce(e),e.drafts_.forEach(pt),e.drafts_=null}function ce(e){e===U&&(U=e.parent_)}function xe(e){return U=dt(U,e)}function pt(e){let t=e[$];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Le(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];return e!==void 0&&e!==n?(n[$].modified_&&(ae(t),O(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 Y(t,(i,o)=>$e(e,r,t,i,o,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 i=r.copy_,o=i,a=!1;r.type_===3&&(o=new Set(i),i.clear(),a=!0),Y(o,(c,l)=>$e(e,r,i,c,l,n,a)),J(e,i,!1),n&&e.patches_&&V("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function $e(e,t,n,r,i,o,a){if(B(i)){let c=o&&t&&t.type_!==3&&!oe(t.assigned_,r)?o.concat(r):void 0,l=H(e,i,c);if(Oe(n,r,l),B(l))e.canAutoFreeze_=!1;else return}else a&&n.add(i);if(T(i)&&!Q(i)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;H(e,i),(!t||!t.scope_.parent_)&&typeof r!="symbol"&&Object.prototype.propertyIsEnumerable.call(n,r)&&J(e,i)}}function J(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&fe(t,n)}function ht(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,o=de;n&&(i=[r],o=z);let{revoke:a,proxy:c}=Proxy.revocable(i,o);return r.draft_=c,r.revoke_=a,c}var de={get(e,t){if(t===$)return e;let n=P(e);if(!oe(n,t))return gt(e,n,t);let r=n[t];return e.finalized_||!T(r)?r:r===re(e.base_,t)?(ie(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 i=re(P(e),t),o=i?.[$];if(o&&o.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(lt(n,i)&&(n!==void 0||oe(e.base_,t)))return!0;ie(e),le(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,ie(e),le(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(){O(11)},getPrototypeOf(e){return M(e.base_)},setPrototypeOf(){O(12)}},z={};Y(de,(e,t)=>{z[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});z.deleteProperty=function(e,t){return z.set.call(this,e,t,void 0)};z.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 gt(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 le(e){e.modified_||(e.modified_=!0,e.parent_&&le(e.parent_))}function ie(e){e.copy_||(e.copy_=se(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var yt=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){let o=n;n=t;let a=this;return function(l=o,...s){return a.produce(l,u=>n.call(this,u,...s))}}typeof n!="function"&&O(6),r!==void 0&&typeof r!="function"&&O(7);let i;if(T(t)){let o=xe(this),a=ue(t,void 0),c=!0;try{i=n(a),c=!1}finally{c?ae(o):ce(o)}return ve(o,r),Le(i,o)}else if(!t||typeof t!="object"){if(i=n(t),i===void 0&&(i=t),i===ke&&(i=void 0),this.autoFreeze_&&fe(i,!0),r){let o=[],a=[];V("Patches").generateReplacementPatches_(t,i,o,a),r(o,a)}return i}else O(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(a,...c)=>this.produceWithPatches(a,l=>t(l,...c));let r,i;return[this.produce(t,n,(a,c)=>{r=a,i=c}),r,i]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){T(e)||O(8),B(e)&&(e=mt(e));let t=xe(this),n=ue(e,void 0);return n[$].isManual_=!0,ce(t),n}finishDraft(e,t){let n=e&&e[$];(!n||!n.isManual_)&&O(9);let{scope_:r}=n;return ve(r,t),Le(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=V("Patches").applyPatches_;return B(e)?r(e,t):this.produce(e,i=>r(i,t))}};function ue(e,t){let n=q(e)?V("MapSet").proxyMap_(e,t):G(e)?V("MapSet").proxySet_(e,t):ht(e,t);return(t?t.scope_:Re()).drafts_.push(n),n}function mt(e){return B(e)||O(10,e),Se(e)}function Se(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 Y(n,(r,i)=>{Oe(n,r,Se(i))}),t&&(t.finalized_=!1),n}var k=new yt,pe=k.produce,wr=k.produceWithPatches.bind(k),Ar=k.setAutoFreeze.bind(k),Er=k.setUseStrictShallowCopy.bind(k),vr=k.applyPatches.bind(k),xr=k.createDraft.bind(k),Lr=k.finishDraft.bind(k);var Pe=(e,t,n={})=>{let r=structuredClone(e),i={},o={},{transformSelectorFirstArgument:a=l=>l,transformActionFirstArgument:c=l=>l}=n;for(let[l,s]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?i[l]=(...u)=>s(a(r),...u):o[l]=(...u)=>{r=pe(r,d=>s(c(d),...u))});return{...i,...o}},Z=(e,t)=>n=>{let r=e(),i=Array.isArray(n)?n:[n];return pe(r,o=>{i.forEach(a=>{t.forEach(c=>{c(o,a)})})})};var bt=()=>({}),It=(e,t)=>{t.base&&(e.base={...t.base})},_t=(e,t)=>{t.background&&(e.background={...t.background})},wt=(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}))},At=(e,t)=>{t.sfx?e.sfx=t.sfx:e.sfx&&delete e.sfx},Et=(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}}},vt=(e,t)=>{t.visual&&(e.visual=t.visual)},xt=(e,t)=>{t.character&&(t.character.items||delete e.character,e.character=structuredClone(t.character))},Lt=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},$t=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},kt=(e,t)=>{t.choice?e.choice=t.choice:e.choice&&delete e.choice},Ct=(e,t)=>{t.keyboard&&(e.keyboard=t.keyboard)},Ot=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},Rt=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(n=>{delete e[n]})},he=e=>Z(bt,[Rt,It,_t,At,Et,vt,wt,xt,Lt,$t,kt,Ct,Ot])(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},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 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 ge=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}')`)},Te=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(i=>i.trim()):[t.trim()];for(let i of r){if(!i)throw new b(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(i))throw new b(`Invalid loop syntax (got: '$for ${e}')`)}};var Ve=(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}'`)},De=(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 Nt=(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 a=w(e,{functions:r,partials:i},t,{});return a===void 0?{}:a},w=(e,t,n,r)=>{let i=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 Pt(e.parts,t,n,r);switch(e.type){case p.FUNCTION:return Be(e,t,n,r);case p.BINARY:return Fe(e,t,n,r);case p.UNARY:return We(e,t,n,r);case p.CONDITIONAL:return Vt(e,t,n,r);case p.LOOP:return Wt(e,t,n,r);case p.OBJECT:return zt(e,t,n,r);case p.ARRAY:return jt(e,t,n,r);case p.PARTIAL:return Kt(e,t,n,r);case p.PATH_REFERENCE:return Yt(e,t,n,r);default:throw new Error(`Unknown node type: ${e.type}`)}},Me=new Map,St=e=>{let t=[],n="",r=!1;for(let i=0;i<e.length;i++){let o=e[i];if(o==="[")n&&(t.push({type:"property",value:n}),n=""),r=!0;else if(o==="]"){if(r&&n){let a=n.trim();if(/^\d+$/.test(a))t.push({type:"index",value:parseInt(a,10)});else if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'")){let c=a.slice(1,-1);t.push({type:"property",value:c})}else t.push({type:"property",value:a});n=""}r=!1}else n+=o}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=Me.get(e);if(!r){let o=[],a="",c=0;for(let l=0;l<e.length;l++){let s=e[l];s==="["?(c++,a+=s):s==="]"?(c--,a+=s):s==="."&&c===0?a&&(o.push(a),a=""):a+=s}a&&o.push(a),r=[];for(let l of o){let s=St(l.trim());r.push(...s)}Me.set(e,r)}let i=t;for(let o=0;o<r.length;o++){let a=r[o];if(a.type==="property"&&a.value in n){i=n[a.value];continue}if(i==null)return;(a.type==="property"||a.type==="index")&&(i=i[a.value])}return i},Pt=(e,t,n,r)=>{let i=[];for(let o of e)if(typeof o=="string")i.push(o);else{let a=w(o,t,n,r);i.push(a!=null?String(a):"")}return i.join("")},Be=(e,t,n,r)=>{let i=t.functions||t,o=i[e.name];if(!o)throw De(e.name,i);let a=e.args.map(c=>w(c,t,n,r));return o(...a)},F=(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 Fe(e,t,n,r);case p.UNARY:return We(e,t,n,r);case p.FUNCTION:return Be(e,t,n,r);default:return w(e,t,n,r)}},Fe=(e,t,n,r)=>{if(e.op===A.AND||e.op===A.OR){let a=F(e.left,t,n,r),c=F(e.right,t,n,r);switch(e.op){case A.AND:return a&&c;case A.OR:return a||c}}let i=w(e.left,t,n,r),o=w(e.right,t,n,r);switch(e.op){case A.EQ:return i==o;case A.NEQ:return i!=o;case A.GT:return i>o;case A.LT:return i<o;case A.GTE:return i>=o;case A.LTE:return i<=o;case A.IN:return Array.isArray(o)?o.includes(i):!1;case A.ADD:if(typeof i!="number"||typeof o!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof i} + ${typeof o}`);return i+o;case A.SUBTRACT:if(typeof i!="number"||typeof o!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof i} - ${typeof o}`);return i-o;default:throw new Error(`Unknown binary operator: ${e.op}`)}},We=(e,t,n,r)=>{let i=e.op===j.NOT?F(e.operand,t,n,r):w(e.operand,t,n,r);if(e.op===j.NOT)return!i;throw new Error(`Unknown unary operator: ${e.op}`)},Tt=(e,t,n,r)=>{if(e.conditions.length===2&&e.conditions[1]===null){let i=e.conditions[0];if(i.type===p.VARIABLE)if(E(i.path,n,r)){let a=e.bodies[0];if(a.type===p.OBJECT&&a.properties.length<=5){let c={};for(let l of a.properties){let s=l.parsedKey?w(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===p.LITERAL)c[s]=u.value;else if(u.type===p.VARIABLE)c[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=w(d,t,n,r);f.push(h!=null?String(h):"")}c[s]=f.join("")}else c[s]=w(u,t,n,r)}return c}}else{let a=e.bodies[1];if(a.type===p.OBJECT&&a.properties.length<=5){let c={};for(let l of a.properties){let s=l.parsedKey?w(l.parsedKey,t,n,r):l.key,u=l.value;if(u.type===p.LITERAL)c[s]=u.value;else if(u.type===p.VARIABLE)c[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=w(d,t,n,r);f.push(h!=null?String(h):"")}c[s]=f.join("")}else c[s]=w(u,t,n,r)}return c}}}return null},Vt=(e,t,n,r)=>{let i=Tt(e,t,n,r);if(i!==null)return i;for(let o=0;o<e.conditions.length;o++){let a=e.conditions[o];if(a===null||F(a,t,n,r))return w(e.bodies[o],t,n,r)}return Ue},Dt=(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 i=n.conditions[0].path,o=n.bodies[0];if(i.startsWith(r+".")){let a=i.substring(r.length+1);if(o.type===p.OBJECT&&o.properties.length<=5){for(let l of o.properties)if(l.parsedKey)return null;let c=[];for(let l=0;l<t.length;l++){let s=t[l];if(s[a]){let u={};for(let f of o.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 _=m.substring(r.length+1),v=s[_];g.push(v!=null?String(v):"")}else{y=!1;break}}else{y=!1;break}if(!y)return null;u[d]=g.join("")}else return null}c.push(u)}}return c}}}return null},Mt=(e,t)=>{let n=e.body,r=e.itemVar,i=Dt(e,t);if(i!==null)return i;if(n.type===p.OBJECT&&n.properties.length<=5&&!n.whenCondition){for(let c of n.properties)if(c.parsedKey)return null;let o=[],a=!0;for(let c of n.properties){let l=c.key,s=c.value;if(s.type===p.LITERAL)o.push({key:l,type:"literal",value:s.value});else if(s.type===p.VARIABLE){let u=s.path;if(u===r)o.push({key:l,type:"item"});else if(u.startsWith(r+".")){let f=u.substring(r.length+1);if(!f.includes(".")&&!f.includes("["))o.push({key:l,type:"prop",prop:f});else{a=!1;break}}else{a=!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)o.push({key:l,type:"item_string"});else if(f.startsWith(r+".")){let d=f.substring(r.length+1);if(!d.includes(".")&&!d.includes("["))o.push({key:l,type:"prop_string",prop:d});else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}else{a=!1;break}}if(a){let c=new Array(t.length);if(o.length===3&&o[0].type==="prop"&&o[0].key==="id"&&o[1].type==="prop_string"&&o[1].key==="title"&&o[2].type==="prop"&&o[2].key==="completed")for(let l=0;l<t.length;l++){let s=t[l];c[l]={id:s.id,title:s.title!=null?String(s.title):"",completed:s.completed}}else for(let l=0;l<t.length;l++){let s=t[l],u={};for(let f of o)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):""}c[l]=u}return c}}return null},Bt=(e,t,n,r,i)=>{let o=[],a=e.body;if(a.type===p.OBJECT&&a.fast!==!1){let c=e.itemVar,l=e.indexVar;for(let s=0;s<i.length;s++){let u=i[s],f={},d={...r,[c]:u,...l&&{[l]:s}};d.__paths__||(d.__paths__=r.__paths__||{});let h=e.iterable.path||"";if(r&&r.__paths__&&h){let g=h.split("."),y=g[0];y in r.__paths__&&(h=r.__paths__[y],g.length>1&&(h+="."+g.slice(1).join(".")))}d.__paths__={...d.__paths__,[c]:`${h}[${s}]`,...l&&{[l]:s}};for(let g of a.properties){let y=g.parsedKey?w(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===c)f[y]=u;else if(m===l)f[y]=s;else if(m.startsWith(c+".")){let _=m.substring(c.length+1);!_.includes(".")&&!_.includes("[")?f[y]=u[_]:f[y]=E(m,n,{...r,[c]:u,...l&&{[l]:s}})}else f[y]=E(m,n,{...r,[c]:u,...l&&{[l]:s}})}else if(I.type===p.INTERPOLATION){let m=[];for(let _ of I.parts)if(typeof _=="string")m.push(_);else if(_.type===p.VARIABLE){let v=_.path,R;if(v===c)R=u;else if(v===l)R=s;else if(v.startsWith(c+".")){let ne=v.substring(c.length+1);!ne.includes(".")&&!ne.includes("[")?R=u[ne]:R=E(v,n,{...r,[c]:u,...l&&{[l]:s}})}else R=E(v,n,{...r,[c]:u,...l&&{[l]:s}});m.push(R!=null?String(R):"")}else{let v={...r,[c]:u,...l&&{[l]:s}},R=w(_,t,n,v);m.push(R!=null?String(R):"")}f[y]=m.join("")}else{let m={...r,[c]:u,...l&&{[l]:s}};f[y]=w(I,t,n,m)}}o.push(f)}return o}return null},Ft=(e,t,n)=>{let r=e.body;if(r.type===p.OBJECT&&r.properties.length===1&&r.properties[0].key==="$if item.visible"){let o=r.properties[0].value;if(o.type===p.CONDITIONAL&&o.conditions.length===1&&o.conditions[0].type===p.VARIABLE&&o.conditions[0].path==="item.visible"){let a=o.bodies[0];if(a.type===p.OBJECT&&a.properties.length===2){let c=a.properties[0],l=a.properties[1];if(c.key==="id"&&c.value.type===p.VARIABLE&&c.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.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},Wt=(e,t,n,r)=>{let i=w(e.iterable,t,n,r);if(!Array.isArray(i)){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 Ve(f,i,u)}if(!e.indexVar){let s=Ft(e,i,e.itemVar);if(s!==null)return s}if(!e.indexVar){let s=Mt(e,i);if(s!==null)return s}let o=Bt(e,t,n,r,i);if(o!==null)return o;let a=[],c=e.iterable.path||"";if(r&&r.__paths__&&c){let s=c.split("."),u=s[0];u in r.__paths__&&(c=r.__paths__[u],s.length>1&&(c+="."+s.slice(1).join(".")))}let l=!1;e.body.type===p.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(s=>s.type===p.OBJECT&&s.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let s=0;s<i.length;s++){let u=e.indexVar?{...r,[e.itemVar]:i[s],[e.indexVar]:s}:{...r,[e.itemVar]:i[s]};u.__paths__||(u.__paths__=r.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${c}[${s}]`},e.indexVar&&(u.__paths__[e.indexVar]=s);let f=w(e.body,t,n,u);if(Array.isArray(f)&&f.length===1&&!l){let d=f[0];a.push(d===void 0?{}:d)}else a.push(f===void 0?{}:f)}return a},Ut=(e,t,n,r)=>{if(e.whenCondition)return null;if(e.properties.length===1){let i=e.properties[0],o=i.parsedKey?w(i.parsedKey,t,n,r):i.key,a=i.value;if(a.type===p.OBJECT&&a.properties.length<=10&&!a.whenCondition){let c={},l={},s=!0;for(let u of a.properties){let f=u.parsedKey?w(u.parsedKey,t,n,r):u.key,d=u.value;if(d.type===p.LITERAL)l[f]=d.value;else if(d.type===p.VARIABLE)l[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;l[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 _ of I.parts)if(typeof _=="string")m.push(_);else if(_.type===p.VARIABLE){let v=E(_.path,n,r);m.push(v!=null?String(v):"")}else{s=!1;break}if(!s)break;h[y]=m.join("")}else{s=!1;break}}if(!s)break;l[f]=h}else{s=!1;break}}if(s)return c[o]=l,c}}return null},zt=(e,t,n,r)=>{let i=t.functions||t;if(e.whenCondition&&!F(e.whenCondition,i,n,r))return;let o=Ut(e,t,n,r);if(o!==null)return o;if(e.fast){let s={};for(let u of e.properties){let f=u.parsedKey?w(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=w(g,t,n,r);h.push(y!=null?String(y):"")}s[f]=h.join("")}else s[f]=w(d,t,n,r)}return s}let a={},c=null,l=!1;for(let s of e.properties)if(!s.key.startsWith("$if ")&&!s.key.match(/^\$if\s+\w+.*:?$/)&&!s.key.startsWith("$elif")&&!s.key.startsWith("$else")&&!s.key.startsWith("$for ")){l=!0;break}for(let s of e.properties)if(s.key.startsWith("$if ")||s.key.match(/^\$if\s+\w+.*:?$/)){let u=w(s.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(a,u)}else if(s.key.startsWith("$for ")){if(e.properties.length===1)return w(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=w(f.value,t,n,r);d!==void 0&&(a[s.key]=d)}else{let d=w(s.value,t,n,r);d!==void 0&&(a[s.key]=d)}}else{let f=s.parsedKey?w(s.parsedKey,t,n,r):s.key,d=w(s.value,t,n,r);d!==void 0&&(a[f]=d)}}return a},Ue={},jt=(e,t,n,r)=>{let i=[];for(let o of e.items)if(o.type===p.LOOP){let a=w(o,t,n,r);Array.isArray(a)&&o.flatten!==!1?i.push(...a):i.push(a)}else{let a=w(o,t,n,r);a!==Ue&&a!==void 0&&i.push(a)}return i},Kt=(e,t,n,r)=>{let{name:i,data:o,whenCondition:a}=e,c=t.partials||{},l=t.functions||t;if(a&&!F(a,l,n,r))return;if(!c[i])throw new L(`Partial '${i}' is not defined`);let s=r._partialStack||[];if(s.includes(i))throw new L(`Circular partial reference detected: ${i}`);let u=c[i],f=n,d={...r,_partialStack:[...s,i]};if(r){f={...n};for(let h of Object.keys(r))h.startsWith("_")||(f[h]=r[h])}if(o){let h=w(o,t,n,r);f={...f,...h}}return w(u,t,f,d)},Yt=(e,t,n,r)=>{let{path:i}=e,o=i.split("."),a=o[0],c=o.slice(1);if(!r||!(a in r))throw new L(`Path reference '#{${i}}' refers to '${a}' which is not a loop variable in the current scope`);if(r.__paths__||(r.__paths__={}),!(a in r.__paths__))throw new L(`Path reference '#{${i}}' cannot be resolved - path tracking may not be initialized properly`);let l=r.__paths__[a];if(typeof l=="number"){if(c.length>0)throw new L(`Path reference '#{${i}}' - cannot access properties on index variable '${a}'`);return String(l)}return c.length>0&&(l+="."+c.join(".")),l},ye=Nt;var Ht=/\$\{([^}]*)\}/g,Jt=/#\{([^}]*)\}/g,je=(e,t={})=>{let n=e.match(/^(\w+)\((.*)\)$/);if(!n)return{isFunction:!1};let[,r,i]=n,o=Xt(i,t);return{isFunction:!0,type:p.FUNCTION,name:r,args:o}},Xt=(e,t={})=>e.trim()?qt(e).map(r=>Gt(r.trim(),t)):[],qt=e=>{let t=[],n="",r=0,i=!1,o="";for(let a=0;a<e.length;a++){let c=e[a],l=a>0?e[a-1]:"";!i&&(c==='"'||c==="'")?(i=!0,o=c,n+=c):i&&c===o&&l!=="\\"?(i=!1,o="",n+=c):!i&&c==="("?(r++,n+=c):!i&&c===")"?(r--,n+=c):!i&&c===","&&r===0?(t.push(n),n=""):n+=c}return n&&t.push(n),t},Gt=(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=je(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"}],o=-1,a=null;for(let{op:c,type:l}of i){let s=0;for(;s<r.length;){let u=D(r.substring(s),c);if(u===-1)break;let f=s+u;f>o&&(o=f,a={op:c,type:l}),s=f+c.length}}if(o!==-1)try{return x(r,t)}catch{return{type:p.VARIABLE,path:r}}return{type:p.VARIABLE,path:r}},Ke=/^\w+\(.*\)$/,Qt=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Zt=e=>{if(!(!e||e.trim()===""||Ke.test(e))&&Qt.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}"`)},ze=e=>{let t=e.trim();if(Ke.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}},K=(e,t={})=>{let n=e.trim();Zt(n);let r=je(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 o of n)o==="["?i++:o==="]"&&i--;if(i!==0)throw new Error("Invalid array index syntax")}return{type:p.VARIABLE,path:n}},me=(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 i=[...n.matchAll(Ht)],o=[...n.matchAll(Jt)],a=[...i.map(s=>({match:s,type:"variable"})),...o.map(s=>({match:s,type:"pathref"}))].sort((s,u)=>s.match.index-u.match.index);if(a.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(a.length===1&&a[0].match[0]===n&&r.length===0){let{match:s,type:u}=a[0];try{return u==="variable"?K(s[1],t):ze(s[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:p.LITERAL,value:n};throw f}}let c=[],l=0;for(let{match:s,type:u}of a){let[f,d]=s,h=s.index;if(h>l){let g=n.substring(l,h);for(let y=0;y<r.length;y++)g=g.replace(`__ESCAPED_${y}__`,r[y]);g&&c.push(g)}try{let g;u==="variable"?g=K(d.trim(),t):g=ze(d.trim()),c.push(g)}catch(g){if(g.message==="Invalid array index syntax")c.push(f);else throw g}l=h+f.length}if(l<n.length){let s=n.substring(l);for(let u=0;u<r.length;u++)s=s.replace(`__ESCAPED_${u}__`,r[u]);s&&c.push(s)}return{type:p.INTERPOLATION,parts:c}};var S=(e,t)=>typeof e=="string"?me(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?tn(e,t):nn(e,t):{type:p.LITERAL,value:e},en=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}},tn=(e,t)=>{let n=[],r=!1;for(let i=0;i<e.length;i++){let o=e[i];if(typeof o=="object"&&o!==null&&!Array.isArray(o)){if(o.$each!==void 0)try{let l=en(o),s=Object.keys(l);if(s.length===1&&/^\$for(?::\w+)?\s/.test(s[0])){let u=Ye(s[0],l[s[0]],t,!0);n.push(u),r=!0;continue}}catch(l){throw l instanceof b?l:new b(l.message)}let c=Object.keys(o);if(c.length===1&&/^\$for(?::\w+)?\s/.test(c[0])){let l=Ye(c[0],o[c[0]],t);n.push(l),r=!0;continue}}let a=S(o,t);n.push(a),(a.type===p.FUNCTION||a.type===p.CONDITIONAL||a.type===p.LOOP||a.type===p.PARTIAL||a.type===p.OBJECT&&!a.fast||a.type===p.ARRAY&&!a.fast)&&(r=!0)}return{type:p.ARRAY,items:n,fast:!r}},nn=(e,t)=>{let n=[],r=!1,i=null,o=Object.entries(e),a=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 l=["$if","$elif","$else","$for"],s=[];for(let[m]of o)for(let _ of l)if(m===_||m.startsWith(_+" ")||m.startsWith(_+"#")){s.push(_);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,_]of Object.entries(d)){let v=m;(m.startsWith("\\$")||m.startsWith("$$"))&&(v=m.slice(1)),h[v]=_,g=!0}let y=null;if(g&&(y=S(h,t),y.type===p.OBJECT)){let m=!1;for(let _ of y.properties)if(_.value.type===p.VARIABLE||_.value.type===p.INTERPOLATION||_.value.type===p.FUNCTION||_.value.type===p.CONDITIONAL||_.value.type===p.OBJECT&&!_.value.fast||_.value.type===p.ARRAY&&!_.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[l,s]of o)if(l==="$when"){if(i!==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'");i=x(u,t),r=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new b("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;a<o.length;){let[l,s]=o[a];if(l==="$when"){a++;continue}if(l==="$each")throw new b("$each can only be used inside arrays");if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=rn(o,a,t);n.push({key:l,value:u.node}),r=!0,a=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.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(l.startsWith("$elif ")||l.startsWith("$else"))throw new b(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new b("Missing condition expression after '$if'");{let u=S(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=me(l,t),d={key:l,value:u};(f.type!==p.LITERAL||f.value!==l)&&(d.parsedKey=f),n.push(d),a++}}}let c={type:p.OBJECT,properties:n,fast:!r};return i&&(c.whenCondition=i),c},rn=(e,t,n={})=>{let r=[],i=[],o=t,[a,c]=e[o],l=null,s;if(a.startsWith("$if#")){let f=a.match(/^\$if#(\w+)\s+(.+)$/);if(f)l=f[1],s=f[2];else throw new b(`Invalid conditional syntax: ${a}`)}else s=a.substring(4),s.endsWith(":")&&(s=s.slice(0,-1).trim());ge(s);let u=x(s,n);for(r.push(u),i.push(S(c,n)),o++;o<e.length;){let[f,d]=e[o],h=!1,g;if(l?f.startsWith(`$elif#${l} `)?(g=f.substring(`$elif#${l} `.length),g.endsWith(":")&&(g=g.slice(0,-1).trim()),h=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(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{ge(g);let y=x(g,n);r.push(y)}if(i.push(S(d,n)),o++,g===null)break}else break}return{node:{type:p.CONDITIONAL,conditions:r,bodies:i,id:l},nextIndex:o}},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:A.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: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:s,type:u}of i){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 o=-1,a=null,c=[{op:" + ",type:A.ADD},{op:" - ",type:A.SUBTRACT}];for(let{op:s,type:u}of c){let f=0;for(;f<e.length;){let d=D(e.substring(f),s);if(d===-1)break;let h=f+d;h>o&&(o=h,a={op:s,type:u}),f=h+s.length}}if(o!==-1&&a)return{type:p.BINARY,op:a.type,left:x(e.substring(0,o).trim(),t),right:x(e.substring(o+a.op.length).trim(),t)};let l=[" * "," / "," % "];for(let s of l)if(D(e,s)!==-1)throw new b(`Arithmetic operations are not allowed in conditionals: "${s}"`);return e.startsWith("!")?{type:p.UNARY,op:j.NOT,operand:x(e.substring(1).trim(),t)}:He(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},on=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}},He=(e,t)=>{let n=e.trim();if(n.match(/^(\w+)\((.*)\)$/))return K(n,t);let i=on(n);if(i.type===p.LITERAL)return i;if(/^[a-zA-Z_$][\w.$]*$/.test(n))return{type:p.VARIABLE,path:n};try{return K(n,t)}catch(o){if(o.message&&o.message.includes("not supported"))return i;throw o}},sn=(e,t=!1)=>{let n=t?"$each":"$for";try{Te(e)}catch(r){if(r instanceof b&&t){let i=r.message.replace(/\$for/g,"$each");throw new b(i.replace("Parse Error: ",""))}throw r}},Ye=(e,t,n,r=!1)=>{let i=/^\$for(?::(\w+))?\s+(.+)$/,o=e.match(i);if(!o){let I=r?"$each":"$for";throw new b(`Invalid loop syntax (got: '${e.replace("$for",I)}')`)}let a=o[1],c=o[2].trim();sn(c,r);let l=c.match(/^(.+?)\s+in\s+(.+)$/);if(!l){let I=r?"$each":"$for";throw new b(`Invalid loop syntax - missing 'in' keyword (got: '${I} ${c}')`)}let s=l[1].trim(),u=l[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=He(u,n),y=S(t,n);return{type:p.LOOP,itemVar:f,indexVar:d,iterable:g,body:y,flatten:a!=="nested"}};var an=(e,t={})=>{let{functions:n={}}=t;return S(e,n)},ee=an;var be={};at(be,{now:()=>cn});var cn=()=>Date.now();var ln=(e,t,n={})=>{let{functions:r={},partials:i={}}=n,o={...be,...r},a=ee(e,{functions:o}),c={};for(let[l,s]of Object.entries(i))c[l]=ee(s,{functions:o});return ye(a,t,{functions:o,partials:c})},N=ln;var Ie={objectValues:e=>Object.entries(e).map(([t,n])=>({id:t,...n}))},un=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],animations:[],audio:[],global:{}}),fn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.base){let i=r.find(o=>o.id==="story");if(!i)return e;if(t.base.resourceId){let o=n?.layouts[t.base.resourceId];o&&i.children.unshift({id:"base",type:"container",children:o.elements})}}return e},dn=(e,{presentationState:t,previousPresentationState:n,resources:r={},variables:i,autoMode:o,skipMode:a,currentLocalizationPackageId:c})=>{let{elements:l}=e,s=e.animations||[];if(t.background){let u=l.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},pn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,i=e.animations||[];if(t.character&&n){let o=r.find(c=>c.id==="story");if(!o)return e;let a=t.character.items||[];for(let c of a){let{transformId:l,sprites:s}=c;if(c.animations&&c.animations.out&&!s&&!l){let h=c.animations.out.resourceId,g=n?.tweens[h];if(g){let y={id:"character-animation-out",type:"tween",targetId:`character-container-${c.id}`,properties:g.properties};i.push(y)}continue}if(!s||s.length===0||!l){console.warn("Character item missing sprites or transformId:",c);continue}let u=s.map(({resourceId:h})=>h),f=n.transforms[l];if(!f){console.warn("Transform not found:",l);continue}let d={type:"container",id:`character-container-${c.id}`,x:c.x??f.x,y:c.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:`${c.id}-${h.id}`,src:g.fileId,width:g.width,height:g.height,x:0,y:0})}if(o.children.push(d),c.animations){if(c.animations.in){let h=c.animations.in.resourceId,g=n?.tweens[h];g&&i.push({id:"character-animation-in",type:"tween",targetId:`character-container-${c.id}`,properties:g.properties})}if(c.animations.update){let h=c.animations.update.resourceId,g=n?.tweens[h];if(g){let y={id:"character-animation-update",type:"tween",targetId:`character-container-${c.id}`,properties:g.properties};i.push(y)}}}}}return e},hn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e,i=e.animations||[];if(t.visual&&n){let o=r.find(c=>c.id==="story");if(!o)return e;let a=t.visual.items;for(let c of a){if(c.resourceId){let{images:l={},videos:s={}}=n,u=l[c.resourceId]||s[c.resourceId];if(u){let f=s[c.resourceId]!==void 0,d=n.transforms[c.transformId],h={id:`visual-${c.id}`,type:f?"video":"sprite",src:u.fileId,width:u.width,height:u.height,x:d.x,y:d.y,anchorX:d.anchorX,anchorY:d.anchorY,rotation:d.rotation,scaleX:d.scaleX,scaleY:d.scaleY};f&&(h.loop=u.loop??!1,h.volume=u.volume??500),o.children.push(h)}}if(c.resourceId){let{layouts:l={}}=n,s=l[c.resourceId];if(s){let u=n.transforms[c.transformId];o.children.push({id:`visual-${c.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(c.animations){if(c.animations.in){let l=c.animations.in.resourceId||c.animations.in,s=n?.tweens[l];s&&i.push({id:`${c.id}-animation`,type:"tween",targetId:`visual-${c.id}`,properties:s.properties})}if(c.animations.out){let l=c.animations.out.resourceId||c.animations.out,s=n?.tweens[l];s&&i.push({id:`${c.id}-animation-2`,type:"tween",targetId:`visual-${c.id}`,properties:s.properties})}}}}return e},gn=(e,{presentationState:t,resources:n={},dialogueUIHidden:r,autoMode:i,skipMode:o,skipOnlyViewedLines:a,l10n:c,variables:l})=>{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:l,autoMode:i,skipMode:o,skipOnlyViewedLines:a,dialogue:{character:{name:h?.name||""},content:t.dialogue?.content||[{text:""}],lines:t.dialogue?.lines||[]},l10n:c},I=N(g,y,{functions:Ie});I=N(I,{l10n:c});let m=I?.elements;if(Array.isArray(m))for(let _ of m)u.children.push(structuredClone(_));else m&&u.children.push(structuredClone(m))}}return e},yn=(e,{presentationState:t,resources:n})=>{let{elements:r}=e;if(t.choice&&n){let i=r.find(s=>s.id==="story");if(!i)return e;let o=n?.layouts[t.choice.resourceId];if(!o||!o.elements)return e;let a={elements:o.elements},l=N(a,{choice:{items:t.choice.items}})?.elements;if(Array.isArray(l))for(let s of l)i.children.push(structuredClone(s));else l&&i.children.push(structuredClone(l))}return e},mn=(e,{presentationState:t,resources:n})=>{if(t.keyboard?.resourceId){let r=n?.keyboards?.[t.keyboard.resourceId];r&&(e.global.keyboard=r)}return e},bn=(e,{presentationState:t,resources:n})=>{let{elements:r,audio:i}=e;if(t.bgm&&n){if(!r.find(c=>c.id==="story"))return e;let a=n.sounds[t.bgm.resourceId];if(!a)return e;i.push({id:"bgm",type:"sound",src:a.fileId,loop:t.bgm.loop??!0,volume:t.bgm.volume??500,delay:t.bgm.delay??null})}return e},In=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(t.sfx&&n){let i=t.sfx.items;for(let o of i){let a=n.sounds?.[o.resourceId];a&&r.push({id:o.id,type:"sound",src:a.fileId,loop:o.loop??a.loop??!0,volume:o.volume??a.volume??500,delay:o.delay??a.delay??null})}}return e},_n=(e,{presentationState:t,resources:n})=>{let{audio:r}=e;if(!t?.voice)return e;let{fileId:i,volume:o,loop:a}=t.voice;return r.push({id:`voice-${i}`,type:"sound",src:i,volume:o??500,loop:a??!1}),e},wn=(e,{presentationState:t,resources:n={},variables:r,autoMode:i,skipMode:o,currentLocalizationPackageId:a})=>{let{elements:c}=e,l=e.animations||[];if(t.layout){let s=c.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=>{l.push(y)});let f={id:`layout-${t.layout.resourceId}`,type:"container",x:0,y:0,children:u.elements||[]},h=N(f,{variables:r,autoMode:i,skipMode:o,currentLocalizationPackageId:a},{functions:Ie});h=N(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},An=(e,{resources:t={},variables:n,autoMode:r,skipMode:i,currentLocalizationPackageId:o,layeredViews:a=[],dialogueHistory:c=[]})=>{let{elements:l}=e,s=e.animations||[];return a&&a.length>0&&a.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=c.map(m=>{let _=t.characters?.[m.characterId];return{...m,characterName:_?.name||""}}),y={variables:n,autoMode:r,skipMode:i,currentLocalizationPackageId:o,historyDialogue:g,characters:t.characters||{}},I=N(h,y,{functions:Ie});I=N(I,{i18n:{}}),l.push(I)}),e},Je=e=>Z(un,[fn,dn,pn,hn,gn,yn,mn,wn,bn,In,_n,An])(e);var En=e=>{let{global:{currentLocalizationPackageId:t,saveSlots:n},projectData:r}=e,i={sceneId:r.story.initialSceneId,sectionId:r.story.scenes[r.story.initialSceneId].initialSectionId,lineId:r.story.scenes[r.story.initialSceneId].sections[r.story.scenes[r.story.initialSceneId].initialSectionId].lines[0].id},o={projectData:r,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:[]},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:{}}]};return console.log("Initial State:",o),o},vn=({state:e})=>e.global.layeredViews||[],xn=({state:e})=>e.global.pendingEffects,Xe=({state:e})=>e.global.skipMode,Ln=({state:e})=>e.global.skipOnlyViewedLines,$n=({state:e})=>e.global.autoMode,qe=({state:e})=>e.global.dialogueUIHidden,kn=({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,i=C({state:e},{sectionId:n});if(!i?.lines||!Array.isArray(i.lines))return[];let o=i.lines.findIndex(l=>l.id===r);return i.lines.slice(0,o+1).filter(l=>l.actions?.dialogue).map(l=>{let s=l.actions.dialogue,u="";return s.characterId&&(u=e.projectData.resources?.characters?.[s.characterId]?.name||""),{content:s.content,characterId:s.characterId,characterName:u}})},Cn=({state:e})=>e.global.currentLocalizationPackageId,Ge=({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 o=C({state:e},{sectionId:n});if(!o||!o.lines||!Array.isArray(o.lines))return!1;let a=o.lines.findIndex(l=>l.id===i.lastLineId),c=o.lines.findIndex(l=>l.id===r);return a===-1||c===-1?i.lastLineId===r:c<a},On=({state:e},t)=>{let{resourceId:n}=t;return!!e.global.viewedRegistry.resources.find(i=>i.resourceId===n)},Rn=({state:e})=>e.global.nextLineConfig,Nn=({state:e})=>e.global.saveSlots,Sn=({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 o=r[i];if(o.sections&&o.sections[n])return o.sections[n]}},Pn=({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(o=>o.id===r)},Qe=({state:e})=>{let{sectionId:t,lineId:n}=W({state:e}).pointer,i=C({state:e},{sectionId:t})?.lines||[],o=i.findIndex(s=>s.id===n),a=i.slice(0,o+1);console.log("currentLines",a);let c=a.map(s=>{let u=s.actions||{},f={};return Object.keys(u).forEach(d=>{f[d]=u[d]}),f});return he(c)},Tn=({state:e})=>{let{sectionId:t,lineId:n}=W({state:e}).pointer,i=C({state:e},{sectionId:t})?.lines||[],o=i.findIndex(l=>l.id===n);if(o<=0)return null;let c=i.slice(0,o).map(l=>{let s=l.actions||{},u={};return Object.keys(s).forEach(f=>{u[f]=s[f]}),u});return he(c)},Vn=({state:e})=>{let t=Qe({state:e}),n=Tn({state:e});console.log("presentationState",t);let r=Je({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})});return console.log("renderState",r),r},Dn=({state:e},t)=>(e.global.layeredViews.push(t),e.global.pendingEffects.push({name:"render"}),e),Mn=({state:e})=>(e.global.layeredViews.pop(),e.global.pendingEffects.push({name:"render"}),e),Bn=({state:e},t)=>(e.global.layeredViews.length>0&&(e.global.layeredViews[e.global.layeredViews.length-1]=t),e.global.pendingEffects.push({name:"render"}),e),Fn=({state:e})=>(e.global.layeredViews=[],e.global.pendingEffects.push({name:"render"}),e),Ze=({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),we=({state:e})=>(e.global.autoMode=!1,e.global.pendingEffects.push({name:"clearAutoNextTimer"}),e.global.pendingEffects.push({name:"render"}),e),Wn=({state:e})=>(e.global.autoMode?we({state:e}):Ze({state:e}),e),et=({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),Un=({state:e})=>(Xe({state:e})?te({state:e}):et({state:e}),e),zn=({state:e},t)=>{let{skipOnlyViewedLines:n}=t;return e.global.skipOnlyViewedLines=n,e.global.pendingEffects.push({name:"render"}),e},jn=({state:e})=>(e.global.skipOnlyViewedLines=!e.global.skipOnlyViewedLines,e.global.pendingEffects.push({name:"render"}),e),tt=({state:e})=>(e.global.dialogueUIHidden=!1,e.global.pendingEffects.push({name:"render"}),e),nt=({state:e})=>(e.global.dialogueUIHidden=!0,e.global.pendingEffects.push({name:"render"}),e),Kn=({state:e})=>(qe({state:e})?tt({state:e}):nt({state:e}),e),Yn=({state:e})=>{let t=_e({state:e});return e.global.isDialogueHistoryShowing=!0,e.global.pendingEffects.push({name:"render"}),e},Hn=({state:e})=>(e.global.isDialogueHistoryShowing=!1,e.global.pendingEffects.push({name:"render"}),e),Jn=({state:e},t)=>{let{localizationPackageId:n}=t;return e.global.currentLocalizationPackageId=n,e.global.pendingEffects.push({name:"render"}),e},Xn=({state:e})=>(e.global.pendingEffects=[],e),qn=({state:e},t)=>(e.global.pendingEffects.push(t),e),rt=({state:e},t)=>{let{sectionId:n,lineId:r}=t,i=e.global.viewedRegistry.sections.find(o=>o.sectionId===n);if(i){let o=C({state:e},{sectionId:n});if(o?.lines&&i.lastLineId!==void 0){let a=o.lines.findIndex(l=>l.id===i.lastLineId),c=o.lines.findIndex(l=>l.id===r);(a===-1||c>a)&&(i.lastLineId=r)}else i.lastLineId=r}else e.global.viewedRegistry.sections.push({sectionId:n,lastLineId:r});return e.global.pendingEffects.push({name:"render"}),e},Gn=({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},Qn=({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},Zn=({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),er=({state:e},t)=>{let{slot:n,thumbnailImage:r}=t,i=String(n),o={contexts:[...e.contexts],viewedRegistry:e.global.viewedRegistry},a={slotKey:i,date:Date.now(),image:r,state:o};return e.global.saveSlots[i]=a,e.global.pendingEffects.push({name:"saveSlots",payload:{saveSlots:{...e.global.saveSlots}}},{name:"render"}),e},tr=({state:e},t)=>{let{slot:n}=t,r=String(n),i=e.global.saveSlots[r];return i&&(e.global.viewedRegistry=i.state.viewedRegistry,e.contexts=i.state.contexts,e.global.pendingEffects.push({name:"render"})),e},nr=({state:e},t)=>{let{projectData:n}=t;return e.projectData=n,e.global.pendingEffects.push({name:"render"}),e},rr=({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 o=n||i.pointers.read?.sectionId;if(n&&!C({state:e},{sectionId:n}))return console.warn(`Section not found: ${n}`),e;let a=C({state:e},{sectionId:o});return!a?.lines||!Array.isArray(a.lines)?(console.warn(`Section ${o} has no lines`),e):a.lines.find(l=>l.id===r)?(i.pointers.read={sectionId:o,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 ${o}`),e)},ir=({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},or=({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||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a],l=e.contexts[e.contexts.length-1];l&&(l.pointers.read={sectionId:n,lineId:c.id}),e.global.isLineCompleted=!1,e.global.nextLineConfig.auto={},e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}return e},sr=({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||[],a=i.findIndex(c=>c.id===t?.lineId)+1;if(a<i.length){let c=i[a];e.global.skipMode&&e.global.skipOnlyViewedLines&&(Ge({state:e},{sectionId:n,lineId:c.id})||te({state:e}));let l=e.contexts[e.contexts.length-1];if(l){let s=l.pointers.read.lineId;s&&n&&rt({state:e},{sectionId:n,lineId:s}),l.pointers.read={sectionId:n,lineId:c.id}}e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"})}else e.global.autoMode&&we({state:e}),e.global.skipMode&&te({state:e});return console.log("state",e),e},ar=({state:e})=>(e.global.isLineCompleted=!0,e.global.pendingEffects.push({name:"render"}),e),cr=({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,o=e.contexts[e.contexts.length-1];if(!o||!o.pointers)return e;let a=o.pointers.history||o.pointers.read;if(o.currentPointerMode!=="history"||!o.pointers.history){if(!a)return e;o.currentPointerMode="history",o.pointers.history={sectionId:n,lineId:a?.lineId};let u=i.findIndex(f=>f.id===a.lineId)-1;if(u>=0&&u<i.length){let f=i[u];o.pointers.history={sectionId:n,lineId:f.id}}return e.global.pendingEffects.push({name:"render"}),e}let l=i.findIndex(s=>s.id===o.pointers.history.lineId)-1;if(l>=0&&l<i.length){let s=i[l];o.pointers.history={sectionId:n,lineId:s.id},e.global.pendingEffects.push({name:"render"})}return e},lr=({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 o=e.contexts[e.contexts.length-1];return o&&(o.pointers.read={sectionId:n,lineId:i.id}),e.global.isLineCompleted=!1,e.global.pendingEffects.push({name:"render"}),e.global.pendingEffects.push({name:"handleLineActions"}),e},it=e=>{let t=En(e);return Pe(t,{selectPendingEffects:xn,selectSkipMode:Xe,selectSkipOnlyViewedLines:Ln,selectAutoMode:$n,selectDialogueUIHidden:qe,selectDialogueHistory:_e,selectCurrentLocalizationPackageId:Cn,selectIsLineViewed:Ge,selectIsResourceViewed:On,selectNextLineConfig:Rn,selectSaveSlots:Nn,selectSaveSlot:Sn,selectCurrentPointer:W,selectSection:C,selectCurrentLine:Pn,selectPresentationState:Qe,selectAutoplayDelay:kn,selectRenderState:Vn,selectLayeredViews:vn,startAutoMode:Ze,stopAutoMode:we,toggleAutoMode:Wn,startSkipMode:et,stopSkipMode:te,toggleSkipMode:Un,setSkipOnlyViewedLines:zn,toggleSkipOnlyViewedLines:jn,showDialogueUI:tt,hideDialogueUI:nt,toggleDialogueUI:Kn,showDialogueHistory:Yn,hideDialogueHistory:Hn,setCurrentLocalizationPackageId:Jn,clearPendingEffects:Xn,appendPendingEffect:qn,addViewedLine:rt,addViewedResource:Gn,setNextLineConfig:Qn,saveSaveSlot:er,loadSaveSlot:tr,setAutoplayDelay:Zn,updateProjectData:nr,sectionTransition:lr,jumpToLine:rr,addToHistorySequence:ir,nextLine:sr,nextLineFromCompleted:or,markLineCompleted:ar,prevLine:cr,pushLayeredView:Dn,popLayeredView:Mn,replaceLastLayeredView:Bn,clearLayeredViews:Fn},{transformActionFirstArgument:r=>({state:r}),transformSelectorFirstArgument:r=>({state:r})})};function Ae(e){let t,{handlePendingEffects:n}=e,r=({initialState:u})=>{t=it(u),t.appendPendingEffect({name:"render"}),s(),n(t.selectPendingEffects()),t.clearPendingEffects()},i=()=>t.selectPresentationState(),o=()=>t.selectRenderState(),a=()=>t.selectSaveSlots(),c=(u,f)=>{t[u]&&(t[u](f),n(t.selectPendingEffects()),t.clearPendingEffects())},l=u=>{Object.entries(u).forEach(([f,d])=>{c(f,d)})},s=()=>{let u=t.selectCurrentLine();u&&u.actions&&l(u.actions)};return{init:r,handleAction:c,handleActions:l,selectRenderState:o,selectPresentationState:i,selectSaveSlots:a,handleLineActions:s}}var ot=()=>{let e=0,t=null;return{getElapsed:()=>e,setElapsed:n=>{e=n},addElapsed:n=>{e+=n},getCallback:()=>t,setCallback:n=>{t=n}}},ur=({engine:e,routeGraphics:t},n)=>{let r=e.selectRenderState();t.render(r)},fr=({engine:e},t)=>{e.handleLineActions()},dr=({engine:e,ticker:t,autoTimer:n},r)=>{let i=n.getCallback();i&&t.remove(i),n.setElapsed(0);let o=a=>{n.addElapsed(a.deltaMS);let c=r.delay??1e3;n.getElapsed()>=c&&(n.setElapsed(0),e.handleAction("nextLine",{}))};n.setCallback(o),t.add(o)},pr=({ticker:e,autoTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},hr=({engine:e,ticker:t,skipTimer:n},r)=>{let i=n.getCallback();i&&t.remove(i),n.setElapsed(0);let o=a=>{n.addElapsed(a.deltaMS),n.getElapsed()>=30&&(n.setElapsed(0),e.handleAction("nextLine",{}))};n.setCallback(o),t.add(o)},gr=({ticker:e,skipTimer:t},n)=>{let r=t.getCallback();r&&(e.remove(r),t.setCallback(null)),t.setElapsed(0)},yr=({},e)=>{localStorage.setItem("saveSlots",JSON.stringify(e.saveSlots))},mr={render:ur,saveSlots:yr,handleLineActions:fr,startAutoNextTimer:dr,clearAutoNextTimer:pr,startSkipNextTimer:hr,clearSkipNextTimer:gr},br=({getEngine:e,routeGraphics:t,ticker:n})=>{let r=ot(),i=ot();return async o=>{let a=e(),c=o.reduce((u,f)=>(u[f.name]=f,u),{}),l=Object.values(c),s={engine:a,routeGraphics:t,ticker:n,autoTimer:r,skipTimer:i};for(let u of l){let f=mr[u.name];f&&f(s,u.payload)}}},Ir=br;var pi=Ae;export{Ir as createEffectsHandler,pi 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.7",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "main": "dist/RouteEngine.js",
6
6
  "exports": {
@@ -24,7 +24,7 @@
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",