route-engine-js 0.3.4 → 0.3.6

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