route-engine-js 0.0.2-rc9 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,7 +13,7 @@ src/
13
13
  ├── schemas/ # YAML schemas for project data
14
14
  │ ├── projectData/ # Individual data schemas
15
15
  │ ├── system.yaml # System state schema
16
- │ └── systemActions.yaml # System actions schema
16
+ │ └── system.yaml # System actions schema
17
17
  ├── stores/ # State management stores
18
18
  │ ├── constructPresentationState.js
19
19
  │ ├── constructRenderState.js
@@ -1 +1 @@
1
- var It=Object.defineProperty;var N=(e,t)=>{for(var r in t)It(e,r,{get:t[r],enumerable:!0})};var we=Symbol.for("immer-nothing"),Ae=Symbol.for("immer-draftable"),I=Symbol.for("immer-state");function A(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var P=Object.getPrototypeOf;function O(e){return!!e&&!!e[I]}function E(e){return e?Pe(e)||Array.isArray(e)||!!e[Ae]||!!e.constructor?.[Ae]||F(e)||z(e):!1}var xt=Object.prototype.constructor.toString();function Pe(e){if(!e||typeof e!="object")return!1;let t=P(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===xt}function R(e,t){V(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function V(e){let t=e[I];return t?t.type_:Array.isArray(e)?1:F(e)?2:z(e)?3:0}function J(e,t){return V(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Oe(e,t,r){let n=V(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function At(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function F(e){return e instanceof Map}function z(e){return e instanceof Set}function S(e){return e.copy_||e.base_}function X(e,t){if(F(e))return new Map(e);if(z(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Pe(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[I];let s=Reflect.ownKeys(n);for(let o=0;o<s.length;o++){let i=s[o],c=n[i];c.writable===!1&&(c.writable=!0,c.configurable=!0),(c.get||c.set)&&(n[i]={configurable:!0,writable:!0,enumerable:c.enumerable,value:e[i]})}return Object.create(P(e),n)}else{let n=P(e);if(n!==null&&r)return{...e};let s=Object.create(n);return Object.assign(s,e)}}function Z(e,t=!1){return j(e)||O(e)||!E(e)||(V(e)>1&&(e.set=e.add=e.clear=e.delete=bt),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Z(n,!0))),e}function bt(){A(2)}function j(e){return Object.isFrozen(e)}var St={};function v(e){let t=St[e];return t||A(0,e),t}var k;function $e(){return k}function Et(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function be(e,t){t&&(v("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function G(e){H(e),e.drafts_.forEach(vt),e.drafts_=null}function H(e){e===k&&(k=e.parent_)}function Se(e){return k=Et(k,e)}function vt(e){let t=e[I];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Ee(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[I].modified_&&(G(t),A(4)),E(e)&&(e=T(t,e),t.parent_||M(t,e)),t.patches_&&v("Patches").generateReplacementPatches_(r[I].base_,e,t.patches_,t.inversePatches_)):e=T(t,r,[]),G(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==we?e:void 0}function T(e,t,r){if(j(t))return t;let n=t[I];if(!n)return R(t,(s,o)=>ve(e,n,t,s,o,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return M(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let s=n.copy_,o=s,i=!1;n.type_===3&&(o=new Set(s),s.clear(),i=!0),R(o,(c,a)=>ve(e,n,s,c,a,r,i)),M(e,s,!1),r&&e.patches_&&v("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function ve(e,t,r,n,s,o,i){if(O(s)){let c=o&&t&&t.type_!==3&&!J(t.assigned_,n)?o.concat(n):void 0,a=T(e,s,c);if(Oe(r,n,a),O(a))e.canAutoFreeze_=!1;else return}else i&&r.add(s);if(E(s)&&!j(s)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;T(e,s),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&M(e,s)}}function M(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Z(t,r)}function wt(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:$e(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},s=n,o=ee;r&&(s=[n],o=C);let{revoke:i,proxy:c}=Proxy.revocable(s,o);return n.draft_=c,n.revoke_=i,c}var ee={get(e,t){if(t===I)return e;let r=S(e);if(!J(r,t))return Pt(e,r,t);let n=r[t];return e.finalized_||!E(n)?n:n===Y(e.base_,t)?(K(e),e.copy_[t]=q(n,e)):n},has(e,t){return t in S(e)},ownKeys(e){return Reflect.ownKeys(S(e))},set(e,t,r){let n=Ne(S(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let s=Y(S(e),t),o=s?.[I];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(At(r,s)&&(r!==void 0||J(e.base_,t)))return!0;K(e),Q(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return Y(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,K(e),Q(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=S(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){A(11)},getPrototypeOf(e){return P(e.base_)},setPrototypeOf(){A(12)}},C={};R(ee,(e,t)=>{C[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});C.deleteProperty=function(e,t){return C.set.call(this,e,t,void 0)};C.set=function(e,t,r){return ee.set.call(this,e[0],t,r,e[0])};function Y(e,t){let r=e[I];return(r?S(r):e)[t]}function Pt(e,t,r){let n=Ne(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Ne(e,t){if(!(t in e))return;let r=P(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=P(r)}}function Q(e){e.modified_||(e.modified_=!0,e.parent_&&Q(e.parent_))}function K(e){e.copy_||(e.copy_=X(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ot=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let o=r;r=t;let i=this;return function(a=o,...u){return i.produce(a,f=>r.call(this,f,...u))}}typeof r!="function"&&A(6),n!==void 0&&typeof n!="function"&&A(7);let s;if(E(t)){let o=Se(this),i=q(t,void 0),c=!0;try{s=r(i),c=!1}finally{c?G(o):H(o)}return be(o,n),Ee(s,o)}else if(!t||typeof t!="object"){if(s=r(t),s===void 0&&(s=t),s===we&&(s=void 0),this.autoFreeze_&&Z(s,!0),n){let o=[],i=[];v("Patches").generateReplacementPatches_(t,s,o,i),n(o,i)}return s}else A(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(i,...c)=>this.produceWithPatches(i,a=>t(a,...c));let n,s;return[this.produce(t,r,(i,c)=>{n=i,s=c}),n,s]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){E(e)||A(8),O(e)&&(e=$t(e));let t=Se(this),r=q(e,void 0);return r[I].isManual_=!0,H(t),r}finishDraft(e,t){let r=e&&e[I];(!r||!r.isManual_)&&A(9);let{scope_:n}=r;return be(n,t),Ee(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let s=t[r];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}r>-1&&(t=t.slice(r+1));let n=v("Patches").applyPatches_;return O(e)?n(e,t):this.produce(e,s=>n(s,t))}};function q(e,t){let r=F(e)?v("MapSet").proxyMap_(e,t):z(e)?v("MapSet").proxySet_(e,t):wt(e,t);return(t?t.scope_:$e()).drafts_.push(r),r}function $t(e){return O(e)||A(10,e),ke(e)}function ke(e){if(!E(e)||j(e))return e;let t=e[I],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=X(e,t.scope_.immer_.useStrictShallowCopy_)}else r=X(e,!0);return R(r,(n,s)=>{Oe(r,n,ke(s))}),t&&(t.finalized_=!1),r}var x=new Ot,te=x.produce,Dr=x.produceWithPatches.bind(x),Rr=x.setAutoFreeze.bind(x),Tr=x.setUseStrictShallowCopy.bind(x),Mr=x.applyPatches.bind(x),Vr=x.createDraft.bind(x),Fr=x.finishDraft.bind(x);var re=(e,t,r={})=>{let n=structuredClone(e),s={},o={},{transformSelectorFirstArgument:i=a=>a,transformActionFirstArgument:c=a=>a}=r;for(let[a,u]of Object.entries(t))a!=="createInitialState"&&(a.startsWith("select")?s[a]=(...f)=>u(i(n),...f):o[a]=(...f)=>{n=te(n,_=>u(c(_),...f))});return{...s,...o}},ne=(e,t)=>r=>{let n=e(),s=Array.isArray(r)?r:[r];return te(n,o=>{s.forEach(i=>{t.forEach(c=>{c(o,i)})})})};var fe={};N(fe,{addBackgrundOrCg:()=>We,addBgm:()=>Ge,addCharacters:()=>Be,addChoices:()=>Xe,addDialogue:()=>Ke,addLayouts:()=>Je,addSfx:()=>He,addVisuals:()=>Ye,createInitialState:()=>Jt,default:()=>ue,generateScreenBackgroundElement:()=>Ue});var l={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9},d={EQ:0,NEQ:1,GT:2,LT:3,GTE:4,LTE:5,AND:6,OR:7,IN:8},L={NOT:0};var g=class extends Error{constructor(t){super(`Parse Error: ${t}`),this.name="JemplParseError"}},$=class extends Error{constructor(t){super(`Render Error: ${t}`),this.name="JemplRenderError"}};var se=e=>{if(!e||e.trim()==="")throw new g("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new g(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new g(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Ce=e=>{if(e.trim().endsWith(" in"))throw new g(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new g(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new g(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(t.includes(",")){let n=t.split(",").map(s=>s.trim());for(let s of n)if(!s)throw new g(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`)}else if(!t.trim())throw new g(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`)};var Le=(e,t)=>{if(t===null)return new $(`Cannot iterate over null value at '$for ${e}'`);if(t===void 0)return new $(`Cannot iterate over undefined value at '$for ${e}'`);let r=typeof t;return new $(`Cannot iterate over non-array value (got: ${r}) at '$for ${e}'`)},De=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new $(`Unknown function '${e}' (${r})`)};var Nt=(e,t,r={})=>h(e,r,t,{}),h=(e,t,r,n)=>{switch(e.type){case l.LITERAL:return e.value;case l.VARIABLE:return Re(e.path,r,n);case l.INTERPOLATION:return kt(e.parts,t,r,n);case l.FUNCTION:return Te(e,t,r,n);case l.BINARY:return Me(e,t,r,n);case l.UNARY:return Ve(e,t,r,n);case l.CONDITIONAL:return Ct(e,t,r,n);case l.LOOP:return Lt(e,t,r,n);case l.OBJECT:return Dt(e,t,r,n);case l.ARRAY:return Rt(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},Re=(e,t,r)=>{if(!e)return;if(r.hasOwnProperty(e))return r[e];let n=e.split("."),s=t;for(let o=0;o<n.length;o++){let i=n[o];if(r.hasOwnProperty(i)){s=r[i];continue}if(s==null)return;s=s[i]}return s},kt=(e,t,r,n)=>{let s="";for(let o of e)if(typeof o=="string")s+=o;else{let i=h(o,t,r,n);s+=i!=null?String(i):""}return s},Te=(e,t,r,n)=>{let s=t[e.name];if(!s)throw De(e.name,t);let o=e.args.map(i=>h(i,t,r,n));return s(...o)},U=(e,t,r,n)=>{switch(e.type){case l.VARIABLE:return Re(e.path,r,n);case l.LITERAL:return e.value;case l.BINARY:return Me(e,t,r,n);case l.UNARY:return Ve(e,t,r,n);case l.FUNCTION:return Te(e,t,r,n);default:return h(e,t,r,n)}},Me=(e,t,r,n)=>{if(e.op===d.AND||e.op===d.OR){let i=U(e.left,t,r,n),c=U(e.right,t,r,n);switch(e.op){case d.AND:return i&&c;case d.OR:return i||c}}let s=h(e.left,t,r,n),o=h(e.right,t,r,n);switch(e.op){case d.EQ:return s==o;case d.NEQ:return s!=o;case d.GT:return s>o;case d.LT:return s<o;case d.GTE:return s>=o;case d.LTE:return s<=o;case d.IN:return Array.isArray(o)?o.includes(s):!1;default:throw new Error(`Unknown binary operator: ${e.op}`)}},Ve=(e,t,r,n)=>{let s=e.op===L.NOT?U(e.operand,t,r,n):h(e.operand,t,r,n);switch(e.op){case L.NOT:return!s;default:throw new Error(`Unknown unary operator: ${e.op}`)}},Ct=(e,t,r,n)=>{for(let s=0;s<e.conditions.length;s++){let o=e.conditions[s];if(o===null||U(o,t,r,n))return h(e.bodies[s],t,r,n)}return{}},Lt=(e,t,r,n)=>{let s=h(e.iterable,t,r,n);if(!Array.isArray(s)){let i=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${e.iterable.path}`;throw Le(i,s)}let o=[];for(let i=0;i<s.length;i++){let c=Object.create(n);c[e.itemVar]=s[i],e.indexVar&&(c[e.indexVar]=i);let a=h(e.body,t,r,c);Array.isArray(a)&&a.length===1?o.push(a[0]):o.push(a)}return o},Dt=(e,t,r,n)=>{let s={},o=null,i=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){i=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let a=h(c.value,t,r,n);if(!i&&a!==null&&a!==void 0)return Array.isArray(a)&&a.length===1?a[0]:a;typeof a=="object"&&a!==null&&!Array.isArray(a)&&Object.assign(s,a)}else if(!c.key.startsWith("$for ")){let a=c.value;if(a&&a.type===l.OBJECT&&a.properties){let u=a.properties.find(f=>f.key.startsWith("$for "));if(u){let f=h(u.value,t,r,n);f!==void 0&&(s[c.key]=f)}else{let f=h(c.value,t,r,n);f!==void 0&&(s[c.key]=f)}}else{let u=c.parsedKey?h(c.parsedKey,t,r,n):c.key,f=h(c.value,t,r,n);f!==void 0&&(s[u]=f)}}return s},Rt=(e,t,r,n)=>{let s=[];for(let o of e.items)if(o.type===l.LOOP){let i=h(o,t,r,n);s.push(i)}else s.push(h(o,t,r,n));return s},oe=Nt;var Tt=/\$\{([^}]*)\}/g,ze=e=>{let t=e.match(/^(\w+)\((.*)\)$/);if(!t)return{isFunction:!1};let[,r,n]=t,s=Mt(n);return{isFunction:!0,type:l.FUNCTION,name:r,args:s}},Mt=e=>e.trim()?Vt(e).map(r=>Ft(r.trim())):[],Vt=e=>{let t=[],r="",n=0,s=!1,o="";for(let i=0;i<e.length;i++){let c=e[i],a=i>0?e[i-1]:"";!s&&(c==='"'||c==="'")?(s=!0,o=c,r+=c):s&&c===o&&a!=="\\"?(s=!1,o="",r+=c):!s&&c==="("?(n++,r+=c):!s&&c===")"?(n--,r+=c):!s&&c===","&&n===0?(t.push(r),r=""):r+=c}return r&&t.push(r),t},Ft=e=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:l.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:l.LITERAL,value:parseFloat(e)};if(e==="true")return{type:l.LITERAL,value:!0};if(e==="false")return{type:l.LITERAL,value:!1};if(e==="null")return{type:l.LITERAL,value:null};let t=ze(e);return t.isFunction?{type:t.type,name:t.name,args:t.args}:{type:l.VARIABLE,path:e}},Fe=(e,t={})=>{let r=e.trim(),n=ze(r);return n.isFunction?{type:n.type,name:n.name,args:n.args}:{type:l.VARIABLE,path:r}},ie=(e,t={})=>{let r=e,n=[];e.includes("\\${")&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(c,a)=>{let u=`__ESCAPED_${n.length}__`;return n.push(a),u}),r=r.replace(/\\DOUBLE_ESC/g,"\\"));let s=[...r.matchAll(Tt)];if(s.length===0){let c=r;for(let a=0;a<n.length;a++)c=c.replace(`__ESCAPED_${a}__`,n[a]);return{type:l.LITERAL,value:c}}if(s.length===1&&s[0][0]===r&&n.length===0)return Fe(s[0][1],t);let o=[],i=0;for(let c of s){let[a,u]=c,f=c.index;if(f>i){let _=r.substring(i,f);for(let y=0;y<n.length;y++)_=_.replace(`__ESCAPED_${y}__`,n[y]);_&&o.push(_)}let p=Fe(u.trim(),t);o.push(p),i=f+a.length}if(i<r.length){let c=r.substring(i);for(let a=0;a<n.length;a++)c=c.replace(`__ESCAPED_${a}__`,n[a]);c&&o.push(c)}return{type:l.INTERPOLATION,parts:o}};var w=(e,t)=>typeof e=="string"?ie(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?zt(e,t):jt(e,t):{type:l.LITERAL,value:e},zt=(e,t)=>{let r=[],n=!1;for(let s=0;s<e.length;s++){let o=e[s];if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let c=Object.keys(o);if(c.length===1&&c[0].startsWith("$for ")){let a=je(c[0],o[c[0]],t);r.push(a),n=!0;continue}}let i=w(o,t);r.push(i),(i.type===l.FUNCTION||i.type===l.CONDITIONAL||i.type===l.LOOP||i.type===l.OBJECT&&!i.fast||i.type===l.ARRAY&&!i.fast)&&(n=!0)}return{type:l.ARRAY,items:r,fast:!n}},jt=(e,t)=>{let r=[],n=!1,s=Object.entries(e),o=0;for(;o<s.length;){let[i,c]=s[o];if(i.startsWith("$if ")||i.match(/^\$if#\w+\s/)||i.match(/^\$if\s+\w+.*:$/)){let a=Ut(s,o,t);r.push({key:i,value:a.node}),n=!0,o=a.nextIndex}else if(i.startsWith("$for ")){let a=je(i,c,t);r.push({key:i,value:a}),n=!0,o++}else{if(i.startsWith("$elif ")||i.startsWith("$else"))throw new g(`'${i.split(" ")[0]}' without matching '$if'`);if(i==="$if"||i==="$if:")throw new g("Missing condition expression after '$if'");{let a=w(c,t);(a.type===l.FUNCTION||a.type===l.CONDITIONAL||a.type===l.LOOP||a.type===l.OBJECT&&!a.fast||a.type===l.ARRAY&&!a.fast)&&(n=!0);let u=ie(i,t),f={key:i,value:a};(u.type!==l.LITERAL||u.value!==i)&&(f.parsedKey=u),r.push(f),o++}}}return{type:l.OBJECT,properties:r,fast:!n}},Ut=(e,t,r={})=>{let n=[],s=[],o=t,[i,c]=e[o],a=null,u;if(i.startsWith("$if#")){let p=i.match(/^\$if#(\w+)\s+(.+)$/);if(p)a=p[1],u=p[2];else throw new g(`Invalid conditional syntax: ${i}`)}else u=i.substring(4),u.endsWith(":")&&(u=u.slice(0,-1).trim());se(u);let f=b(u);for(n.push(f),s.push(w(c,r)),o++;o<e.length;){let[p,_]=e[o],y=!1,m;if(a?p.startsWith(`$elif#${a} `)?(m=p.substring(`$elif#${a} `.length),m.endsWith(":")&&(m=m.slice(0,-1).trim()),y=!0):(p===`$else#${a}`||p===`$else#${a}:`)&&(y=!0,m=null):p.startsWith("$elif ")?(m=p.substring(6),m.endsWith(":")&&(m=m.slice(0,-1).trim()),y=!0):(p==="$else"||p==="$else:")&&(y=!0,m=null),y){if(m===null)n.push(null);else{se(m);let B=b(m);n.push(B)}if(s.push(w(_,r)),o++,m===null)break}else break}return{node:{type:l.CONDITIONAL,conditions:n,bodies:s,id:a},nextIndex:o}},b=e=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")"))return b(e.slice(1,-1));let t=ce(e,"||");if(t!==-1)return{type:l.BINARY,op:d.OR,left:b(e.substring(0,t).trim()),right:b(e.substring(t+2).trim())};let r=ce(e,"&&");if(r!==-1)return{type:l.BINARY,op:d.AND,left:b(e.substring(0,r).trim()),right:b(e.substring(r+2).trim())};let n=[{op:">=",type:d.GTE},{op:"<=",type:d.LTE},{op:"==",type:d.EQ},{op:"!=",type:d.NEQ},{op:">",type:d.GT},{op:"<",type:d.LT},{op:" in ",type:d.IN}];for(let{op:s,type:o}of n){let i=ce(e,s);if(i!==-1)return{type:l.BINARY,op:o,left:b(e.substring(0,i).trim()),right:b(e.substring(i+s.length).trim())}}return e.startsWith("!")?{type:l.UNARY,op:L.NOT,operand:b(e.substring(1).trim())}:Wt(e)},ce=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},Wt=e=>{if(e=e.trim(),e==="true")return{type:l.LITERAL,value:!0};if(e==="false")return{type:l.LITERAL,value:!1};if(e==="null")return{type:l.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:l.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:l.LITERAL,value:""};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:l.LITERAL,value:t}:{type:l.VARIABLE,path:e}},je=(e,t,r)=>{let n=e.substring(5).trim();Ce(n);let s=n.match(/^(.+?)\s+in\s+(.+)$/);if(!s)throw new g(`Invalid loop syntax - missing 'in' keyword (got: '$for ${n}')`);let o=s[1].trim(),i=s[2].trim(),c,a=null;if(o.includes(",")){let p=o.split(",").map(_=>_.trim());if(p.length!==2)throw new g(`Invalid loop variables: ${o}. Expected format: "item" or "item, index"`);c=p[0],a=p[1]}else c=o;let u={type:l.VARIABLE,path:i},f=w(t,r);return{type:l.LOOP,itemVar:c,indexVar:a,iterable:u,body:f}};var Bt=(e,t={})=>{let{functions:r={}}=t;return w(e,r)},ae=Bt;var le={};N(le,{now:()=>Yt});var Yt=()=>Date.now();var Kt=(e,t,r={})=>{let{functions:n={}}=r,s={...le,...n},o=ae(e,{functions:s});return oe(o,t,s)},D=Kt;var Jt=()=>({elements:[],transitions:[]}),Ue=({elements:e},{screen:t})=>{e.push({id:"bg-screen",type:"rect",x:0,width:t.width,y:0,height:t.height,fill:t.backgroundColor,clickEventName:"LeftClick",rightClickEventName:"RightClick",wheelEventName:"ScrollUp"})},We=({elements:e,transitions:t},{presentationState:r,assets:n,resolveFile:s})=>{if(r.background){if(r.background.imageId){let o=n.images[r.background.imageId];e.push({id:"bg-cg",type:"sprite",x:0,y:0,url:s(o.fileId)})}if(r.background.animations){if(r.background.animations.in){let o=n.animations[r.background.animations.in];t.push({id:"bg-cg-animation",type:"keyframes",event:"add",elementId:"bg-cg",animationProperties:o.properties})}if(r.background.animations.out){let o=n.animations[r.background.animations.out];o&&t.push({id:"bg-cg-animation-2",type:"keyframes",event:"remove",elementId:"bg-cg",animationProperties:o.properties})}}}},Be=({elements:e,transitions:t},{presentationState:r,assets:n,resolveFile:s})=>{if(r.character){let o=r.character.items;for(let i of o){let{transformId:c,spriteParts:a}=i,u=a.map(({spritePartId:y})=>y),f=n.transforms[c],p={type:"container",id:`character-container-${i.id}`,x:f.x,y:f.y,anchorX:f.anchorX,anchorY:f.anchorY,rotation:f.rotation,scaleX:f.scaleX,scaleY:f.scaleY,children:[]},_=[];Object.entries(n.characters).flatMap(([y,m])=>{let{spriteParts:B}=m;Object.entries(B).map(([xe,_t])=>{u.includes(xe)&&_.push({partId:xe,fileId:_t.fileId})})});for(let y of _)p.children.push({type:"sprite",id:`${i.id}-${y.partId}`,url:s(y.fileId),x:0,y:0});e.push(p)}}},Ye=({elements:e,transitions:t},{presentationState:r,assets:n,resolveFile:s})=>{if(r.visual){let o=r.visual.items;for(let i of o){if(i.visualId){let c=n.visuals[i.visualId],a=n.transforms[i.transformId];e.push({id:`visual-${i.visualId}`,type:"sprite",url:s(c.fileId),x:a.x,y:a.y,anchorX:a.anchorX,anchorY:a.anchorY,rotation:a.rotation,scaleX:a.scaleX,scaleY:a.scaleY})}if(i.animations){if(i.animations.in){let c=n.animations[i.animations.in];t.push({id:`${i.id}-animation`,type:"keyframes",event:"add",elementId:`visual-${i.id}`,animationProperties:c.properties})}if(i.animations.out){let c=n.animations[i.animations.out];t.push({id:`${i.id}-animation-2`,type:"keyframes",event:"remove",elementId:`visual-${i.id}`,animationProperties:c.properties})}}}}},Ke=({elements:e},{presentationState:t,ui:r,assets:n,dialogueUIHidden:s})=>{if(!t.dialogue||s)return;let o=r.layouts[t.dialogue.layoutId];if(!o)return;let i;t.dialogue.characterId&&(i=n.characters[t.dialogue.characterId]);let c={elements:o.elements},u=D(c,{dialogue:{character:{name:i?.name||""},text:t.dialogue.text}})?.elements;if(Array.isArray(u))for(let f of u)e.push(structuredClone(f));else u&&e.push(structuredClone(u))},Je=({elements:e,transitions:t},{presentationState:r,ui:n,variables:s})=>{if(r.layout){let i={elements:n.layouts[r.layout.layoutId].elements},a=D(i,{variables:s})?.elements;if(Array.isArray(a))for(let u of a){let f=structuredClone(u);f.children&&(f.children=f.children.map(p=>({...p,x:p.x||0,y:p.y||0}))),e.push(f)}else if(a){let u=structuredClone(a);u.children&&(u.children=u.children.map(f=>({...f,x:f.x||0,y:f.y||0}))),e.push(u)}}},Xe=({elements:e,transitions:t},{presentationState:r,assets:n,ui:s})=>{if(r.choices){let i={elements:s.layouts[r.choices.layoutId].elements},a=D(i,{choices:{items:r.choices.items}})?.elements;if(Array.isArray(a))for(let u of a)e.push(structuredClone(u));else a&&e.push(structuredClone(a))}},Ge=({elements:e},{presentationState:t,assets:r,resolveFile:n})=>{if(t.bgm){let s=r.audios[t.bgm.audioId];e.push({id:"bgm",type:"audio",url:n(s.fileId)})}},He=({elements:e},{presentationState:t,assets:r,resolveFile:n})=>{if(t.sfx){let s=t.sfx.items;for(let o of s){let i=r.audios[o.audioId];e.push({id:o.id,type:"audio",url:n(i.fileId)})}}},ue=[Ue,We,Be,Ye,Ke,Je,Xe,Ge,He];var de={};N(de,{applyAnimation:()=>nt,applyBackground:()=>Qe,applyBgm:()=>Ze,applyCharacter:()=>rt,applyChoices:()=>ot,applyCleanAll:()=>it,applyDialogue:()=>tt,applyLayout:()=>st,applySfx:()=>qe,applyVisual:()=>et,createInitialState:()=>Xt,default:()=>pe});var Qe=(e,t)=>{t.background&&(e.background={...t.background})},qe=(e,t)=>{t.sfx?e.sfx=t.sfx:e.sfx&&delete e.sfx},Ze=(e,t)=>{if(t.bgm){if(!t.bgm.audioId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},et=(e,t)=>{t.visual&&(e.visual=t.visual)},tt=(e,t)=>{t.dialogue&&(e.dialogue||(e.dialogue={}),Object.assign(e.dialogue,t.dialogue),t.dialogue.text&&delete e.dialogue.segments,t.dialogue.character&&!t.dialogue.character.characterName&&e.dialogue.character&&delete e.dialogue.character.characterName)},rt=(e,t)=>{if(t.character){if(!e.character){e.character=JSON.parse(JSON.stringify(t.character));return}Object.assign(e.character,t.character),e.character.items||(e.character.items=[]);for(let r=0;r<e.character.items.length;r++){let n=e.character.items[r],s=t.character.items.find(o=>o.id===n.id);s?(Object.assign(n,s),s.inAnimation||delete n.inAnimation,s.outAnimation||delete n.outAnimation):delete n.inAnimation}t.character.items.forEach(r=>{e.character.items.some(n=>n.id===r.id)||e.character.items.push(r)})}},nt=(e,t)=>{t.animation?e.animation=t.animation:e.animation&&delete e.animation},st=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},ot=(e,t)=>{t.choices?e.choices=t.choices:e.choices&&delete e.choices},it=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Xt=()=>({}),pe=[Qe,qe,Ze,et,tt,rt,nt,st,ot,it];var ye={};N(ye,{clearCurrentMode:()=>pr,clearPendingEffects:()=>or,createInitialState:()=>Gt,goToSectionScene:()=>lr,lineCompleted:()=>ir,loadVnData:()=>mr,nextLine:()=>cr,prevLine:()=>ar,saveVnData:()=>yr,selectAutoMode:()=>lt,selectAutoNext:()=>ut,selectCurrentPointer:()=>he,selectCurrentPreset:()=>Qt,selectCurrentPresetId:()=>ct,selectDialogueUIHidden:()=>er,selectHistory:()=>tr,selectPendingEffects:()=>Ht,selectPointerMode:()=>W,selectPointers:()=>qt,selectRuntimeState:()=>Zt,selectSaveData:()=>nr,selectSkipMode:()=>at,selectSpecificPointer:()=>rr,selectVariables:()=>sr,setPreset:()=>fr,startAutoMode:()=>ft,startSkipMode:()=>dt,stopAutoMode:()=>pt,stopSkipMode:()=>ht,toggleAutoMode:()=>dr,toggleSkipMode:()=>hr,updateVariable:()=>ur});var Gt=({sectionId:e,lineId:t,presetId:r,autoNext:n,saveData:s,variables:o})=>{let i={pendingEffects:[],variables:o,saveData:s,story:{lastLineAction:void 0,dialogueUIHidden:!1,currentPointer:"read",autoNext:n,autoMode:!1,skipMode:!1,pointers:{read:{presetId:r,sectionId:e,lineId:t},menu:{presetId:"3ijasdk3",sectionId:void 0,lineId:void 0},history:{presetId:r,sectionId:void 0,lineId:void 0,historyEntryIndex:void 0}},history:{entries:[]}}};return i.story.history.entries.push({sectionId:e}),i},Ht=({state:e})=>e.pendingEffects,he=({state:e})=>e.story.pointers[e.story.currentPointer],ct=({state:e})=>e.story.pointers[e.story.currentPointer].presetId,Qt=({state:e,projectDataStore:t})=>{let r=ct({state:e});return t.selectPreset(r)},at=({state:e})=>e.story.skipMode,lt=({state:e})=>e.story.autoMode,qt=({state:e})=>e.story.pointers,ut=({state:e})=>e.story.autoNext,Zt=({state:e})=>e.runtimeState,W=({state:e})=>e.story.currentPointer,er=({state:e})=>e.story.dialogueUIHidden,tr=({state:e})=>e.story.history,rr=({state:e,mode:t})=>e.story.pointers[t],nr=({state:e})=>e.saveData,sr=({state:e})=>e.variables,or=({state:e})=>{e.pendingEffects=[]},ir=({state:e,projectDataStore:t})=>{let r=lt(e),{pendingEffects:n}=e;if(r){n.push({name:"systemInstructions",options:{delay:1e3,systemInstructions:{nextLine:{forceSkipAutonext:!0}}}});return}if(at(e)){n.push({name:"systemInstructions",options:{delay:300,systemInstructions:{nextLine:{forceSkipAutonext:!0}}}});return}let o=ut(e);if(!o)return;let{nextTrigger:i,delay:c}=o;switch(i){case"onComplete":delete e.story.autoNext;break;case"fromComplete":n.push({name:"systemInstructions",options:{delay:c,systemInstructions:{nextLine:{forceSkipAutonext:!0}}}});break;case"manual":delete e.story.autoNext;break;default:delete e.story.autoNext;break}},cr=({state:e,projectDataStore:t})=>{let{pendingEffects:r}=e,n=he({state:e}),s=W({state:e}),o=t.selectSectionLines(n.sectionId),i=o.findIndex(a=>a.id===n.lineId),c=o[i+1];c&&(e.story.pointers[e.story.currentPointer].lineId=c.id,r.push({name:"render"}))},ar=({state:e,projectDataStore:t})=>{let r=W(e),n=he(e),s=t.selectSectionLines(n.sectionId),o=s.findIndex(c=>c.id===n.lineId),i=s[o-1];if(!i){if(r==="history"){if(e.story.historyEntryIndex>0)e.story.historyEntryIndex--;else return;e.story.pointers.history.sectionId=e.story.history.entries[e.story.historyEntryIndex].sectionId;let c=vnDataSelectors.selectSectionLines(vnData,systemState.story.pointers.history.sectionId);systemState.story.pointers.history.lineId=c[c.length-1].id,systemState.story.lastLineAction="prevLine",effects.push({name:"render"})}return}r==="read"&&(systemState.story.currentPointer="history",systemState.story.historyEntryIndex=systemState.story.history.entries.length-1),systemState.story.pointers.history.lineId=i.id,systemState.story.pointers.history.sectionId=n.sectionId,systemState.story.lastLineAction="prevLine",effects.push({name:"render"})},lr=({state:e,projectDataStore:t},r)=>{let{sectionId:n,sceneId:s,mode:o,presetId:i}=r,c=t.selectSectionLines(n);o&&(e.story.currentPointer=o);let a=W({state:e});a==="read"?e.story.history.entries.push({sectionId:n}):a==="history"&&n===e.story.history.entries[e.story.historyEntryIndex+1].sectionId&&e.story.historyEntryIndex++,e.story.pointers[a].sectionId=n,e.story.pointers[a].sceneId=s,e.story.pointers[a].lineId=c[0].id,e.story.autoNext=c[0].autoNext,i&&(e.story.pointers[a].presetId=i),e.pendingEffects.push({name:"render"})},ur=({payload:e,systemState:t,effects:r,vnData:n})=>{let{operations:s}=e;for(let a of s){let{variableId:u,op:f,value:p}=a;f==="set"?t.variables[u]=p:f==="increment"?t.variables[u]+=p:f==="decrement"&&(t.variables[u]-=p)}let o=vnDataSelectors.selectVariables(n),c=Object.keys(t.variables).filter(a=>o[a].persistence==="local").reduce((a,u)=>(a[u]=t.variables[u],a),{});r.push({name:"render"}),r.push({name:"updateLocalVariables",options:{variables:c}})},fr=({payload:e,systemState:t,effects:r})=>{t.story.pointers[t.story.currentPointer].presetId=e.presetId},pr=({payload:e,systemState:t,effects:r})=>{t.story.currentPointer=e.mode,r.push({name:"render"})},ft=({systemState:e,effects:t})=>{systemStateSelectors.selectSkipMode(e)&&(e.story.skipMode=!1),e.story.autoMode=!0,t.push({name:"cancelTimerEffect"}),t.push({name:"systemInstructions",options:{delay:1e3,systemInstructions:{nextLine:{forceSkipAutonext:!0}}}})},pt=({systemState:e,effects:t})=>{e.story.autoMode=!1,t.push({name:"cancelTimerEffect"})},dr=({systemState:e,effects:t})=>{systemStateSelectors.selectAutoMode(e)?pt({systemState:e,effects:t}):ft({systemState:e,effects:t})},dt=({systemState:e,effects:t})=>{systemStateSelectors.selectAutoMode(e)&&(e.story.autoMode=!1),e.story.skipMode=!0,t.push({name:"cancelTimerEffect"}),t.push({name:"systemInstructions",options:{delay:300,systemInstructions:{nextLine:{forceSkipAutonext:!0}}}})},ht=({systemState:e,effects:t})=>{e.story.skipMode=!1,t.push({name:"cancelTimerEffect"})},hr=({systemState:e,effects:t})=>{systemStateSelectors.selectSkipMode(e)?ht({systemState:e,effects:t}):dt({systemState:e,effects:t})};var yr=({systemState:e,effects:t,payload:r})=>{e.saveData.push({id:Date.now().toString().slice(4,10),slotIndex:r.slotIndex,pointer:systemStateSelectors.selectSpecificPointer(e,"read"),history:systemStateSelectors.selectHistory(e)}),t.push({name:"saveVnData",options:{saveData:[...e.saveData]}})},mr=({systemState:e,effects:t,payload:r})=>{let{slotIndex:n}=r,o=systemStateSelectors.selectSaveData(e).filter(a=>a.slotIndex===n);if(o.length===0){console.warn(`No save data found for slot index ${n}`);return}let{pointer:i,history:c}=o[o.length-1];e.story.currentPointer="read",e.story.pointers.read=i,e.story.history=c,t.push({name:"render"})};var me={};N(me,{createInitialState:()=>wr,selectAssets:()=>Ar,selectInitialIds:()=>yt,selectInitialPreset:()=>_r,selectLayout:()=>Sr,selectPreset:()=>Ir,selectPresets:()=>gr,selectScreen:()=>xr,selectSectionLines:()=>vr,selectUi:()=>br,selectVariables:()=>Er});var gr=e=>e.presets,_r=e=>e.presets[e.story.initialPresetId],Ir=(e,t)=>e.presets[t],xr=e=>e.screen,Ar=e=>e.assets,br=e=>e.ui,Sr=e=>e.layout,yt=e=>{let t=e.story.scenes[e.story.initialSceneId],r=t.sections[t.initialSectionId];return{sceneId:e.story.initialSceneId,sectionId:t.initialSectionId,presetId:e.story.initialPresetId,lineId:r.lines[0].id,autoNext:r.lines[0].autoNext}},Er=e=>e.variables||{},vr=(e,t,r)=>{let s=Object.values(e.story.scenes).flatMap(o=>Object.entries(o.sections).map(([i,c])=>({...c,id:i}))).find(o=>o.id===t);if(r){let o=s.lines.findIndex(i=>i.id===r);return s.lines.slice(0,o+1)}return s.lines},wr=e=>{let t=yt(e),{sectionId:r,lineId:n}=t;if(!r||!n)throw new Error("No initial sectionId found");return e};var{createInitialState:Pr}=de,{createInitialState:Or}=fe,{createInitialState:$r,...Nr}=ye,{createInitialState:dn,...kr}=me,mt=e=>re(e,kr),gt=(e,t)=>re($r({sectionId:e.sectionId,lineId:e.lineId,presetId:e.presetId,autoNext:e.autoNext,saveData:{},variables:{}}),Nr,{transformActionFirstArgument:r=>({state:r,projectDataStore:t}),transformSelectorFirstArgument:r=>({state:r,projectDataStore:t})}),ge=ne(Pr,pe),_e=ne(Or,ue);var Ie=class{_projectDataStore;_systemStore;_constructRenderState;_constructPresentationState;_applySystemInstruction;_eventCallback=()=>{};constructor(){}init=({projectData:t})=>{this._projectDataStore=mt(t);let r=this._projectDataStore.selectInitialIds();this._systemStore=gt(r,this._projectDataStore),this._constructPresentationState=ge,this._constructRenderState=_e,this._render()};onEvent=t=>(this._eventCallback=t,this);offEvent=()=>(this._eventCallback=()=>{},this);handleEvent=t=>{let{eventType:r,payload:n}=t,i=(this._systemStore.selectCurrentPreset()?.eventsMap||{})[r]?.systemActions,c=i?Object.keys(i)[0]:null;c&&typeof this._systemStore[c]=="function"?this._systemStore[c](n):c&&console.error(`Method ${c} not found on system store`),this._systemStore.selectPendingEffects().forEach(u=>{u.name==="render"&&(this._processSystemActions(),this._render())}),this._systemStore.clearPendingEffects()};_processSystemActions=()=>{let t=this._systemStore.selectCurrentPointer(),r=this._projectDataStore.selectSectionLines(t.sectionId,t.lineId);r.length&&r.forEach(n=>{n.system&&Object.keys(n.system).forEach(s=>{typeof this._systemStore[s]=="function"?this._systemStore[s](n.system[s]):console.error(`System action ${s} not found on system store`)})})};_render=()=>{let t=this._systemStore.selectCurrentPointer(),r=this._projectDataStore.selectSectionLines(t.sectionId,t.lineId);if(!r.length){console.warn(`No lines found for section: ${t.sectionId}, line: ${t.lineId}`);return}let n=r.map(i=>i.presentation||{}),s=this._constructPresentationState(n),o=this._constructRenderState({presentationState:s,screen:this._projectDataStore.selectScreen(),resolveFile:i=>`file:${i}`,assets:this._projectDataStore.selectAssets(),ui:this._projectDataStore.selectUi()});this._eventCallback({eventType:"render",payload:o})}},Cr=Ie;export{Cr as RouteEngine,ge as constructPresentationState,_e as constructRenderState};
1
+ var Gt=Object.defineProperty;var K=(e,t)=>{for(var r in t)Gt(e,r,{get:t[r],enumerable:!0})};var Ye=Symbol.for("immer-nothing"),Ue=Symbol.for("immer-draftable"),R=Symbol.for("immer-state");function S(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var J=Object.getPrototypeOf;function Y(e){return!!e&&!!e[R]}function W(e){return e?Ge(e)||Array.isArray(e)||!!e[Ue]||!!e.constructor?.[Ue]||le(e)||ue(e):!1}var Ht=Object.prototype.constructor.toString();function Ge(e){if(!e||typeof e!="object")return!1;let t=J(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Ht}function oe(e,t){ce(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function ce(e){let t=e[R];return t?t.type_:Array.isArray(e)?1:le(e)?2:ue(e)?3:0}function ge(e,t){return ce(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function He(e,t,r){let n=ce(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function Xt(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function le(e){return e instanceof Map}function ue(e){return e instanceof Set}function F(e){return e.copy_||e.base_}function Ie(e,t){if(le(e))return new Map(e);if(ue(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Ge(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[R];let s=Reflect.ownKeys(n);for(let i=0;i<s.length;i++){let o=s[i],a=n[o];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(n[o]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[o]})}return Object.create(J(e),n)}else{let n=J(e);if(n!==null&&r)return{...e};let s=Object.create(n);return Object.assign(s,e)}}function Ee(e,t=!1){return fe(e)||Y(e)||!W(e)||(ce(e)>1&&(e.set=e.add=e.clear=e.delete=Qt),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>Ee(n,!0))),e}function Qt(){S(2)}function fe(e){return Object.isFrozen(e)}var qt={};function U(e){let t=qt[e];return t||S(0,e),t}var Q;function Xe(){return Q}function Zt(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function je(e,t){t&&(U("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ve(e){_e(e),e.drafts_.forEach(er),e.drafts_=null}function _e(e){e===Q&&(Q=e.parent_)}function ze(e){return Q=Zt(Q,e)}function er(e){let t=e[R];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Ke(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[R].modified_&&(ve(t),S(4)),W(e)&&(e=se(t,e),t.parent_||ae(t,e)),t.patches_&&U("Patches").generateReplacementPatches_(r[R].base_,e,t.patches_,t.inversePatches_)):e=se(t,r,[]),ve(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ye?e:void 0}function se(e,t,r){if(fe(t))return t;let n=t[R];if(!n)return oe(t,(s,i)=>Je(e,n,t,s,i,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return ae(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let s=n.copy_,i=s,o=!1;n.type_===3&&(i=new Set(s),s.clear(),o=!0),oe(i,(a,l)=>Je(e,n,s,a,l,r,o)),ae(e,s,!1),r&&e.patches_&&U("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Je(e,t,r,n,s,i,o){if(Y(s)){let a=i&&t&&t.type_!==3&&!ge(t.assigned_,n)?i.concat(n):void 0,l=se(e,s,a);if(He(r,n,l),Y(l))e.canAutoFreeze_=!1;else return}else o&&r.add(s);if(W(s)&&!fe(s)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;se(e,s),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&ae(e,s)}}function ae(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Ee(t,r)}function tr(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Xe(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},s=n,i=xe;r&&(s=[n],i=q);let{revoke:o,proxy:a}=Proxy.revocable(s,i);return n.draft_=a,n.revoke_=o,a}var xe={get(e,t){if(t===R)return e;let r=F(e);if(!ge(r,t))return rr(e,r,t);let n=r[t];return e.finalized_||!W(n)?n:n===ye(e.base_,t)?(me(e),e.copy_[t]=be(n,e)):n},has(e,t){return t in F(e)},ownKeys(e){return Reflect.ownKeys(F(e))},set(e,t,r){let n=Qe(F(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let s=ye(F(e),t),i=s?.[R];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(Xt(r,s)&&(r!==void 0||ge(e.base_,t)))return!0;me(e),Ae(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return ye(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,me(e),Ae(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=F(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){S(11)},getPrototypeOf(e){return J(e.base_)},setPrototypeOf(){S(12)}},q={};oe(xe,(e,t)=>{q[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});q.deleteProperty=function(e,t){return q.set.call(this,e,t,void 0)};q.set=function(e,t,r){return xe.set.call(this,e[0],t,r,e[0])};function ye(e,t){let r=e[R];return(r?F(r):e)[t]}function rr(e,t,r){let n=Qe(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Qe(e,t){if(!(t in e))return;let r=J(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=J(r)}}function Ae(e){e.modified_||(e.modified_=!0,e.parent_&&Ae(e.parent_))}function me(e){e.copy_||(e.copy_=Ie(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var nr=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){let i=r;r=t;let o=this;return function(l=i,...c){return o.produce(l,u=>r.call(this,u,...c))}}typeof r!="function"&&S(6),n!==void 0&&typeof n!="function"&&S(7);let s;if(W(t)){let i=ze(this),o=be(t,void 0),a=!0;try{s=r(o),a=!1}finally{a?ve(i):_e(i)}return je(i,n),Ke(s,i)}else if(!t||typeof t!="object"){if(s=r(t),s===void 0&&(s=t),s===Ye&&(s=void 0),this.autoFreeze_&&Ee(s,!0),n){let i=[],o=[];U("Patches").generateReplacementPatches_(t,s,i,o),n(i,o)}return s}else S(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(o,...a)=>this.produceWithPatches(o,l=>t(l,...a));let n,s;return[this.produce(t,r,(o,a)=>{n=o,s=a}),n,s]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){W(e)||S(8),Y(e)&&(e=ir(e));let t=ze(this),r=be(e,void 0);return r[R].isManual_=!0,_e(t),r}finishDraft(e,t){let r=e&&e[R];(!r||!r.isManual_)&&S(9);let{scope_:n}=r;return je(n,t),Ke(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let s=t[r];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}r>-1&&(t=t.slice(r+1));let n=U("Patches").applyPatches_;return Y(e)?n(e,t):this.produce(e,s=>n(s,t))}};function be(e,t){let r=le(e)?U("MapSet").proxyMap_(e,t):ue(e)?U("MapSet").proxySet_(e,t):tr(e,t);return(t?t.scope_:Xe()).drafts_.push(r),r}function ir(e){return Y(e)||S(10,e),qe(e)}function qe(e){if(!W(e)||fe(e))return e;let t=e[R],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Ie(e,t.scope_.immer_.useStrictShallowCopy_)}else r=Ie(e,!0);return oe(r,(n,s)=>{He(r,n,qe(s))}),t&&(t.finalized_=!1),r}var T=new nr,we=T.produce,Xn=T.produceWithPatches.bind(T),Qn=T.setAutoFreeze.bind(T),qn=T.setUseStrictShallowCopy.bind(T),Zn=T.applyPatches.bind(T),ei=T.createDraft.bind(T),ti=T.finishDraft.bind(T);var Pe=(e,t,r={})=>{let n=structuredClone(e),s={},i={},{transformSelectorFirstArgument:o=l=>l,transformActionFirstArgument:a=l=>l}=r;for(let[l,c]of Object.entries(t))l!=="createInitialState"&&(l.startsWith("select")?s[l]=(...u)=>c(o(n),...u):i[l]=(...u)=>{n=we(n,p=>c(a(p),...u))});return{...s,...i}},ke=(e,t)=>r=>{let n=e(),s=Array.isArray(r)?r:[r];return we(n,i=>{s.forEach(o=>{t.forEach(a=>{a(i,o)})})})};var de=e=>{let t=window.atob(e.replace(/^data:image\/[a-z]+;base64,/,"")),r=t.length,n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=t.charCodeAt(s);return n.buffer};var Se={};K(Se,{addBackgrundOrCg:()=>dt,addBgm:()=>gt,addCharacters:()=>pt,addChoices:()=>mt,addDialogue:()=>yt,addGlobalAudios:()=>bt,addLayout:()=>_t,addModals:()=>At,addScreen:()=>ft,addSfx:()=>It,addVisuals:()=>ht,addVoice:()=>vt,createInitialState:()=>Nr,default:()=>Te});var d={LITERAL:0,VARIABLE:1,INTERPOLATION:2,FUNCTION:3,BINARY:4,UNARY:5,CONDITIONAL:6,LOOP:7,OBJECT:8,ARRAY:9,PARTIAL:10,PATH_REFERENCE:11},x={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 _=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 $e=e=>{if(!e||e.trim()==="")throw new _("Missing condition expression after '$if'");if(e.includes("===")||e.includes("!==")){let r=e.includes("===")?"==":"!=";throw new _(`Invalid comparison operator '${e.includes("===")?"===":"!=="}' - did you mean '${r}'? (got: '${e}')`)}let t=["<",">","<=",">=","==","!="];for(let r of t)if(e.trim().endsWith(r))throw new _(`Incomplete comparison expression - missing right operand (got: '${e}')`)},Ze=e=>{if(e.trim().endsWith(" in"))throw new _(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(!e.includes(" in "))throw new _(`Invalid loop syntax - missing 'in' keyword (got: '$for ${e}')`);let[t,r]=e.split(" in ");if(!r||r.trim()==="")throw new _(`Missing iterable expression after 'in' (got: '$for ${e}')`);if(t.includes(",")){let n=t.split(",").map(s=>s.trim());for(let s of n)if(!s)throw new _(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`)}else if(!t.trim())throw new _(`Invalid loop variable - variable name cannot be empty (got: '$for ${e}')`)};var et=(e,t,r=!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 n=typeof t;return r?new L(`Cannot iterate over non-array value in loop '${e}' - got ${n} instead`):new L(`Cannot iterate over non-array value (got: ${n}) at '$for ${e}'`)},tt=(e,t)=>{let r=t&&Object.keys(t).length>0?Object.keys(t).join(", "):"no custom functions provided";return new L(`Unknown function '${e}' (${r})`)};var or=(e,t,r={})=>{let n={},s={};r&&typeof r=="object"&&(r.functions!==void 0||r.partials!==void 0?(n=r.functions||{},s=r.partials||{}):typeof r=="object"&&(n=r));let o=A(e,{functions:n,partials:s},t,{});return o===void 0?{}:o},A=(e,t,r,n)=>{let s=t.functions||t;if(e.var&&!e.type)return k(e.var,r,n);if(e.type===d.LITERAL)return e.value;if(e.type===d.VARIABLE)return k(e.path,r,n);if(e.type===d.INTERPOLATION)return ar(e.parts,t,r,n);switch(e.type){case d.FUNCTION:return nt(e,t,r,n);case d.BINARY:return it(e,t,r,n);case d.UNARY:return ot(e,t,r,n);case d.CONDITIONAL:return lr(e,t,r,n);case d.LOOP:return hr(e,t,r,n);case d.OBJECT:return mr(e,t,r,n);case d.ARRAY:return gr(e,t,r,n);case d.PARTIAL:return Ir(e,t,r,n);case d.PATH_REFERENCE:return vr(e,t,r,n);default:throw new Error(`Unknown node type: ${e.type}`)}},rt=new Map,sr=e=>{let t=[],r="",n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="[")r&&(t.push({type:"property",value:r}),r=""),n=!0;else if(i==="]"){if(n&&r){let o=r.trim();if(/^\d+$/.test(o))t.push({type:"index",value:parseInt(o,10)});else if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")){let a=o.slice(1,-1);t.push({type:"property",value:a})}else t.push({type:"property",value:o});r=""}n=!1}else r+=i}return r&&t.push({type:"property",value:r}),t},k=(e,t,r)=>{if(!e)return;if(e in r)return r[e];let n=rt.get(e);if(!n){let i=[],o="",a=0;for(let l=0;l<e.length;l++){let c=e[l];c==="["?(a++,o+=c):c==="]"?(a--,o+=c):c==="."&&a===0?o&&(i.push(o),o=""):o+=c}o&&i.push(o),n=[];for(let l of i){let c=sr(l.trim());n.push(...c)}rt.set(e,n)}let s=t;for(let i=0;i<n.length;i++){let o=n[i];if(o.type==="property"&&o.value in r){s=r[o.value];continue}if(s==null)return;(o.type==="property"||o.type==="index")&&(s=s[o.value])}return s},ar=(e,t,r,n)=>{let s=[];for(let i of e)if(typeof i=="string")s.push(i);else{let o=A(i,t,r,n);s.push(o!=null?String(o):"")}return s.join("")},nt=(e,t,r,n)=>{let s=t.functions||t,i=s[e.name];if(!i)throw tt(e.name,s);let o=e.args.map(a=>A(a,t,r,n));return i(...o)},G=(e,t,r,n)=>{if(e.var&&!e.type)return k(e.var,r,n);switch(e.type){case d.VARIABLE:return k(e.path,r,n);case d.LITERAL:return e.value;case d.BINARY:return it(e,t,r,n);case d.UNARY:return ot(e,t,r,n);case d.FUNCTION:return nt(e,t,r,n);default:return A(e,t,r,n)}},it=(e,t,r,n)=>{if(e.op===x.AND||e.op===x.OR){let o=G(e.left,t,r,n),a=G(e.right,t,r,n);switch(e.op){case x.AND:return o&&a;case x.OR:return o||a}}let s=A(e.left,t,r,n),i=A(e.right,t,r,n);switch(e.op){case x.EQ:return s==i;case x.NEQ:return s!=i;case x.GT:return s>i;case x.LT:return s<i;case x.GTE:return s>=i;case x.LTE:return s<=i;case x.IN:return Array.isArray(i)?i.includes(s):!1;case x.ADD:if(typeof s!="number"||typeof i!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof s} + ${typeof i}`);return s+i;case x.SUBTRACT:if(typeof s!="number"||typeof i!="number")throw new L(`Arithmetic operations require numbers. Got ${typeof s} - ${typeof i}`);return s-i;default:throw new Error(`Unknown binary operator: ${e.op}`)}},ot=(e,t,r,n)=>{let s=e.op===Z.NOT?G(e.operand,t,r,n):A(e.operand,t,r,n);switch(e.op){case Z.NOT:return!s;default:throw new Error(`Unknown unary operator: ${e.op}`)}},cr=(e,t,r,n)=>{if(e.conditions.length===2&&e.conditions[1]===null){let s=e.conditions[0];if(s.type===d.VARIABLE)if(k(s.path,r,n)){let o=e.bodies[0];if(o.type===d.OBJECT&&o.properties.length<=5){let a={};for(let l of o.properties){let c=l.parsedKey?A(l.parsedKey,t,r,n):l.key,u=l.value;if(u.type===d.LITERAL)a[c]=u.value;else if(u.type===d.VARIABLE)a[c]=k(u.path,r,n);else if(u.type===d.INTERPOLATION){let f=[];for(let p of u.parts)if(typeof p=="string")f.push(p);else if(p.type===d.VARIABLE){let y=k(p.path,r,n);f.push(y!=null?String(y):"")}else{let y=A(p,t,r,n);f.push(y!=null?String(y):"")}a[c]=f.join("")}else a[c]=A(u,t,r,n)}return a}}else{let o=e.bodies[1];if(o.type===d.OBJECT&&o.properties.length<=5){let a={};for(let l of o.properties){let c=l.parsedKey?A(l.parsedKey,t,r,n):l.key,u=l.value;if(u.type===d.LITERAL)a[c]=u.value;else if(u.type===d.VARIABLE)a[c]=k(u.path,r,n);else if(u.type===d.INTERPOLATION){let f=[];for(let p of u.parts)if(typeof p=="string")f.push(p);else if(p.type===d.VARIABLE){let y=k(p.path,r,n);f.push(y!=null?String(y):"")}else{let y=A(p,t,r,n);f.push(y!=null?String(y):"")}a[c]=f.join("")}else a[c]=A(u,t,r,n)}return a}}}return null},lr=(e,t,r,n)=>{let s=cr(e,t,r,n);if(s!==null)return s;for(let i=0;i<e.conditions.length;i++){let o=e.conditions[i];if(o===null||G(o,t,r,n))return A(e.bodies[i],t,r,n)}return st},ur=(e,t)=>{let r=e.body,n=e.itemVar;if(r.type===d.CONDITIONAL&&r.conditions.length===1&&r.conditions[0].type===d.VARIABLE){let s=r.conditions[0].path,i=r.bodies[0];if(s.startsWith(n+".")){let o=s.substring(n.length+1);if(i.type===d.OBJECT&&i.properties.length<=5){for(let l of i.properties)if(l.parsedKey)return null;let a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c[o]){let u={};for(let f of i.properties){let p=f.key,y=f.value;if(y.type===d.LITERAL)u[p]=y.value;else if(y.type===d.VARIABLE){let h=y.path;if(h===n)u[p]=c;else if(h.startsWith(n+".")){let g=h.substring(n.length+1);u[p]=c[g]}else return null}else if(y.type===d.INTERPOLATION){let h=[],g=!0;for(let v of y.parts)if(typeof v=="string")h.push(v);else if(v.type===d.VARIABLE){let m=v.path;if(m===n)h.push(c!=null?String(c):"");else if(m.startsWith(n+".")){let I=m.substring(n.length+1),b=c[I];h.push(b!=null?String(b):"")}else{g=!1;break}}else{g=!1;break}if(!g)return null;u[p]=h.join("")}else return null}a.push(u)}}return a}}}return null},fr=(e,t)=>{let r=e.body,n=e.itemVar,s=ur(e,t);if(s!==null)return s;if(r.type===d.OBJECT&&r.properties.length<=5){for(let a of r.properties)if(a.parsedKey)return null;let i=[],o=!0;for(let a of r.properties){let l=a.key,c=a.value;if(c.type===d.LITERAL)i.push({key:l,type:"literal",value:c.value});else if(c.type===d.VARIABLE){let u=c.path;if(u===n)i.push({key:l,type:"item"});else if(u.startsWith(n+".")){let f=u.substring(n.length+1);if(!f.includes(".")&&!f.includes("["))i.push({key:l,type:"prop",prop:f});else{o=!1;break}}else{o=!1;break}}else if(c.type===d.INTERPOLATION&&c.parts.length===1){let u=c.parts[0];if(u.type===d.VARIABLE){let f=u.path;if(f===n)i.push({key:l,type:"item_string"});else if(f.startsWith(n+".")){let p=f.substring(n.length+1);if(!p.includes(".")&&!p.includes("["))i.push({key:l,type:"prop_string",prop:p});else{o=!1;break}}else{o=!1;break}}else{o=!1;break}}else{o=!1;break}}if(o){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 l=0;l<t.length;l++){let c=t[l];a[l]={id:c.id,title:c.title!=null?String(c.title):"",completed:c.completed}}else for(let l=0;l<t.length;l++){let c=t[l],u={};for(let f of i)if(f.type==="literal")u[f.key]=f.value;else if(f.type==="item")u[f.key]=c;else if(f.type==="prop")u[f.key]=c[f.prop];else if(f.type==="item_string")u[f.key]=c!=null?String(c):"";else if(f.type==="prop_string"){let p=c[f.prop];u[f.key]=p!=null?String(p):""}a[l]=u}return a}}return null},dr=(e,t,r,n,s)=>{let i=[],o=e.body;if(o.type===d.OBJECT&&o.fast!==!1){let a=e.itemVar,l=e.indexVar;for(let c=0;c<s.length;c++){let u=s[c],f={},p={...n,[a]:u,...l&&{[l]:c}};p.__paths__||(p.__paths__=n.__paths__||{});let y=e.iterable.path||"";if(n&&n.__paths__&&y){let h=y.split("."),g=h[0];g in n.__paths__&&(y=n.__paths__[g],h.length>1&&(y+="."+h.slice(1).join(".")))}p.__paths__={...p.__paths__,[a]:`${y}[${c}]`,...l&&{[l]:c}};for(let h of o.properties){let g=h.parsedKey?A(h.parsedKey,t,r,p):h.key,v=h.value;if(v.type===d.LITERAL)f[g]=v.value;else if(v.type===d.VARIABLE){let m=v.path;if(m===a)f[g]=u;else if(m===l)f[g]=c;else if(m.startsWith(a+".")){let I=m.substring(a.length+1);!I.includes(".")&&!I.includes("[")?f[g]=u[I]:f[g]=k(m,r,{...n,[a]:u,...l&&{[l]:c}})}else f[g]=k(m,r,{...n,[a]:u,...l&&{[l]:c}})}else if(v.type===d.INTERPOLATION){let m=[];for(let I of v.parts)if(typeof I=="string")m.push(I);else if(I.type===d.VARIABLE){let b=I.path,E;if(b===a)E=u;else if(b===l)E=c;else if(b.startsWith(a+".")){let w=b.substring(a.length+1);!w.includes(".")&&!w.includes("[")?E=u[w]:E=k(b,r,{...n,[a]:u,...l&&{[l]:c}})}else E=k(b,r,{...n,[a]:u,...l&&{[l]:c}});m.push(E!=null?String(E):"")}else{let b={...n,[a]:u,...l&&{[l]:c}},E=A(I,t,r,b);m.push(E!=null?String(E):"")}f[g]=m.join("")}else{let m={...n,[a]:u,...l&&{[l]:c}};f[g]=A(v,t,r,m)}}i.push(f)}return i}return null},pr=(e,t,r)=>{let n=e.body;if(n.type===d.OBJECT&&n.properties.length===1&&n.properties[0].key==="$if item.visible"){let i=n.properties[0].value;if(i.type===d.CONDITIONAL&&i.conditions.length===1&&i.conditions[0].type===d.VARIABLE&&i.conditions[0].path==="item.visible"){let o=i.bodies[0];if(o.type===d.OBJECT&&o.properties.length===2){let a=o.properties[0],l=o.properties[1];if(a.key==="id"&&a.value.type===d.VARIABLE&&a.value.path==="item.id"&&l.key==="$if item.highlighted"&&l.value.type===d.CONDITIONAL){let c=[];for(let u=0;u<t.length;u++){let f=t[u];if(f.visible){let p={id:f.id};f.highlighted?(p.highlight=!0,p.message=`This item is highlighted: ${f.name}`):(p.highlight=!1,p.message=f.name),c.push(p)}}return c}}}}return null},hr=(e,t,r,n)=>{let s=A(e.iterable,t,r,n);if(!Array.isArray(s)){let c,u=!1;if(e.iterable.type===d.FUNCTION){u=!0;let p=e.iterable.args.map(y=>y.type===d.LITERAL?typeof y.value=="string"?`'${y.value}'`:String(y.value):y.type===d.VARIABLE?y.path:y.type===d.FUNCTION?`${y.name}(...)`:"?").join(", ");c=`${e.iterable.name}(${p})`}else c=e.iterable.path||"undefined";let f=`${e.itemVar}${e.indexVar?`, ${e.indexVar}`:""} in ${c}`;throw et(f,s,u)}if(!e.indexVar){let c=pr(e,s,e.itemVar);if(c!==null)return c}if(!e.indexVar){let c=fr(e,s);if(c!==null)return c}let i=dr(e,t,r,n,s);if(i!==null)return i;let o=[],a=e.iterable.path||"";if(n&&n.__paths__&&a){let c=a.split("."),u=c[0];u in n.__paths__&&(a=n.__paths__[u],c.length>1&&(a+="."+c.slice(1).join(".")))}let l=!1;e.body.type===d.ARRAY&&(e.body.items.length<=1?l=!1:l=e.body._shouldPreserveArray??=e.body.items.some(c=>c.type===d.OBJECT&&c.properties.some(u=>u.key.startsWith("$if ")||u.key.startsWith("$when "))));for(let c=0;c<s.length;c++){let u=e.indexVar?{...n,[e.itemVar]:s[c],[e.indexVar]:c}:{...n,[e.itemVar]:s[c]};u.__paths__||(u.__paths__=n.__paths__||{}),u.__paths__={...u.__paths__,[e.itemVar]:`${a}[${c}]`},e.indexVar&&(u.__paths__[e.indexVar]=c);let f=A(e.body,t,r,u);Array.isArray(f)&&f.length===1&&!l?o.push(f[0]):o.push(f)}return o},yr=(e,t,r,n)=>{if(e.whenCondition)return null;if(e.properties.length===1){let s=e.properties[0],i=s.parsedKey?A(s.parsedKey,t,r,n):s.key,o=s.value;if(o.type===d.OBJECT&&o.properties.length<=10&&!o.whenCondition){let a={},l={},c=!0;for(let u of o.properties){let f=u.parsedKey?A(u.parsedKey,t,r,n):u.key,p=u.value;if(p.type===d.LITERAL)l[f]=p.value;else if(p.type===d.VARIABLE)l[f]=k(p.path,r,n);else if(p.type===d.INTERPOLATION){let y=[];for(let h of p.parts)if(typeof h=="string")y.push(h);else if(h.type===d.VARIABLE){let g=k(h.path,r,n);y.push(g!=null?String(g):"")}else{c=!1;break}if(!c)break;l[f]=y.join("")}else if(p.type===d.OBJECT&&p.properties.length<=5){let y={};for(let h of p.properties){let g=h.key,v=h.value;if(v.type===d.LITERAL)y[g]=v.value;else if(v.type===d.VARIABLE)y[g]=k(v.path,r,n);else if(v.type===d.INTERPOLATION){let m=[];for(let I of v.parts)if(typeof I=="string")m.push(I);else if(I.type===d.VARIABLE){let b=k(I.path,r,n);m.push(b!=null?String(b):"")}else{c=!1;break}if(!c)break;y[g]=m.join("")}else{c=!1;break}}if(!c)break;l[f]=y}else{c=!1;break}}if(c)return a[i]=l,a}}return null},mr=(e,t,r,n)=>{let s=t.functions||t;if(e.whenCondition&&!G(e.whenCondition,s,r,n))return;let i=yr(e,t,r,n);if(i!==null)return i;if(e.fast){let c={};for(let u of e.properties){let f=u.parsedKey?A(u.parsedKey,t,r,n):u.key,p=u.value;if(p.type===d.LITERAL)c[f]=p.value;else if(p.type===d.VARIABLE)c[f]=k(p.path,r,n);else if(p.type===d.INTERPOLATION){let y=[];for(let h of p.parts)if(typeof h=="string")y.push(h);else if(h.type===d.VARIABLE){let g=k(h.path,r,n);y.push(g!=null?String(g):"")}else{let g=A(h,t,r,n);y.push(g!=null?String(g):"")}c[f]=y.join("")}else c[f]=A(p,t,r,n)}return c}let o={},a=null,l=!1;for(let c of e.properties)if(!c.key.startsWith("$if ")&&!c.key.match(/^\$if\s+\w+.*:?$/)&&!c.key.startsWith("$elif")&&!c.key.startsWith("$else")&&!c.key.startsWith("$for ")){l=!0;break}for(let c of e.properties)if(c.key.startsWith("$if ")||c.key.match(/^\$if\s+\w+.*:?$/)){let u=A(c.value,t,r,n);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(o,u)}else if(c.key.startsWith("$for ")){if(e.properties.length===1)return A(c.value,t,r,n)}else{let u=c.value;if(u&&u.type===d.OBJECT&&u.properties){let f=u.properties.find(p=>p.key.startsWith("$for "));if(f){let p=A(f.value,t,r,n);p!==void 0&&(o[c.key]=p)}else{let p=A(c.value,t,r,n);p!==void 0&&(o[c.key]=p)}}else{let f=c.parsedKey?A(c.parsedKey,t,r,n):c.key,p=A(c.value,t,r,n);p!==void 0&&(o[f]=p)}}return o},st={},gr=(e,t,r,n)=>{let s=[];for(let i of e.items)if(i.type===d.LOOP){let o=A(i,t,r,n);Array.isArray(o)&&i.flatten!==!1?s.push(...o):s.push(o)}else{let o=A(i,t,r,n);o!==st&&o!==void 0&&s.push(o)}return s},Ir=(e,t,r,n)=>{let{name:s,data:i,whenCondition:o}=e,a=t.partials||{},l=t.functions||t;if(o&&!G(o,l,r,n))return;if(!a[s])throw new L(`Partial '${s}' is not defined`);let c=n._partialStack||[];if(c.includes(s))throw new L(`Circular partial reference detected: ${s}`);let u=a[s],f=r,p={...n,_partialStack:[...c,s]};if(n){f={...r};for(let y of Object.keys(n))y.startsWith("_")||(f[y]=n[y])}if(i){let y=A(i,t,r,n);f={...f,...y}}return A(u,t,f,p)},vr=(e,t,r,n)=>{let{path:s}=e,i=s.split("."),o=i[0],a=i.slice(1);if(!n||!(o in n))throw new L(`Path reference '#{${s}}' refers to '${o}' which is not a loop variable in the current scope`);if(n.__paths__||(n.__paths__={}),!(o in n.__paths__))throw new L(`Path reference '#{${s}}' cannot be resolved - path tracking may not be initialized properly`);let l=n.__paths__[o];if(typeof l=="number"){if(a.length>0)throw new L(`Path reference '#{${s}}' - cannot access properties on index variable '${o}'`);return String(l)}return a.length>0&&(l+="."+a.join(".")),l},Oe=or;var _r=/\$\{([^}]*)\}/g,Ar=/#\{([^}]*)\}/g,ct=(e,t={})=>{let r=e.match(/^(\w+)\((.*)\)$/);if(!r)return{isFunction:!1};let[,n,s]=r,i=br(s,t);return{isFunction:!0,type:d.FUNCTION,name:n,args:i}},br=(e,t={})=>e.trim()?Er(e).map(n=>xr(n.trim(),t)):[],Er=e=>{let t=[],r="",n=0,s=!1,i="";for(let o=0;o<e.length;o++){let a=e[o],l=o>0?e[o-1]:"";!s&&(a==='"'||a==="'")?(s=!0,i=a,r+=a):s&&a===i&&l!=="\\"?(s=!1,i="",r+=a):!s&&a==="("?(n++,r+=a):!s&&a===")"?(n--,r+=a):!s&&a===","&&n===0?(t.push(r),r=""):r+=a}return r&&t.push(r),t},xr=(e,t={})=>{if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:d.LITERAL,value:e.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(e))return{type:d.LITERAL,value:parseFloat(e)};if(e==="true")return{type:d.LITERAL,value:!0};if(e==="false")return{type:d.LITERAL,value:!1};if(e==="null")return{type:d.LITERAL,value:null};let r=ct(e,t);if(r.isFunction)return{type:r.type,name:r.name,args:r.args};let n=e.trim(),s=[{op:" + ",type:"ADD"},{op:" - ",type:"SUBTRACT"}],i=-1,o=null;for(let{op:a,type:l}of s){let c=0;for(;c<n.length;){let u=j(n.substring(c),a);if(u===-1)break;let f=c+u;f>i&&(i=f,o={op:a,type:l}),c=f+a.length}}if(i!==-1)try{return O(n,t)}catch{return{type:d.VARIABLE,path:n}}return{type:d.VARIABLE,path:n}},lt=/^\w+\(.*\)$/,wr=/\s[+\-*/%]\s|\|\||&&|\?\?|.*\?.*:/,Pr=e=>{if(!(!e||e.trim()===""||lt.test(e))&&wr.test(e))throw e.includes("?")&&e.includes(":")?new _(`Complex expressions not supported in variable replacements - consider calculating the value in your data instead. Offending expression: "${e}"`):e.includes("||")||e.includes("&&")||e.includes("??")?new _(`Logical operators not supported in variable replacements - consider calculating the value in your data instead (operators like ||, &&, ?? are not supported). Offending expression: "${e}"`):new _(`Arithmetic expressions not supported in variable replacements - consider calculating '${e}' in your data instead (expressions with +, -, *, /, % are not supported). Offending expression: "${e}"`)},at=e=>{let t=e.trim();if(lt.test(t))throw new _(`Functions are not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("["))throw new _(`Array indices not supported in path references - use simple variable names or properties. Offending expression: "#{${e}}"`);if(/[+\-*/%]/.test(t))throw new _(`Arithmetic expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(/\|\||&&/.test(t))throw new _(`Logical operators not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);if(t.includes("?")&&t.includes(":"))throw new _(`Complex expressions not supported in path references - path references can only refer to loop variables. Offending expression: "#{${e}}"`);return{type:d.PATH_REFERENCE,path:t}},ee=(e,t={})=>{let r=e.trim();Pr(r);let n=ct(r,t);if(n.isFunction)return{type:n.type,name:n.name,args:n.args};if(r.includes("[")&&!/[\s+\-*/%|&?:]/.test(r)){let s=0;for(let i of r)i==="["?s++:i==="]"&&s--;if(s!==0)throw new Error("Invalid array index syntax")}return{type:d.VARIABLE,path:r}},Le=(e,t={})=>{let r=e,n=[];(e.includes("\\${")||e.includes("\\#{"))&&(r=e.replace(/\\\\(\$\{[^}]*\})/g,"\\DOUBLE_ESC_VAR$1"),r=r.replace(/\\\\(#\{[^}]*\})/g,"\\DOUBLE_ESC_PATH$1"),r=r.replace(/\\(\$\{[^}]*\})/g,(c,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\(#\{[^}]*\})/g,(c,u)=>{let f=`__ESCAPED_${n.length}__`;return n.push(u),f}),r=r.replace(/\\DOUBLE_ESC_VAR/g,"\\"),r=r.replace(/\\DOUBLE_ESC_PATH/g,"\\"));let s=[...r.matchAll(_r)],i=[...r.matchAll(Ar)],o=[...s.map(c=>({match:c,type:"variable"})),...i.map(c=>({match:c,type:"pathref"}))].sort((c,u)=>c.match.index-u.match.index);if(o.length===0){let c=r;for(let u=0;u<n.length;u++)c=c.replace(`__ESCAPED_${u}__`,n[u]);return{type:d.LITERAL,value:c}}if(o.length===1&&o[0].match[0]===r&&n.length===0){let{match:c,type:u}=o[0];try{return u==="variable"?ee(c[1],t):at(c[1])}catch(f){if(f.message==="Invalid array index syntax")return{type:d.LITERAL,value:r};throw f}}let a=[],l=0;for(let{match:c,type:u}of o){let[f,p]=c,y=c.index;if(y>l){let h=r.substring(l,y);for(let g=0;g<n.length;g++)h=h.replace(`__ESCAPED_${g}__`,n[g]);h&&a.push(h)}try{let h;u==="variable"?h=ee(p.trim(),t):h=at(p.trim()),a.push(h)}catch(h){if(h.message==="Invalid array index syntax")a.push(f);else throw h}l=y+f.length}if(l<r.length){let c=r.substring(l);for(let u=0;u<n.length;u++)c=c.replace(`__ESCAPED_${u}__`,n[u]);c&&a.push(c)}return{type:d.INTERPOLATION,parts:a}};var V=(e,t)=>typeof e=="string"?Le(e,t):typeof e=="object"&&e!==null?Array.isArray(e)?kr(e,t):$r(e,t):{type:d.LITERAL,value:e},kr=(e,t)=>{let r=[],n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let a=Object.keys(i);if(a.length===1&&/^\$for(?::\w+)?\s/.test(a[0])){let l=Cr(a[0],i[a[0]],t);r.push(l),n=!0;continue}}let o=V(i,t);r.push(o),(o.type===d.FUNCTION||o.type===d.CONDITIONAL||o.type===d.LOOP||o.type===d.PARTIAL||o.type===d.OBJECT&&!o.fast||o.type===d.ARRAY&&!o.fast)&&(n=!0)}return{type:d.ARRAY,items:r,fast:!n}},$r=(e,t)=>{let r=[],n=!1,s=null,i=Object.entries(e),o=0;if(e.$partial!==void 0){if(typeof e.$partial!="string")throw new _("$partial value must be a string");if(e.$partial.trim()==="")throw new _("$partial value cannot be an empty string");let l=["$if","$elif","$else","$for"],c=[];for(let[m]of i)for(let I of l)if(m===I||m.startsWith(I+" ")||m.startsWith(I+"#")){c.push(I);break}if(c.length>0)throw new _(`Cannot use $partial with ${c.join(", ")} at the same level. Wrap $partial in a parent object if you need conditionals.`);let{$partial:u,$when:f,...p}=e,y={},h=!1;for(let[m,I]of Object.entries(p)){let b=m;(m.startsWith("\\$")||m.startsWith("$$"))&&(b=m.slice(1)),y[b]=I,h=!0}let g=null;if(h&&(g=V(y,t),g.type===d.OBJECT)){let m=!1;for(let I of g.properties)if(I.value.type===d.VARIABLE||I.value.type===d.INTERPOLATION||I.value.type===d.FUNCTION||I.value.type===d.CONDITIONAL||I.value.type===d.OBJECT&&!I.value.fast||I.value.type===d.ARRAY&&!I.value.fast){m=!0;break}m&&(g.fast=!1)}let v={type:d.PARTIAL,name:u,data:g};if(f!==void 0){let m;if(typeof f=="string"){if(f.trim()==="")throw new _("Empty condition expression after '$when'");m=O(f,t)}else m={type:d.LITERAL,value:f};v.whenCondition=m}return v}for(let[l,c]of i)if(l==="$when"){if(s!==null)throw new _("Multiple '$when' directives on the same object are not allowed");if(c==null)throw new _("Missing condition expression after '$when'");let u=typeof c=="string"?c:JSON.stringify(c);if(u.trim()==="")throw new _("Empty condition expression after '$when'");s=O(u,t),n=!0}else if(l.startsWith("$when#")||l.startsWith("$when "))throw new _("'$when' does not support ID syntax or inline conditions - use '$when' as a property");for(;o<i.length;){let[l,c]=i[o];if(l==="$when"){o++;continue}if(l.startsWith("$if ")||l.match(/^\$if#\w+\s/)||l.match(/^\$if\s+\w+.*:$/)){let u=Or(i,o,t);r.push({key:l,value:u.node}),n=!0,o=u.nextIndex}else if(/^\$for(?::\w+)?\s/.test(l)){let u=l.match(/^\$for(?::(\w+))?\s/)?.[1]||"",f=u?`:${u}`:"";throw new _(`$for loops must be inside arrays - use '- $for${f} item in items:' instead of '$for${f} item in items:'`)}else{if(l.startsWith("$elif ")||l.startsWith("$else"))throw new _(`'${l.split(" ")[0]}' without matching '$if'`);if(l==="$if"||l==="$if:")throw new _("Missing condition expression after '$if'");{let u=V(c,t);(u.type===d.FUNCTION||u.type===d.CONDITIONAL||u.type===d.PARTIAL||u.type===d.OBJECT&&!u.fast||u.type===d.ARRAY&&!u.fast)&&(n=!0);let f=Le(l,t),p={key:l,value:u};(f.type!==d.LITERAL||f.value!==l)&&(p.parsedKey=f),r.push(p),o++}}}let a={type:d.OBJECT,properties:r,fast:!n};return s&&(a.whenCondition=s),a},Or=(e,t,r={})=>{let n=[],s=[],i=t,[o,a]=e[i],l=null,c;if(o.startsWith("$if#")){let f=o.match(/^\$if#(\w+)\s+(.+)$/);if(f)l=f[1],c=f[2];else throw new _(`Invalid conditional syntax: ${o}`)}else c=o.substring(4),c.endsWith(":")&&(c=c.slice(0,-1).trim());$e(c);let u=O(c,r);for(n.push(u),s.push(V(a,r)),i++;i<e.length;){let[f,p]=e[i],y=!1,h;if(l?f.startsWith(`$elif#${l} `)?(h=f.substring(`$elif#${l} `.length),h.endsWith(":")&&(h=h.slice(0,-1).trim()),y=!0):(f===`$else#${l}`||f===`$else#${l}:`)&&(y=!0,h=null):f.startsWith("$elif ")?(h=f.substring(6),h.endsWith(":")&&(h=h.slice(0,-1).trim()),y=!0):(f==="$else"||f==="$else:")&&(y=!0,h=null),y){if(h===null)n.push(null);else{$e(h);let g=O(h,r);n.push(g)}if(s.push(V(p,r)),i++,h===null)break}else break}return{node:{type:d.CONDITIONAL,conditions:n,bodies:s,id:l},nextIndex:i}},O=(e,t={})=>{if(e=e.trim(),e.startsWith("(")&&e.endsWith(")")){let c=e.slice(1,-1),u=0,f=!0;for(let p=0;p<c.length;p++)if(c[p]==="("?u++:c[p]===")"&&u--,u<0){f=!1;break}if(f&&u===0)return O(c,t)}let r=j(e,"||");if(r!==-1)return{type:d.BINARY,op:x.OR,left:O(e.substring(0,r).trim(),t),right:O(e.substring(r+2).trim(),t)};let n=j(e,"&&");if(n!==-1)return{type:d.BINARY,op:x.AND,left:O(e.substring(0,n).trim(),t),right:O(e.substring(n+2).trim(),t)};let s=[{op:">=",type:x.GTE},{op:"<=",type:x.LTE},{op:"==",type:x.EQ},{op:"!=",type:x.NEQ},{op:">",type:x.GT},{op:"<",type:x.LT},{op:" in ",type:x.IN}];for(let{op:c,type:u}of s){let f=j(e,c);if(f!==-1)return{type:d.BINARY,op:u,left:O(e.substring(0,f).trim(),t),right:O(e.substring(f+c.length).trim(),t)}}let i=-1,o=null,a=[{op:" + ",type:x.ADD},{op:" - ",type:x.SUBTRACT}];for(let{op:c,type:u}of a){let f=0;for(;f<e.length;){let p=j(e.substring(f),c);if(p===-1)break;let y=f+p;y>i&&(i=y,o={op:c,type:u}),f=y+c.length}}if(i!==-1&&o)return{type:d.BINARY,op:o.type,left:O(e.substring(0,i).trim(),t),right:O(e.substring(i+o.op.length).trim(),t)};let l=[" * "," / "," % "];for(let c of l)if(j(e,c)!==-1)throw new _(`Arithmetic operations are not allowed in conditionals: "${c}"`);return e.startsWith("!")?{type:d.UNARY,op:Z.NOT,operand:O(e.substring(1).trim(),t)}:ut(e,t)},j=(e,t)=>{let r=0,n=0;for(;n<=e.length-t.length;){if(e[n]==="(")r++;else if(e[n]===")")r--;else if(r===0&&e.substring(n,n+t.length)===t)return n;n++}return-1},Lr=e=>{if(e=e.trim(),e==="true")return{type:d.LITERAL,value:!0};if(e==="false")return{type:d.LITERAL,value:!1};if(e==="null")return{type:d.LITERAL,value:null};if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return{type:d.LITERAL,value:e.slice(1,-1)};if(e==='""'||e==="''")return{type:d.LITERAL,value:""};if(e==="{}")return{type:d.LITERAL,value:{}};if(e==="[]")return{type:d.LITERAL,value:[]};let t=Number(e);return!isNaN(t)&&isFinite(t)?{type:d.LITERAL,value:t}:{type:d.VARIABLE,path:e}},ut=(e,t)=>{let r=e.trim();if(r.match(/^(\w+)\((.*)\)$/))return ee(r,t);let s=Lr(r);if(s.type===d.LITERAL)return s;if(/^[a-zA-Z_$][\w.$]*$/.test(r))return{type:d.VARIABLE,path:r};try{return ee(r,t)}catch(i){if(i.message&&i.message.includes("not supported"))return s;throw i}},Cr=(e,t,r)=>{let n=/^\$for(?::(\w+))?\s+(.+)$/,s=e.match(n);if(!s)throw new _(`Invalid loop syntax (got: '${e}')`);let i=s[1],o=s[2].trim();Ze(o);let a=o.match(/^(.+?)\s+in\s+(.+)$/);if(!a)throw new _(`Invalid loop syntax - missing 'in' keyword (got: '$for ${o}')`);let l=a[1].trim(),c=a[2].trim(),u,f=null;if(l.includes(",")){let h=l.split(",").map(g=>g.trim());if(h.length!==2)throw new _(`Invalid loop variables: ${l}. Expected format: "item" or "item, index"`);u=h[0],f=h[1]}else u=l;let p=ut(c,r),y=V(t,r);return{type:d.LOOP,itemVar:u,indexVar:f,iterable:p,body:y,flatten:i!=="nested"}};var Rr=(e,t={})=>{let{functions:r={}}=t;return V(e,r)},pe=Rr;var Ce={};K(Ce,{now:()=>Tr});var Tr=()=>Date.now();var Sr=(e,t,r={})=>{let{functions:n={},partials:s={}}=r,i={...Ce,...n},o=pe(e,{functions:i}),a={};for(let[l,c]of Object.entries(s))a[l]=pe(c,{functions:i});return Oe(o,t,{functions:i,partials:a})},M=Sr;var Re={objectValues:e=>Object.entries(e).map(([t,r])=>({id:t,...r}))},Nr=()=>({elements:[{id:"story",type:"container",x:0,y:0,children:[]}],transitions:[]}),ft=({elements:e},{presentationState:t,resources:r})=>{if(t.screen){let n=e.find(s=>s.id==="story");if(!n)return;if(t.screen.resourceId&&t.screen.resourceType==="layout"){let s=r.layouts[t.screen.resourceId];s&&n.children.unshift({id:"screen",type:"container",children:s.elements})}}},dt=({elements:e,transitions:t},{presentationState:r,resources:n,resolveFile:s})=>{if(r.background){let i=e.find(o=>o.id==="story");if(!i)return;if(r.background.resourceId&&r.background.resourceType==="image"){let o=n.images[r.background.resourceId];i.children.push({id:`bg-cg-${r.background.resourceId}`,type:"sprite",x:0,y:0,url:s(o.fileId)})}if(r.background.resourceId&&r.background.resourceType==="layout"){let o=n.layouts[r.background.resourceId];i.children.push({id:`bg-cg-${r.background.resourceId}`,type:"container",children:o.elements})}if(r.background.animations){if(r.background.animations.in){let o=r.background.animations.in.animationId,a=n.animations[o];a&&t.push({id:"bg-cg-animation-in",type:"keyframes",event:"add",elementId:`bg-cg-${r.background.resourceId}`,properties:a.properties})}if(r.background.animations.out){let o=r.background.animations.out.animationId,a=r.background.animations.out.resourceId,l=n.animations[o];l&&t.push({id:"bg-cg-animation-out",type:"keyframes",event:"remove",elementId:`bg-cg-${a}`,properties:l.properties})}if(r.background.animations.update){let o=r.background.animations.update.animationId,a=n.animations[o];a&&t.push({id:"bg-cg-animation-update",type:"keyframes",event:"update",elementId:`bg-cg-${r.background.resourceId}`,properties:a.properties})}}}},pt=({elements:e,transitions:t},{presentationState:r,resources:n,resolveFile:s})=>{if(r.character){let i=e.find(a=>a.id==="story");if(!i)return;let o=r.character.items||[];for(let a of o){let{transformId:l,sprites:c}=a;if(a.animations&&a.animations.out&&!c&&!l){let h=a.animations.out.animationId,g=n.animations[h];if(g){let v={id:"character-animation-out",type:"keyframes",event:"remove",elementId:`character-container-${a.id}`,properties:g.properties};t.push(v)}continue}if(!c||!l){console.warn("Character item missing sprites or transformId:",a);continue}let u=c.map(({imageId:h})=>h),f=n.transforms[l],p={type:"container",id:`character-container-${a.id}`,x:f.x,y:f.y,anchorX:f.anchorX,anchorY:f.anchorY,rotation:f.rotation,scaleX:f.scaleX,scaleY:f.scaleY,children:[]},y=[];Object.entries(n.characters).flatMap(([h,g])=>{let{sprites:v}=g;Object.entries(v).map(([m,I])=>{u.includes(m)&&y.push({partId:m,fileId:I.fileId})})});for(let h of y)p.children.push({type:"sprite",id:`${a.id}-${h.partId}`,url:s(h.fileId),x:0,y:0});if(i.children.push(p),a.animations){if(a.animations.in){let h=a.animations.in.animationId,g=n.animations[h];g&&t.push({id:"character-animation-in",type:"keyframes",event:"add",elementId:`character-container-${a.id}`,properties:g.properties})}if(a.animations.update){let h=a.animations.update.animationId,g=n.animations[h];if(g){let v={id:"character-animation-update",type:"keyframes",event:"update",elementId:`character-container-${a.id}`,properties:g.properties};t.push(v)}}}}}},ht=({elements:e,transitions:t},{presentationState:r,resources:n,resolveFile:s})=>{if(r.visual){let i=e.find(a=>a.id==="story");if(!i)return;let o=r.visual.items;for(let a of o){if(a.resourceId&&a.resourceType){let l;if(a.resourceType==="image")l=n.images[a.resourceId];else continue;if(l){let c=n.transforms[a.transformId];i.children.push({id:`visual-${a.id}`,type:"sprite",url:s(l.fileId),x:c.x,y:c.y,anchorX:c.anchorX,anchorY:c.anchorY,rotation:c.rotation,scaleX:c.scaleX,scaleY:c.scaleY})}}if(a.animations){if(a.animations.in){let l=a.animations.in.animationId||a.animations.in,c=n.animations[l];c&&t.push({id:`${a.id}-animation`,type:"keyframes",event:"add",elementId:`visual-${a.id}`,properties:c.properties})}if(a.animations.out){let l=a.animations.out.animationId||a.animations.out,c=n.animations[l];c&&t.push({id:`${a.id}-animation-2`,type:"keyframes",event:"remove",elementId:`visual-${a.id}`,properties:c.properties})}}}}},yt=({elements:e},{presentationState:t,resources:r,systemState:n,systemStore:s})=>{if(!t.dialogue||n?.dialogueUIHidden)return;let i=e.find(p=>p.id==="story");if(!i)return;let o=r.layouts[t.dialogue.layoutId];if(!o)return;let a;t.dialogue.characterId&&(a=r.characters[t.dialogue.characterId]),t.dialogue.character&&(a={...a,name:t.dialogue.character.name});let l={elements:o.elements},c={variables:n?.variables||{},saveDataArray:s.selectSaveDataPage({page:n?.variables.currentSavePageIndex,numberPerPage:6}),autoMode:s.selectAutoMode(),skipMode:s.selectSkipMode(),dialogue:{character:{name:a?.name||""},content:t.dialogue?.content||[],lines:t.dialogue?.lines||[]},currentLanguagePackId:s.selectCurrentLanguagePackId(),i18n:s.selectCurrentLanguagePackKeys()},u=M(l,c,{functions:Re});u=M(u,{i18n:s.selectCurrentLanguagePackKeys()});let f=u?.elements;if(Array.isArray(f))for(let p of f)i.children.push(structuredClone(p));else f&&i.children.push(structuredClone(f))},mt=({elements:e,transitions:t},{presentationState:r,resources:n,ui:s})=>{if(r.choice){let i=e.find(u=>u.id==="story");if(!i)return;let a={elements:n.layouts[r.choice.layoutId].elements},c=M(a,{choice:{items:r.choice.items}})?.elements;if(Array.isArray(c))for(let u of c)i.children.push(structuredClone(u));else c&&i.children.push(structuredClone(c))}},gt=({elements:e},{presentationState:t,resources:r,resolveFile:n})=>{if(t.bgm){let s=e.find(o=>o.id==="story");if(!s)return;let i=r.audio[t.bgm.audioId];s.children.push({id:"bgm",type:"audio",url:n(i.fileId),loop:i.loop??!0,volume:i.volume??.5,delay:i.delay})}},It=({elements:e},{presentationState:t,resources:r,resolveFile:n})=>{if(t.sfx){let s=e.find(o=>o.id==="story");if(!s)return;let i=t.sfx.items;for(let o of i){let a=r.audio[o.audioId];s.children.push({id:o.id,type:"audio",url:n(a.fileId),loop:o.loop??!1,volume:o.volume??.5,delay:o.delay})}}},vt=({elements:e},{presentationState:t,resolveFile:r})=>{if(!t.voice)return;let n=e.find(a=>a.id==="story");if(!n)return;let{fileId:s,volume:i,loop:o}=t.voice;n.children.push({id:`voice-${s}`,type:"audio",url:r(s),volume:i,loop:o})},_t=({elements:e,transitions:t},{presentationState:r,resources:n,resolveFile:s,systemState:i,systemStore:o})=>{if(r.layout){let a=e.find(h=>h.id==="story");if(!a)return;let l=n.layouts[r.layout.layoutId];if(!l)return;Array.isArray(l.transitions)&&l.transitions.forEach(h=>{t.push(h)});let c=h=>{let g={...h};if(h.url&&h.url.startsWith("file:")){let v=h.url.replace("file:","");g.url=s(v)}return h.children&&Array.isArray(h.children)&&(g.children=h.children.map(c)),g},u={id:`layout-${r.layout.layoutId}`,type:"container",x:0,y:0,children:l.elements||[]},f={variables:i?.variables||{},saveDataArray:o.selectSaveDataPage({page:i?.variables.currentSavePageIndex,numberPerPage:6}),autoMode:o.selectAutoMode(),skipMode:o.selectSkipMode(),globalAudios:o.selectGlobalAudios()||[],currentLanguagePackId:o.selectCurrentLanguagePackId(),i18n:o.selectCurrentLanguagePackKeys(),languagePacks:o.selectLanguagePacks()},p=M(u,f,{functions:Re});p=M(p,{i18n:o.selectCurrentLanguagePackKeys()});let y=h=>{let g={...h};if(h.url&&h.url.startsWith("file:")){let v=h.url.replace("file:","");g.url=s(v)}return h.children&&Array.isArray(h.children)&&(g.children=h.children.map(y)),g};a.children.push(y(p))}},At=({elements:e,transitions:t},{systemState:r,resources:n,resolveFile:s,systemStore:i})=>{let o=r.modes[r.currentMode].modals;o&&o.length>0&&o.forEach((a,l)=>{if(a.resourceType==="layout"){let c=n.layouts[a.resourceId];if(!c){console.warn(`Modal layout not found: ${a.resourceId}`);return}Array.isArray(c.transitions)&&c.transitions.forEach(m=>{t.push(m)});let u=m=>{let I={...m};if(m.url&&m.url.startsWith("file:")){let b=m.url.replace("file:","");I.url=s(b)}return m.children&&Array.isArray(m.children)&&(I.children=m.children.map(u)),I},f={id:`modal-${l}`,type:"container",x:0,y:0,children:c.elements||[]},p,y=!1;if(r.variables.activeGalleryIndex!==void 0){let m=r.variables.gallery.items;m&&Array.isArray(m)&&r.variables.activeGalleryIndex<m.length&&(p=m[r.variables.activeGalleryIndex]?.fileIds[r.variables.activeGalleryFileIndex]),r.variables.activeGalleryFileIndex<m[r.variables.activeGalleryIndex]?.fileIds.length-1?y=!1:y=!0}let h={variables:r.variables||{},currentActiveGalleryFileId:p,isLastFileIdIndex:y,saveDataArray:i.selectSaveDataPage({page:r?.variables.currentSavePageIndex,numberPerPage:6}),autoMode:i.selectAutoMode(),skipMode:i.selectSkipMode(),globalAudios:i.selectGlobalAudios()||[],historyDialogue:i.selectHistoryDialogue()||[],currentLanguagePackId:i.selectCurrentLanguagePackId(),i18n:i.selectCurrentLanguagePackKeys(),languagePacks:i.selectLanguagePacks()},g=M(f,h,{functions:Re});g=M(g,{i18n:i.selectCurrentLanguagePackKeys()});let v=m=>{let I={...m};if(m.url&&m.url.startsWith("file:")){let b=m.url.replace("file:","");I.url=s(b)}return m.children&&Array.isArray(m.children)&&(I.children=m.children.map(v)),I};e.push(v(g))}})},bt=({elements:e},{systemState:t,resources:r,resolveFile:n})=>{let s=t.globalAudios;s&&s.length>0&&s.forEach((i,o)=>{e.push({id:`global-audio-${o}-${i.audioId}`,type:"audio",url:n(i.fileId)})})},Te=[ft,dt,pt,ht,yt,mt,_t,gt,It,vt,At,bt];var te={};K(te,{animation:()=>Lt,background:()=>xt,bgm:()=>Pt,character:()=>Ot,choice:()=>Rt,cleanAll:()=>St,createInitialState:()=>Dr,default:()=>Ne,dialogue:()=>$t,layout:()=>Ct,screen:()=>Et,sfx:()=>wt,visual:()=>kt,voice:()=>Tt});var Et=(e,t)=>{t.screen&&(e.screen={...t.screen})},xt=(e,t)=>{t.background&&(e.background={...t.background})},wt=(e,t)=>{t.sfx?e.sfx=t.sfx:e.sfx&&delete e.sfx},Pt=(e,t)=>{if(t.bgm){if(!t.bgm.audioId){e.bgm=void 0;return}e.bgm={...t.bgm,loop:t.bgm.loop||t.bgm.loop===void 0}}},kt=(e,t)=>{t.visual&&(e.visual=t.visual)},$t=(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||(t.dialogue.mode==="adv"&&(e.dialogue={layoutId:t.dialogue.layoutId,content:void 0,characterId:void 0,mode:"adv"}),t.dialogue.mode==="nvl"&&e.dialogue?.mode!=="nvl"&&(e.dialogue={layoutId:t.dialogue.layoutId,lines:[],mode:"nvl"})),e.dialogue.mode==="adv"&&(e.dialogue.content=t.dialogue.content,e.dialogue.characterId=t.dialogue.characterId,e.dialogue.clear&&delete e.dialogue),t.dialogue.mode==="nvl"){t.dialogue.clear&&(e.dialogue.lines=[]),e.dialogue.lines.push({content:t.dialogue.content});return}},Ot=(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},Ct=(e,t)=>{t.layout?e.layout=t.layout:e.layout&&delete e.layout},Rt=(e,t)=>{t.choice?e.choice=t.choice:e.choice&&delete e.choice},Tt=(e,t)=>{t.voice?e.voice=t.voice:e.voice&&delete e.voice},St=(e,t)=>{t.cleanAll&&Object.keys(e).forEach(r=>{delete e[r]})},Dr=()=>({}),Ne=[St,Et,xt,wt,Pt,kt,$t,Ot,Lt,Ct,Rt,Tt];var ie={};K(ie,{addGlobalAudio:()=>_n,addModal:()=>bn,clearAllGlobalAudio:()=>An,clearCurrentMode:()=>un,clearLastModal:()=>En,clearPendingEffects:()=>nn,createInitialState:()=>Mr,handleCompleted:()=>wn,lineCompleted:()=>on,loadVnData:()=>In,nextConfig:()=>hn,nextLine:()=>sn,prevLine:()=>an,render:()=>vn,saveVnData:()=>gn,sectionTransition:()=>cn,selectAutoMode:()=>ne,selectCurrentLanguagePackId:()=>Qr,selectCurrentLanguagePackKeys:()=>Zr,selectCurrentPointer:()=>De,selectCurrentPreset:()=>Ur,selectCurrentPresetId:()=>Wr,selectCurrentReplayPointer:()=>Yr,selectDeviceVariables:()=>en,selectDialogueUIHidden:()=>Kr,selectGlobalAudios:()=>Xr,selectHistory:()=>Dt,selectHistoryDialogue:()=>tn,selectLanguagePacks:()=>qr,selectModals:()=>rn,selectNextConfig:()=>he,selectPendingEffects:()=>Br,selectPointerMode:()=>Nt,selectPointers:()=>jr,selectReplayPointer:()=>Jr,selectRuntimeState:()=>zr,selectSaveData:()=>Vt,selectSaveDataPage:()=>Gr,selectSkipMode:()=>re,selectSortedPendingEffects:()=>Fr,selectSpecificPointer:()=>Mt,selectState:()=>Vr,selectVariables:()=>Hr,setDeviceVariables:()=>mn,setLanguagePackId:()=>xn,setSaveData:()=>yn,startAutoMode:()=>Bt,startSkipMode:()=>Wt,stopAutoMode:()=>Ft,stopSkipMode:()=>Ut,toggleAutoMode:()=>fn,toggleDialogueUIHidden:()=>pn,toggleSkipMode:()=>dn,updateVariable:()=>ln});var Mr=({sectionId:e,lineId:t,saveData:r,variables:n,projectDataStore:s})=>{let i=s.selectI18n(),o={pendingEffects:[],variables:n,saveData:r||{},lastLineAction:void 0,dialogueUIHidden:!1,autoMode:!1,skipMode:!1,currentLanguagePackId:i?.defaultPackId,history:{entries:[]},globalAudios:[],historyEntryIndex:void 0,currentMode:"main",nextConfig:{},modes:{main:{currentPointer:"read",modals:[],read:{sectionId:e,lineId:t},history:{sectionId:void 0,lineId:void 0,historyEntryIndex:void 0}},replay:{currentPointer:"read",modals:[],read:{sectionId:void 0,lineId:void 0},history:{sectionId:void 0,lineId:void 0,historyEntryIndex:void 0}}}};return o.history.entries.push({sectionId:e}),o},Vr=({state:e})=>e,Br=({state:e})=>e.pendingEffects,Fr=({state:e})=>{let t=e.pendingEffects,r=new Map;return t.forEach(n=>{r.set(n.name,n)}),Array.from(r.values())},De=({state:e})=>{let t=e.modes[e.currentMode];return t[t.currentPointer]},Wr=({state:e})=>null,Ur=({state:e,projectDataStore:t})=>null,re=({state:e})=>e.skipMode,ne=({state:e})=>e.autoMode,jr=({state:e})=>e.modes[e.currentMode],he=({state:e})=>e.nextConfig,zr=({state:e})=>e.runtimeState,Nt=({state:e})=>e.modes[e.currentMode].currentPointer,Kr=({state:e})=>e.dialogueUIHidden,Dt=({state:e})=>e.history,Mt=({state:e,mode:t})=>e.modes[e.currentMode][t],Jr=({state:e,mode:t})=>e.modes.replay[t],Yr=({state:e})=>{let t=e.modes.replay;return t[t.currentPointer]},Vt=({state:e})=>e.saveData,Gr=({state:e},t)=>{let{page:r,numberPerPage:n}=t,s=r*n,i=[];for(let o=s;o<s+n;o++){let a=e.saveData[o]?{id:o,label:new Date(e.saveData[o].date).toISOString().split("T")[0],hasData:!0}:{id:o,label:"No Data",hasData:!1};i.push(a)}return i},Hr=({state:e})=>e.variables,Xr=({state:e})=>e.globalAudios,Qr=({state:e})=>e.currentLanguagePackId,qr=({state:e,projectDataStore:t})=>t.selectI18n().packs,Zr=({state:e,projectDataStore:t})=>{let r=t.selectI18n(),n=e.currentLanguagePackId;return r.packs[n].keys},en=({state:e,projectDataStore:t})=>{let r=t.selectVariables(),n=e.variables,s={};return Object.entries(r).forEach(([i,o])=>{o.persistence==="device"&&n.hasOwnProperty(i)&&(s[i]=n[i])}),s},tn=({state:e,projectDataStore:t})=>{let r=De({state:e}),{sectionId:n,lineId:s}=r;if(!n||!s)return[];let i=t.selectSectionLines(n),o=i.findIndex(c=>c.id===s);if(o===-1)return[];let a=i.slice(0,o+1),l=[];return a.forEach((c,u)=>{c.actions?.dialogue?.content&&Array.isArray(c.actions.dialogue.content)&&c.actions.dialogue.content.forEach(f=>{l.push({content:f.text})})}),l},rn=({state:e})=>e.modes[e.currentMode].modals,nn=({state:e})=>{e.pendingEffects=[]},on=({state:e,projectDataStore:t})=>{let r=ne(e),{pendingEffects:n}=e;if(r){n.push({name:"systemInstructions",options:{delay:1e3,systemInstructions:{nextLine:{forceSkipAutonext:!0}}}});return}if(re(e)){n.push({name:"systemInstructions",options:{delay:300,systemInstructions:{nextLine:{forceSkipAutonext:!0}}}});return}let i=he(e);if(!i||!i.auto)return;let{trigger:o,delay:a}=i.auto;switch(o){case"fromComplete":n.push({name:"systemInstructions",options:{delay:a,systemInstructions:{nextLine:{forceSkipAutonext:!0}}}});break;case"fromStart":delete e.nextConfig;break;default:delete e.nextConfig;break}},sn=({state:e,projectDataStore:t},r={})=>{let{pendingEffects:n}=e;if(e.dialogueUIHidden){e.dialogueUIHidden=!1,n.push({name:"render"});return}let{forceSkipAutonext:s=!1,targetMode:i}=r,o=i||e.currentMode,a=he({state:e});if(!s&&a&&a.manual&&(!a.manual.enabled||a.manual.requireComplete&&!e.lineComplete))return;let l=e.modes[o],c=l[l.currentPointer],u=t.selectSectionLines(c.sectionId),f=u.findIndex(y=>y.id===c.lineId),p=u[f+1];if(!p){e.skipMode=!1,e.autoMode=!1,n.push({name:"clearAutoNextTimer"}),n.push({name:"clearSkipNextTimer"});return}l[l.currentPointer].lineId=p.id,delete e.nextConfig,n.push({name:"render"})},an=({state:e,projectDataStore:t})=>{let r=Nt({state:e}),n=De({state:e}),s=t.selectSectionLines(n.sectionId),i=s.findIndex(a=>a.id===n.lineId),o=s[i-1];if(!o){if(r==="history"){if(e.historyEntryIndex>0)e.historyEntryIndex--;else return;e.modes[e.currentMode].history.sectionId=e.history.entries[e.historyEntryIndex].sectionId;let a=t.selectSectionLines(e.modes[e.currentMode].history.sectionId);e.modes[e.currentMode].history.lineId=a[a.length-1].id,e.lastLineAction="prevLine",e.pendingEffects.push({name:"render"})}return}r==="read"&&(e.modes[e.currentMode].currentPointer="history",e.historyEntryIndex=e.history.entries.length-1),e.modes[e.currentMode].history.lineId=o.id,e.modes[e.currentMode].history.sectionId=n.sectionId,e.lastLineAction="prevLine",e.pendingEffects.push({name:"render"})},cn=({state:e,projectDataStore:t},r)=>{let{sectionId:n,sceneId:s,mode:i,targetMode:o,endReplay:a}=r;if(e.currentMode==="replay"&&a){e.currentMode="main",e.modes.replay.currentPointer="read",e.modes.replay.modals=[],e.modes.replay.read={sectionId:void 0,lineId:void 0},e.modes.replay.history={sectionId:void 0,lineId:void 0,historyEntryIndex:void 0},e.pendingEffects.push({name:"render"});return}let l=t.selectSectionLines(n),c=o||(i&&e.modes[i]?i:e.currentMode);i&&e.modes[i]&&i!==e.currentMode&&!o&&(e.modes[i].modals=[]),o&&o!==e.currentMode?e.currentMode=o:i&&e.modes[i]&&i!==e.currentMode&&(e.currentMode=i),i&&!e.modes[i]&&(e.modes[c].currentPointer=i);let u=e.modes[c].currentPointer;u==="read"&&c===e.currentMode?e.history.entries.push({sectionId:n}):u==="history"&&n===e.history.entries[e.historyEntryIndex+1].sectionId&&e.historyEntryIndex++,e.modes[c][u].sectionId=n,e.modes[c][u].sceneId=s,e.modes[c][u].lineId=l[0].id,c===e.currentMode&&(e.nextConfig=l[0].actions?.nextConfig),e.pendingEffects.push({name:"render"})},ln=({state:e,projectDataStore:t},r)=>{let{operations:n}=r;for(let s of n){let{variableId:i,op:o,value:a}=s;if(o==="set")e.variables[i]=a;else if(o==="add")e.variables[i]=(e.variables[i]||0)+a;else if(o==="subtract")e.variables[i]=(e.variables[i]||0)-a;else if(o==="multiply")e.variables[i]=(e.variables[i]||0)*a;else if(o==="divide")e.variables[i]=(e.variables[i]||0)/a;else if(o==="increment"){let{max:l}=s,c=(e.variables[i]||0)+1;(l===void 0||c<=l)&&(e.variables[i]=(e.variables[i]||0)+1)}else if(o==="decrement"){let{min:l}=s,c=(e.variables[i]||0)-1;l!==void 0&&c>=l&&(e.variables[i]=(e.variables[i]||0)-1)}}e.pendingEffects.push({name:"render"}),e.pendingEffects.push({name:"saveVariables"})},un=({state:e},t)=>{e.modes[e.currentMode].currentPointer=t.mode,e.pendingEffects.push({name:"render"})},Bt=({state:e})=>{re({state:e})&&(e.skipMode=!1,e.pendingEffects.push({name:"clearSkipNextTimer"})),e.autoMode=!0,e.pendingEffects.push({name:"clearAutoNextTimer"}),e.pendingEffects.push({name:"startAutoNextTimer"}),e.pendingEffects.push({name:"render"})},Ft=({state:e})=>{e.autoMode=!1,e.pendingEffects.push({name:"render"}),e.pendingEffects.push({name:"clearAutoNextTimer"})},fn=({state:e})=>{ne({state:e})?Ft({state:e}):Bt({state:e})},Wt=({state:e})=>{ne({state:e})&&(e.autoMode=!1,e.pendingEffects.push({name:"clearAutoNextTimer"})),e.skipMode=!0,e.pendingEffects.push({name:"clearSkipNextTimer"}),e.pendingEffects.push({name:"startSkipNextTimer"}),e.pendingEffects.push({name:"render"})},Ut=({state:e})=>{e.skipMode=!1,e.pendingEffects.push({name:"clearSkipNextTimer"}),e.pendingEffects.push({name:"render"})},dn=({state:e})=>{re({state:e})?Ut({state:e}):Wt({state:e})},pn=({state:e})=>{e.dialogueUIHidden=!e.dialogueUIHidden,e.pendingEffects.push({name:"render"})},hn=({state:e},t)=>{e.nextConfig=t},yn=({state:e},t)=>{let{saveData:r}=t;e.saveData=r},mn=({state:e},t)=>{let{variables:r}=t;Object.entries(r).forEach(([n,s])=>{e.variables[n]=s})},gn=({state:e},t)=>{let{slotIndex:r}=t;e.saveData[r]={id:String(r),pointer:Mt({state:e,mode:"read"}),history:Dt({state:e}),date:Date.now()},e.pendingEffects.push({name:"saveVnData",options:{saveData:{...e.saveData},slotIndex:r}})},In=({state:e},t)=>{let{slotIndex:r}=t,s=Vt({state:e})[r];if(!s){console.warn(`No save data found for slot index ${r}`);return}let{pointer:i,history:o}=s;e.modes[e.currentMode].currentPointer="read",e.modes[e.currentMode].read=i,e.history=o,e.modes[e.currentMode].modals=[],e.pendingEffects.push({name:"render"})},vn=({state:e})=>{e.pendingEffects.push({name:"render"})},_n=({state:e},t)=>{let{fileId:r}=t;e.globalAudios.push({fileId:r}),e.pendingEffects.push({name:"render"})},An=({state:e})=>{e.globalAudios=[],e.pendingEffects.push({name:"render"})},bn=({state:e},t)=>{let r=e.currentMode;e.modes[r].modals.push({resourceId:t.resourceId,resourceType:"layout"}),e.pendingEffects.push({name:"render"})},En=({state:e},t)=>{let r=e.modes[e.currentMode].modals;r.length>0&&(r.pop(),e.pendingEffects.push({name:"render"}))},xn=({state:e},t)=>{let{languagePackId:r}=t;e.currentLanguagePackId=r,e.pendingEffects.push({name:"render"})},wn=({state:e})=>{let t=he({state:e});if(t){t.auto&&t.auto.trigger==="fromComplete"&&e.pendingEffects.push({name:"startTimer",options:{timerId:"nextConfig",payload:{nextLine:{forceSkipAutonext:!0}},delay:t.auto.delay??1e3}});return}ne({state:e})?e.pendingEffects.push({name:"startTimer",options:{timerId:"autoMode",payload:{nextLine:{forceSkipAutonext:!0}},delay:1e3}}):re({state:e})&&e.pendingEffects.push({name:"startTimer",options:{timerId:"skipMode",payload:{nextLine:{forceSkipAutonext:!0}},delay:300}})};var Me={};K(Me,{createInitialState:()=>Tn,selectI18n:()=>Ln,selectInitialIds:()=>jt,selectLayout:()=>On,selectResources:()=>kn,selectScreen:()=>Pn,selectSectionLines:()=>Rn,selectUi:()=>$n,selectVariables:()=>Cn});var Pn=e=>e.screen,kn=e=>e.resources,$n=e=>e.ui,On=e=>e.layout,Ln=e=>e.i18n,jt=e=>{let t=e.story.scenes[e.story.initialSceneId],r=t.sections[t.initialSectionId];return{sceneId:e.story.initialSceneId,sectionId:t.initialSectionId,lineId:r.lines[0].id}},Cn=e=>e.resources.variables||{},Rn=(e,t,r)=>{let s=Object.values(e.story.scenes).flatMap(i=>Object.entries(i.sections).map(([o,a])=>({...a,id:o}))).find(i=>i.id===t);if(r){let i=s.lines.findIndex(o=>o.id===r);return s.lines.slice(0,i+1)}return s.lines},Tn=e=>{let t=jt(e),{sectionId:r,lineId:n}=t;if(!r||!n)throw new Error("No initial sectionId found");return e};var{createInitialState:Sn}=te,{createInitialState:Nn}=Se,{createInitialState:Dn,...Mn}=ie,{createInitialState:Li,...Vn}=Me,zt=e=>Pe(e,Vn),Kt=(e,t)=>{let r=t.selectVariables(),n={};return Object.entries(r).forEach(([s,i])=>{i.hasOwnProperty("default")&&(n[s]=i.default)}),Pe(Dn({sectionId:e.sectionId,lineId:e.lineId,saveData:{},variables:n,projectDataStore:t}),Mn,{transformActionFirstArgument:s=>({state:s,projectDataStore:t}),transformSelectorFirstArgument:s=>({state:s,projectDataStore:t})})},Ve=ke(Sn,Ne),Be=ke(Nn,Te);var Bn=e=>{let t=new Map,r=new Set,n=(i,o)=>{let a={eventType:i,payload:o,timestamp:performance.now()};r.forEach(l=>l(a))},s=i=>{let o=i.deltaMS;t.forEach((a,l)=>{if(!a.paused&&(a.elapsed+=o,a.elapsed>=a.delay)){let c={id:l,elapsed:a.elapsed,delay:a.delay,type:a.type,triggerCount:a.triggerCount+1,overshoot:a.elapsed-a.delay,payload:a.payload};n(l,c),a.triggerCount++,a.type==="timeout"?t.delete(l):a.type==="interval"&&(a.elapsed=a.elapsed-a.delay)}})};return e.add(s),{setTimeout:(i,o,a)=>(t.has(i)&&console.warn(`Timer '${i}' already exists, replacing it`),t.set(i,{type:"timeout",delay:a,payload:o,elapsed:0,triggerCount:0,paused:!1}),i),setInterval:(i,o,a)=>(t.has(i)&&console.warn(`Timer '${i}' already exists, replacing it`),t.set(i,{type:"interval",delay:a,payload:o,elapsed:0,triggerCount:0,paused:!1}),i),clear:i=>{t.delete(i)},pause:i=>{let o=t.get(i);o&&(o.paused=!0)},resume:i=>{let o=t.get(i);o&&o.paused&&(o.paused=!1)},pauseAll:()=>{t.forEach((i,o)=>{i.paused=!0})},resumeAll:()=>{t.forEach((i,o)=>{i.paused=!1})},clearAll:()=>{t.clear()},onEvent:i=>(r.add(i),()=>r.delete(i)),getTimer:i=>{let o=t.get(i);return o?{id:i,...o}:null},getActiveTimers:()=>Array.from(t.keys()),destroy:()=>{t.clear(),r.clear(),e.remove(s)}}},Jt=Bn;var Fe={};K(Fe,{clearAutoNextTimer:()=>zn,clearSkipNextTimer:()=>Jn,render:()=>Fn,saveVariables:()=>Un,saveVnData:()=>Wn,startAutoNextTimer:()=>jn,startSkipNextTimer:()=>Kn,startTimer:()=>Yn});var Fn=({processAndRender:e})=>{e()},Wn=async({timer:e,localStorage:t,captureElement:r,loadAssets:n},s)=>{let{saveData:i,slotIndex:o}=s.options,a=structuredClone(i),l=await r("story");console.log("saveData",a),console.log("slotindex",o),a[o].image=l;let c={[`saveImage:${o}`]:{buffer:de(l),type:"image/png"}};await n(c),t.setItem("saveData",JSON.stringify(a)),e.setTimeout("saveData",{render:{}},100)},Un=({localStorage:e,systemStore:t})=>{let r=t.selectDeviceVariables();e.setItem("deviceVariables",JSON.stringify(r))},jn=({timer:e})=>{e.setTimeout("autoMode",{nextLine:{forceSkipAutonext:!0}},1e3)},zn=({timer:e})=>{e.clear("autoMode")},Kn=({timer:e})=>{e.setTimeout("skipMode",{nextLine:{forceSkipAutonext:!0}},300)},Jn=({timer:e})=>{e.clear("skipMode")},Yn=({timer:e},t)=>{let{timerId:r,payload:n,delay:s}=t.options;e.setTimeout(r,n,s)};var Yt=Object.keys(te).filter(e=>e!=="default"&&e!=="createInitialState"),Gn=Object.keys(ie).filter(e=>!e.startsWith("select")&&e!=="createInitialState");function We(){let e,t,r,n,s,i=()=>{},o,a,l=({projectData:v,ticker:m,captureElement:I,loadAssets:b})=>{e=zt(v);let E=e.selectInitialIds();t=Kt(E,e),n=Ve,r=Be,o=I,a=b,s=Jt(m),s.onEvent(c);let w=localStorage.getItem("saveData")||"{}",N=JSON.parse(w),H=Object.entries(N).filter(([$,P])=>!!P.image).map(([$,P])=>{let z=`saveImage:${$}`,X=de(P.image);return{[z]:{buffer:X,type:"image/png"}}}).reduce(($,P)=>({...$,...P}),{});b(H).then(()=>{console.log("All save images loaded")}).catch($=>{console.log("Error loading save images",$)}),t.setSaveData({saveData:N});let B=e.selectVariables(),C={};Object.entries(B).forEach(([$,P])=>{P.persistence==="device"&&P.hasOwnProperty("default")&&(C[$]=P.default)});let D=localStorage.getItem("deviceVariables");if(D)try{let $=JSON.parse(D);Object.entries($).forEach(([P,z])=>{B[P]&&B[P].persistence==="device"&&(C[P]=z)})}catch($){console.error("Failed to load device variables:",$)}Object.keys(C).length>0&&(t.setDeviceVariables({variables:C}),localStorage.setItem("deviceVariables",JSON.stringify(C))),y()},c=({eventType:v,payload:m})=>{Object.keys(m.payload).forEach(I=>{if(typeof t[I]=="function")t[I](m.payload[I]);else throw new Error(`System action ${I} not found on system store`)}),y()},u=v=>{i=v},f=()=>{i=()=>{}},p=v=>{let{payload:m}=v,I=m.actions;Object.keys(I).forEach(E=>{if(typeof t[E]=="function"){let w=I[E];E==="nextLine"&&!w.targetMode&&t.selectState().modes.replay.read.sectionId&&(w={...w,targetMode:"replay"}),t[E](w)}else throw new Error(`System action ${E} not found on system store`)});let b=t.selectSortedPendingEffects();if(b.length>0){let E={processAndRender:y,timer:s,localStorage,systemStore:t,captureElement:o,loadAssets:a};b.forEach(w=>{let N=Fe[w.name];if(!N)throw new Error(`No handler found for effect: ${w.name}`);N(E,w)}),t.clearPendingEffects()}},y=()=>{h(),g()},h=()=>{let v=t.selectCurrentPointer(),m=e.selectSectionLines(v.sectionId,v.lineId);m.length&&m.forEach(I=>{let b=I.actions||{};Gn.filter(w=>w in b).forEach(w=>{t[w](b[w])})})},g=()=>{let v=t.selectCurrentPointer(),m=e.selectSectionLines(v.sectionId,v.lineId);if(!m.length)throw new Error(`No lines found for section: ${v.sectionId}, line: ${v.lineId}`);let I=m.map(C=>{let D=C.actions||{},$={};return Object.keys(D).forEach(P=>{Yt.includes(P)&&($[P]=D[P])}),$}),b=n(I),E=null,w=t.selectCurrentReplayPointer();if(w&&w.sectionId&&w.lineId){let C=e.selectSectionLines(w.sectionId,w.lineId);if(C.length){let D=C.map($=>{let P=$.actions||{},z={};return Object.keys(P).forEach(X=>{Yt.includes(X)&&(z[X]=P[X])}),z});E=n(D)}}let N=t.selectState(),H=r({presentationState:b,systemState:N,systemStore:t,screen:e.selectScreen(),resolveFile:C=>`file:${C}`,resources:e.selectResources(),ui:e.selectUi(),i18n:e.selectI18n()}),B=null;if(E){let C=structuredClone(N);B=r({presentationState:E,systemState:C,systemStore:t,screen:e.selectScreen(),resolveFile:D=>`file:${D}`,resources:e.selectResources(),ui:e.selectUi(),i18n:e.selectI18n()})}console.log({systemState:N,mainPresentationState:b,mainRenderState:H,replayPresentationState:E,replayRenderState:B}),i({eventType:"render",payload:B||H})};return{init:l,onEvent:u,offEvent:f,handleEvent:p}}var Fi=We;export{Ve as constructPresentationState,Be as constructRenderState,Fi as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "route-engine-js",
3
- "version": "0.0.2-rc9",
3
+ "version": "0.0.4",
4
4
  "type": "module",
5
5
  "main": "dist/RouteEngine.js",
6
6
  "exports": {
@@ -14,15 +14,15 @@
14
14
  "test": "vitest run",
15
15
  "test:watch": "vitest",
16
16
  "build": "bun run esbuild.js",
17
- "lint": "bunx prettier src tests -c",
18
- "lint:fix": "bunx prettier src tests -w",
17
+ "lint": "bunx prettier src -c",
18
+ "lint:fix": "bunx prettier src -w",
19
19
  "coverage": "vitest run --coverage",
20
20
  "vt:generate": "bun run esbuild.js && rtgl vt generate --skip-screenshots",
21
21
  "serve": "bun run esbuild.js && bunx serve -p 3004 .rettangoli/vt/_site"
22
22
  },
23
23
  "dependencies": {
24
24
  "immer": "^10.1.1",
25
- "jempl": "^0.1.0",
25
+ "jempl": "1.0.0-rc1",
26
26
  "js-yaml": "^4.1.0",
27
27
  "puty": "^0.0.4-rc2"
28
28
  },